# Graphics

---

# GPU Driver Developer's Guide

_Peios Kernel / Hardware and drivers / Graphics_

> Reference for GPU Driver Developer's Guide.

<a id="rst-gpu-driver-developer-s-guide"></a>

- [Introduction](</kernel/hardware/gpu/introduction.md>)
- [DRM Internals](</kernel/hardware/gpu/drm-internals.md>)
- [DRM Memory Management](</kernel/hardware/gpu/drm-mm.md>)
- [drm-kms](<https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/Documentation/gpu/drm-kms.rst?id=9021cc14f7d98b4a1d2c932f52c5343d4d0f6b92>)
- [Mode Setting Helper Functions](</kernel/hardware/gpu/drm-kms-helpers.md>)
- [Userland interfaces](</kernel/hardware/gpu/drm-uapi.md>)
- [DRM client usage stats](</kernel/hardware/gpu/drm-usage-stats.md>)
- [DRM Driver uAPI](</kernel/hardware/gpu/driver-uapi.md>)
- [Kernel clients](</kernel/hardware/gpu/drm-client.md>)
- [Long running workloads and compute](</kernel/hardware/gpu/drm-compute.md>)
- [GPU Driver Documentation](</kernel/hardware/gpu/drivers.md>)
- [Backlight support](</kernel/hardware/gpu/backlight.md>)
- [VGA Switcheroo](</kernel/hardware/gpu/vga-switcheroo.md>)
- [VGA Arbiter](</kernel/hardware/gpu/vgaarbiter.md>)
- [Automated testing of the DRM subsystem](<https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/Documentation/gpu/automated_testing.rst?id=9021cc14f7d98b4a1d2c932f52c5343d4d0f6b92>)
- [Misc DRM driver uAPI- and feature implementation guidelines](</kernel/hardware/gpu/implementation-guidelines.md>)
- [TODO list](</kernel/hardware/gpu/todo.md>)
- [GPU RFC Section](</kernel/hardware/gpu/rfc/index.md>)

---

# Arm Framebuffer Compression (AFBC)

_Peios Kernel / Hardware and drivers / Graphics_

> AFBC is a proprietary lossless image compression protocol and format. It provides fine-grained random access and minimizes the amount of data transferred between IP blocks.

<a id="rst-arm-framebuffer-compression-afbc"></a>

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

AFBC is a proprietary lossless image compression protocol and format. It provides fine-grained random access and minimizes the amount of data transferred between IP blocks.

AFBC can be enabled on drivers which support it via use of the AFBC format modifiers defined in drm_fourcc.h. See DRM_FORMAT_MOD_ARM_AFBC(\*).

All users of the AFBC modifiers must follow the usage guidelines laid out in this document, to ensure compatibility across different AFBC producers and consumers.

<a id="rst-components-and-ordering"></a>

## Components and Ordering

AFBC streams can contain several components - where a component corresponds to a color channel (i.e. R, G, B, X, A, Y, Cb, Cr). The assignment of input/output color channels must be consistent between the encoder and the decoder for correct operation, otherwise the consumer will interpret the decoded data incorrectly.

Furthermore, when the lossless colorspace transform is used (AFBC_FORMAT_MOD_YTR, which should be enabled for RGB buffers for maximum compression efficiency), the component order must be:

> - Component 0: R
>
> - Component 1: G
>
> - Component 2: B

The component ordering is communicated via the fourcc code in the fourcc:modifier pair. In general, component '0' is considered to reside in the least-significant bits of the corresponding linear format. For example, COMP(bits):

> - DRM_FORMAT_ABGR8888
>
>   - Component 0: R(8)
>
>   - Component 1: G(8)
>
>   - Component 2: B(8)
>
>   - Component 3: A(8)
>
> - DRM_FORMAT_BGR888
>
>   - Component 0: R(8)
>
>   - Component 1: G(8)
>
>   - Component 2: B(8)
>
> - DRM_FORMAT_YUYV
>
>   - Component 0: Y(8)
>
>   - Component 1: Cb(8, 2x1 subsampled)
>
>   - Component 2: Cr(8, 2x1 subsampled)

In AFBC, 'X' components are not treated any differently from any other component. Therefore, an AFBC buffer with fourcc DRM_FORMAT_XBGR8888 encodes with 4 components, like so:

> - DRM_FORMAT_XBGR8888
>
>   - Component 0: R(8)
>
>   - Component 1: G(8)
>
>   - Component 2: B(8)
>
>   - Component 3: X(8)

Please note, however, that the inclusion of a "wasted" 'X' channel is bad for compression efficiency, and so it's recommended to avoid formats containing 'X' bits. If a fourth component is required/expected by the encoder/decoder, then it is recommended to instead use an equivalent format with alpha, setting all alpha bits to '1'. If there is no requirement for a fourth component, then a format which doesn't include alpha can be used, e.g. DRM_FORMAT_BGR888.

<a id="rst-number-of-planes"></a>

## Number of Planes

Formats which are typically multi-planar in linear layouts (e.g. YUV 420), can be encoded into one, or multiple, AFBC planes. As with component order, the encoder and decoder must agree about the number of planes in order to correctly decode the buffer. The fourcc code is used to determine the number of encoded planes in an AFBC buffer, matching the number of planes for the linear (unmodified) format. Within each plane, the component ordering also follows the fourcc code:

For example:

> - DRM_FORMAT_YUYV: nplanes = 1
>
>   - Plane 0:
>
>     - Component 0: Y(8)
>
>     - Component 1: Cb(8, 2x1 subsampled)
>
>     - Component 2: Cr(8, 2x1 subsampled)
>
> - DRM_FORMAT_NV12: nplanes = 2
>
>   - Plane 0:
>
>     - Component 0: Y(8)
>
>   - Plane 1:
>
>     - Component 0: Cb(8, 2x1 subsampled)
>
>     - Component 1: Cr(8, 2x1 subsampled)

<a id="rst-cross-device-interoperability"></a>

## Cross-device interoperability

For maximum compatibility across devices, the table below defines canonical formats for use between AFBC-enabled devices. Formats which are listed here must be used exactly as specified when using the AFBC modifiers. Formats which are not listed should be avoided.


<table>
<caption>AFBC formats</caption>
<tbody>
<tr>
<td>


Fourcc code

</td>
<td>


Description

</td>
<td>


Planes/Components

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


DRM_FORMAT_ABGR2101010

</td>
<td>


10-bit per component RGB, with 2-bit alpha

</td>
<td>


- **Plane 0: 4 components**

  - Component 0: R(10)

  - Component 1: G(10)

  - Component 2: B(10)

  - Component 3: A(2)

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


DRM_FORMAT_ABGR8888

</td>
<td>


8-bit per component RGB, with 8-bit alpha

</td>
<td>


- **Plane 0: 4 components**

  - Component 0: R(8)

  - Component 1: G(8)

  - Component 2: B(8)

  - Component 3: A(8)

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


DRM_FORMAT_BGR888

</td>
<td>


8-bit per component RGB

</td>
<td>


- **Plane 0: 3 components**

  - Component 0: R(8)

  - Component 1: G(8)

  - Component 2: B(8)

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


DRM_FORMAT_BGR565

</td>
<td>


5/6-bit per component RGB

</td>
<td>


- **Plane 0: 3 components**

  - Component 0: R(5)

  - Component 1: G(6)

  - Component 2: B(5)

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


DRM_FORMAT_ABGR1555

</td>
<td>


5-bit per component RGB, with 1-bit alpha

</td>
<td>


- **Plane 0: 4 components**

  - Component 0: R(5)

  - Component 1: G(5)

  - Component 2: B(5)

  - Component 3: A(1)

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


DRM_FORMAT_VUY888

</td>
<td>


8-bit per component YCbCr 444, single plane

</td>
<td>


- **Plane 0: 3 components**

  - Component 0: Y(8)

  - Component 1: Cb(8)

  - Component 2: Cr(8)

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


DRM_FORMAT_VUY101010

</td>
<td>


10-bit per component YCbCr 444, single plane

</td>
<td>


- **Plane 0: 3 components**

  - Component 0: Y(10)

  - Component 1: Cb(10)

  - Component 2: Cr(10)

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


DRM_FORMAT_YUYV

</td>
<td>


8-bit per component YCbCr 422, single plane

</td>
<td>


- **Plane 0: 3 components**

  - Component 0: Y(8)

  - Component 1: Cb(8, 2x1 subsampled)

  - Component 2: Cr(8, 2x1 subsampled)

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


DRM_FORMAT_NV16

</td>
<td>


8-bit per component YCbCr 422, two plane

</td>
<td>


- **Plane 0: 1 component**

  - Component 0: Y(8)

- **Plane 1: 2 components**

  - Component 0: Cb(8, 2x1 subsampled)

  - Component 1: Cr(8, 2x1 subsampled)

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


DRM_FORMAT_Y210

</td>
<td>


10-bit per component YCbCr 422, single plane

</td>
<td>


- **Plane 0: 3 components**

  - Component 0: Y(10)

  - Component 1: Cb(10, 2x1 subsampled)

  - Component 2: Cr(10, 2x1 subsampled)

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


DRM_FORMAT_P210

</td>
<td>


10-bit per component YCbCr 422, two plane

</td>
<td>


- **Plane 0: 1 component**

  - Component 0: Y(10)

- **Plane 1: 2 components**

  - Component 0: Cb(10, 2x1 subsampled)

  - Component 1: Cr(10, 2x1 subsampled)

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


DRM_FORMAT_YUV420_8BIT

</td>
<td>


8-bit per component YCbCr 420, single plane

</td>
<td>


- **Plane 0: 3 components**

  - Component 0: Y(8)

  - Component 1: Cb(8, 2x2 subsampled)

  - Component 2: Cr(8, 2x2 subsampled)

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


DRM_FORMAT_YUV420_10BIT

</td>
<td>


10-bit per component YCbCr 420, single plane

</td>
<td>


- **Plane 0: 3 components**

  - Component 0: Y(10)

  - Component 1: Cb(10, 2x2 subsampled)

  - Component 2: Cr(10, 2x2 subsampled)

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


DRM_FORMAT_NV12

</td>
<td>


8-bit per component YCbCr 420, two plane

</td>
<td>


- **Plane 0: 1 component**

  - Component 0: Y(8)

- **Plane 1: 2 components**

  - Component 0: Cb(8, 2x2 subsampled)

  - Component 1: Cr(8, 2x2 subsampled)

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


DRM_FORMAT_P010

</td>
<td>


10-bit per component YCbCr 420, two plane

</td>
<td>


- **Plane 0: 1 component**

  - Component 0: Y(10)

- **Plane 1: 2 components**

  - Component 0: Cb(10, 2x2 subsampled)

  - Component 1: Cr(10, 2x2 subsampled)

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

---

# Automated testing of the DRM subsystem

_Peios Kernel / Hardware and drivers / Graphics_

> Making sure that changes to the core or drivers don't introduce regressions can be very time-consuming when lots of different hardware configurations need to be tested. Moreover, it isn't practical for each person interested in this…

<a id="rst-automated-testing-of-the-drm-subsystem"></a>

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

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

## Introduction

Making sure that changes to the core or drivers don't introduce regressions can be very time-consuming when lots of different hardware configurations need to be tested. Moreover, it isn't practical for each person interested in this testing to have to acquire and maintain what can be a considerable amount of hardware.

Also, it is desirable for developers to check for regressions in their code by themselves, instead of relying on the maintainers to find them and then reporting back.

There are facilities in gitlab.freedesktop.org to automatically test Mesa that can be used as well for testing the DRM subsystem. This document explains how people interested in testing it can use this shared infrastructure to save quite some time and effort.

<a id="rst-relevant-files"></a>

## Relevant files

<a id="rst-drivers-gpu-drm-ci-gitlab-ci-yml"></a>

### drivers/gpu/drm/ci/gitlab-ci.yml

This is the root configuration file for GitLab CI. Among other less interesting bits, it specifies the specific version of the scripts to be used. There are some variables that can be modified to change the behavior of the pipeline:

- **DRM\_CI\_PROJECT\_PATH**

  Repository that contains the Mesa software infrastructure for CI

- **DRM\_CI\_COMMIT\_SHA**

  A particular revision to use from that repository

- **UPSTREAM\_REPO**

  URL to git repository containing the target branch

- **TARGET\_BRANCH**

  Branch to which this branch is to be merged into

- **IGT\_VERSION**

  Revision of igt-gpu-tools being used, from [https://gitlab.freedesktop.org/drm/igt-gpu-tools](<https://gitlab.freedesktop.org/drm/igt-gpu-tools>)

<a id="rst-drivers-gpu-drm-ci-testlist-txt"></a>

### drivers/gpu/drm/ci/testlist.txt

IGT tests to be run on all drivers (unless mentioned in a driver's \*-skips.txt file, see below).

<a id="rst-drivers-gpu-drm-ci-driver-name-hw-revision-fails-txt"></a>

### drivers/gpu/drm/ci/$\{DRIVER\_NAME\}-$\{HW\_REVISION\}-fails.txt

Lists the known failures for a given driver on a specific hardware revision.

<a id="rst-drivers-gpu-drm-ci-driver-name-hw-revision-flakes-txt"></a>

### drivers/gpu/drm/ci/$\{DRIVER\_NAME\}-$\{HW\_REVISION\}-flakes.txt

Lists the tests that for a given driver on a specific hardware revision are known to behave unreliably. These tests won't cause a job to fail regardless of the result. They will still be run.

Each new flake entry must be associated with a link to the email reporting the bug to the author of the affected driver or the relevant GitLab issue. The entry must also include the board name or Device Tree name, the first kernel version affected, the IGT version used for tests, and an approximation of the failure rate.

They should be provided under the following format:



```text
# Bug Report: $LORE_URL_OR_GITLAB_ISSUE
# Board Name: broken-board.dtb
# Linux Version: 6.6-rc1
# IGT Version: 1.28-gd2af13d9f
# Failure Rate: 100
flaky-test
```

Use the appropriate link below to create a GitLab issue: amdgpu driver: [https://gitlab.freedesktop.org/drm/amd/-/issues](<https://gitlab.freedesktop.org/drm/amd/-/issues>) i915 driver: [https://gitlab.freedesktop.org/drm/i915/kernel/-/issues](<https://gitlab.freedesktop.org/drm/i915/kernel/-/issues>) msm driver: [https://gitlab.freedesktop.org/drm/msm/-/issues](<https://gitlab.freedesktop.org/drm/msm/-/issues>) xe driver: [https://gitlab.freedesktop.org/drm/xe/kernel/-/issues](<https://gitlab.freedesktop.org/drm/xe/kernel/-/issues>)

<a id="rst-drivers-gpu-drm-ci-driver-name-hw-revision-skips-txt"></a>

### drivers/gpu/drm/ci/$\{DRIVER\_NAME\}-$\{HW\_REVISION\}-skips.txt

Lists the tests that won't be run for a given driver on a specific hardware revision. These are usually tests that interfere with the running of the test list due to hanging the machine, causing OOM, taking too long, etc.

<a id="rst-how-to-enable-automated-testing-on-your-tree"></a>

## How to enable automated testing on your tree

1\. Create a Linux tree in [https://gitlab.freedesktop.org/](<https://gitlab.freedesktop.org/>) if you don't have one yet

2\. In your kernel repo's configuration (eg. [https://gitlab.freedesktop.org/janedoe/linux/-/settings/ci\_cd](<https://gitlab.freedesktop.org/janedoe/linux/-/settings/ci_cd>)), change the CI/CD configuration file from .gitlab-ci.yml to drivers/gpu/drm/ci/gitlab-ci.yml.

3\. Request to be added to the drm/ci-ok group so that your user has the necessary privileges to run the CI on [https://gitlab.freedesktop.org/drm/ci-ok](<https://gitlab.freedesktop.org/drm/ci-ok>)

4\. Next time you push to this repository, you will see a CI pipeline being created (eg. [https://gitlab.freedesktop.org/janedoe/linux/-/pipelines](<https://gitlab.freedesktop.org/janedoe/linux/-/pipelines>))

5\. The various jobs will be run and when the pipeline is finished, all jobs should be green unless a regression has been found.

6\. Warnings in the pipeline indicate that lockdep (see [Documentation/locking/lockdep-design.rst](/kernel/internals/locking/lockdep-design.md)) issues have been detected during the tests.

<a id="rst-how-to-update-test-expectations"></a>

## How to update test expectations

If your changes to the code fix any tests, you will have to remove one or more lines from one or more of the files in drivers/gpu/drm/ci/$\{DRIVER\_NAME\}\_\*\_fails.txt, for each of the test platforms affected by the change.

<a id="rst-how-to-expand-coverage"></a>

## How to expand coverage

If your code changes make it possible to run more tests (by solving reliability issues, for example), you can remove tests from the flakes and/or skips lists, and then the expected results if there are any known failures.

If there is a need for updating the version of IGT being used (maybe you have added more tests to it), update the IGT\_VERSION variable at the top of the gitlab-ci.yml file.

<a id="rst-how-to-test-your-changes-to-the-scripts"></a>

## How to test your changes to the scripts

For testing changes to the scripts in the drm-ci repo, change the DRM\_CI\_PROJECT\_PATH and DRM\_CI\_COMMIT\_SHA variables in drivers/gpu/drm/ci/gitlab-ci.yml to match your fork of the project (eg. janedoe/drm-ci). This fork needs to be in [https://gitlab.freedesktop.org/](<https://gitlab.freedesktop.org/>).

<a id="rst-how-to-incorporate-external-fixes-in-your-testing"></a>

## How to incorporate external fixes in your testing

Often, regressions in other trees will prevent testing changes local to the tree under test. These fixes will be automatically merged in during the build jobs from a branch in the target tree that is named as $\{TARGET\_BRANCH\}-external-fixes.

If the pipeline is not in a merge request and a branch with the same name exists in the local tree, commits from that branch will be merged in as well.

<a id="rst-how-to-deal-with-automated-testing-labs-that-may-be-down"></a>

## How to deal with automated testing labs that may be down

If a hardware farm is down and thus causing pipelines to fail that would otherwise pass, one can disable all jobs that would be submitted to that farm by editing the file at [https://gitlab.freedesktop.org/gfx-ci/lab-status/-/blob/main/lab-status.yml](<https://gitlab.freedesktop.org/gfx-ci/lab-status/-/blob/main/lab-status.yml>).

---

# Backlight support

_Peios Kernel / Hardware and drivers / Graphics_

> Reference for Backlight support.

<a id="rst-backlight-support"></a>


The backlight core supports implementing backlight drivers.

A backlight driver registers a driver using
[`devm_backlight_device_register()`](#c-devm_backlight_device_register). The properties of the backlight
driver such as type and max_brightness must be specified.
When the core detect changes in for example brightness or power state
the `update_status()` operation is called. The backlight driver shall
implement this operation and use it to adjust backlight.

Several sysfs attributes are provided by the backlight core:

- brightness         R/W, set the requested brightness level
- actual_brightness  RO, the brightness level used by the HW
- max_brightness     RO, the maximum  brightness level supported

See Documentation/ABI/stable/sysfs-class-backlight for the full list.

The backlight can be adjusted using the sysfs interface, and
the backlight driver may also support adjusting backlight using
a hot-key or some other platform or firmware specific way.

The driver must implement the `get_brightness()` operation if
the HW do not support all the levels that can be specified in
brightness, thus providing user-space access to the actual level
via the actual_brightness attribute.

When the backlight changes this is reported to user-space using
an uevent connected to the actual_brightness attribute.
When brightness is set by platform specific means, for example
a hot-key to adjust backlight, the driver must notify the backlight
core that brightness has changed using [`backlight_force_update()`](#c-backlight_force_update).

Display drives can control the backlight device's status using
`backlight_notify_blank()` and `backlight_notify_blank_all()`. If this
results in a change in the backlight state the functions call the
`update_status()` operation.



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

what method was used to update backlight

**Constants**

- `BACKLIGHT_UPDATE_HOTKEY`: The backlight was updated using a hot-key.
- `BACKLIGHT_UPDATE_SYSFS`: The backlight was updated using sysfs.

**Description**

A driver indicates the method (reason) used for updating the backlight
when calling [`backlight_force_update()`](#c-backlight_force_update).

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

the type of backlight control

**Constants**

- `BACKLIGHT_RAW`: The backlight is controlled using hardware registers.
- `BACKLIGHT_PLATFORM`: The backlight is controlled using a platform-specific interface.
- `BACKLIGHT_FIRMWARE`: The backlight is controlled using a standard firmware interface.
- `BACKLIGHT_TYPE_MAX`: Number of entries.

**Description**

The type of interface used to control the backlight.

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

backlight operations

**Definition**

```c
struct backlight_ops {
        unsigned int options;
    #define BL_CORE_SUSPENDRESUME   (1 << 0);
        int (*update_status)(struct backlight_device *);
        int (*get_brightness)(struct backlight_device *);
        bool (*controls_device)(struct backlight_device *bd, struct device *display_dev);
};
```

**Members**

- `options`: Configure how operations are called from the core.

  The options parameter is used to adjust the behaviour of the core.
  Set BL_CORE_SUSPENDRESUME to get the `update_status()` operation called
  upon suspend and resume.
- `update_status`: Operation called when properties have changed.

  Notify the backlight driver some property has changed.
  The update_status operation is protected by the update_lock.

  The backlight driver is expected to use [`backlight_is_blank()`](#c-backlight_is_blank)
  to check if the display is blanked and set brightness accordingly.
  `update_status()` is called when any of the properties has changed.

  RETURNS:

  0 on success, negative error code if any failure occurred.
- `get_brightness`: Return the current backlight brightness.

  The driver may implement this as a readback from the HW.
  This operation is optional and if not present then the current
  brightness property value is used.

  RETURNS:

  A brightness value which is 0 or a positive number.
  On failure a negative error code is returned.
- `controls_device`: Check against the display device

  Check if the backlight controls the given display device. This
  operation is optional and if not implemented it is assumed that
  the display is always the one controlled by the backlight.

  RETURNS:

  If display_dev is NULL or display_dev matches the device controlled by
  the backlight, return true. Otherwise return false.

**Description**

The backlight operations are specified when the backlight device is registered.

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

backlight properties

**Definition**

```c
struct backlight_properties {
        int brightness;
        int max_brightness;
        int power;
    #define BACKLIGHT_POWER_ON              (0);
    #define BACKLIGHT_POWER_OFF             (4);
    #define BACKLIGHT_POWER_REDUCED         (1);
        enum backlight_type type;
        unsigned int state;
    #define BL_CORE_SUSPENDED       (1 << 0);
    #define BL_CORE_FBBLANK         (1 << 1);
        enum backlight_scale scale;
};
```

**Members**

- `brightness`: The current brightness requested by the user.

  The backlight core makes sure the range is (0 to max_brightness)
  when the brightness is set via the sysfs attribute:
  /sys/class/backlight/\<backlight>/brightness.

  This value can be set in the backlight_properties passed
  to [`devm_backlight_device_register()`](#c-devm_backlight_device_register) to set a default brightness
  value.
- `max_brightness`: The maximum brightness value.

  This value must be set in the backlight_properties passed to
  [`devm_backlight_device_register()`](#c-devm_backlight_device_register) and shall not be modified by the
  driver after registration.
- `power`: The current power mode.

  User space can configure the power mode using the sysfs
  attribute: /sys/class/backlight/\<backlight>/bl_power
  When the power property is updated `update_status()` is called.

  The possible values are: (0: full on, 4: full off), see
  BACKLIGHT_POWER constants.

  When the backlight device is enabled, **power** is set to
  BACKLIGHT_POWER_ON. When the backlight device is disabled,
  **power** is set to BACKLIGHT_POWER_OFF.
- `type`: The type of backlight supported.

  The backlight type allows userspace to make appropriate
  policy decisions based on the backlight type.

  This value must be set in the backlight_properties
  passed to [`devm_backlight_device_register()`](#c-devm_backlight_device_register).
- `state`: The state of the backlight core.

  The state is a bitmask. BL_CORE_FBBLANK is set when the display
  is expected to be blank. BL_CORE_SUSPENDED is set when the
  driver is suspended.

  backlight drivers are expected to use [`backlight_is_blank()`](#c-backlight_is_blank)
  in their `update_status()` operation rather than reading the
  state property.

  The state is maintained by the core and drivers may not modify it.
- `scale`: The type of the brightness scale.

**Description**

This structure defines all the properties of a backlight.

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

backlight device data

**Definition**

```c
struct backlight_device {
    struct backlight_properties props;
    struct mutex update_lock;
    struct mutex ops_lock;
    const struct backlight_ops *ops;
    struct list_head entry;
    struct device dev;
    int use_count;
};
```

**Members**

- `props`: Backlight properties
- `update_lock`: The lock used when calling the `update_status()` operation.

  update_lock is an internal backlight lock that serialise access
  to the `update_status()` operation. The backlight core holds the update_lock
  when calling the `update_status()` operation. The update_lock shall not
  be used by backlight drivers.
- `ops_lock`: The lock used around everything related to backlight_ops.

  ops_lock is an internal backlight lock that protects the ops pointer
  and is used around all accesses to ops and when the operations are
  invoked. The ops_lock shall not be used by backlight drivers.
- `ops`: Pointer to the backlight operations.

  If ops is NULL, the driver that registered this device has been unloaded,
  and if `class_get_devdata()` points to something in the body of that driver,
  it is also invalid.
- `entry`: List entry of all registered backlight devices
- `dev`: Parent device.
- `use_count`: The number of unblanked displays.

**Description**

This structure holds all data required by a backlight device.

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

```c
int backlight_update_status(struct backlight_device *bd)
```

force an update of the backlight device status

**Parameters**

- `struct backlight_device *bd`: the backlight device

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

```c
int backlight_enable(struct backlight_device *bd)
```

Enable backlight

**Parameters**

- `struct backlight_device *bd`: the backlight device to enable

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

```c
int backlight_disable(struct backlight_device *bd)
```

Disable backlight

**Parameters**

- `struct backlight_device *bd`: the backlight device to disable

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

```c
bool backlight_is_blank(const struct backlight_device *bd)
```

Return true if display is expected to be blank

**Parameters**

- `const struct backlight_device *bd`: the backlight device

**Description**

Display is expected to be blank if any of these is true:

```text
1) if power in not UNBLANK
2) if state indicate BLANK or SUSPENDED
```

Returns true if display is expected to be blank, false otherwise.

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

```c
int backlight_get_brightness(const struct backlight_device *bd)
```

Returns the current brightness value

**Parameters**

- `const struct backlight_device *bd`: the backlight device

**Description**

Returns the current brightness value, taking in consideration the current
state. If [`backlight_is_blank()`](#c-backlight_is_blank) returns true then return 0 as brightness
otherwise return the current brightness property value.

Backlight drivers are expected to use this function in their `update_status()`
operation to get the brightness value.

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

```c
void * bl_get_data(struct backlight_device *bl_dev)
```

access devdata

**Parameters**

- `struct backlight_device *bl_dev`: pointer to backlight device

**Description**

When a backlight device is registered the driver has the possibility
to supply a void * devdata. [`bl_get_data()`](#c-bl_get_data) return a pointer to the
devdata.

pointer to devdata stored while registering the backlight device.



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

```c
void backlight_force_update(struct backlight_device *bd, enum backlight_update_reason reason)
```

tell the backlight subsystem that hardware state has changed

**Parameters**

- `struct backlight_device *bd`: the backlight device to update
- `enum backlight_update_reason reason`: reason for update

**Description**

Updates the internal state of the backlight in response to a hardware event,
and generates an uevent to notify userspace. A backlight driver shall call
[`backlight_force_update()`](#c-backlight_force_update) when the backlight is changed using, for example,
a hot-key. The updated brightness is read using `get_brightness()` and the
brightness value is reported using an uevent.

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

```c
struct backlight_device * backlight_device_get_by_name(const char *name)
```

Get backlight device by name

**Parameters**

- `const char *name`: Device name

**Description**

This function looks up a backlight device by its name. It obtains a reference
on the backlight device and it is the caller's responsibility to drop the
reference by calling [`put_device()`](/kernel/hardware/driver-api/fundamentals/infrastructure.md#c-put_device).

**Return**

A pointer to the backlight device if found, otherwise NULL.

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

```c
struct backlight_device * devm_backlight_device_register(struct device *dev, const char *name, struct device *parent, void *devdata, const struct backlight_ops *ops, const struct backlight_properties *props)
```

register a new backlight device

**Parameters**

- `struct device *dev`: the device to register
- `const char *name`: the name of the device
- `struct device *parent`: a pointer to the parent device (often the same as **dev**)
- `void *devdata`: an optional pointer to be stored for private driver use
- `const struct backlight_ops *ops`: the backlight operations structure
- `const struct backlight_properties *props`: the backlight properties

**Description**

Creates and registers new backlight device. When a backlight device
is registered the configuration must be specified in the **props**
parameter. See description of [`backlight_properties`](#c-struct-backlight_properties).

struct backlight on success, or an ERR_PTR on error

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

```c
void devm_backlight_device_unregister(struct device *dev, struct backlight_device *bd)
```

unregister backlight device

**Parameters**

- `struct device *dev`: the device to unregister
- `struct backlight_device *bd`: the backlight device to unregister

**Description**

Deallocates a backlight allocated with [`devm_backlight_device_register()`](#c-devm_backlight_device_register).
Normally this function will not need to be called and the resource management
code will ensure that the resources are freed.

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

```c
struct backlight_device * of_find_backlight_by_node(struct device_node *node)
```

find backlight device by device-tree node

**Parameters**

- `struct device_node *node`: device-tree node of the backlight device

**Description**

Returns a pointer to the backlight device corresponding to the given DT
node or NULL if no such backlight device exists or if the device hasn't
been probed yet.

This function obtains a reference on the backlight device and it is the
caller's responsibility to drop the reference by calling [`put_device()`](/kernel/hardware/driver-api/fundamentals/infrastructure.md#c-put_device) on
the backlight device's .dev field.

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

```c
struct backlight_device * devm_of_find_backlight(struct device *dev)
```

find backlight for a device

**Parameters**

- `struct device *dev`: the device

**Description**

This function looks for a property named 'backlight' on the DT node
connected to **dev** and looks up the backlight device. The lookup is
device managed so the reference to the backlight device is automatically
dropped on driver detach.

A pointer to the backlight device if found.
Error pointer -EPROBE_DEFER if the DT property is set, but no backlight
device is found. NULL if there's no backlight property.

---

# DRM Driver uAPI

_Peios Kernel / Hardware and drivers / Graphics_

> Reference for DRM Driver uAPI.

<a id="rst-drm-driver-uapi"></a>

<a id="rst-drm-i915-uapi"></a>

## drm/i915 uAPI


**uevents generated by i915 on its device node**

- I915_L3_PARITY_UEVENT - Generated when the driver receives a parity mismatch

  event from the GPU L3 cache. Additional information supplied is ROW,
  BANK, SUBBANK, SLICE of the affected cacheline. Userspace should keep
  track of these events, and if a specific cache-line seems to have a
  persistent error, remap it with the L3 remapping tool supplied in
  intel-gpu-tools.  The value supplied with the event is always 1.

- I915_ERROR_UEVENT - Generated upon error detection, currently only via

  hangcheck. The error detection event is a good indicator of when things
  began to go badly. The value supplied with the event is a 1 upon error
  detection, and a 0 upon reset completion, signifying no more error
  exists. NOTE: Disabling hangcheck or reset via module parameter will
  cause the related events to not be seen.

- I915_RESET_UEVENT - Event is generated just before an attempt to reset the

  GPU. The value supplied with the event is always 1. NOTE: Disable
  reset via module parameter will cause this event to not be seen.

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

Base class for defining a chain of extensions

**Definition**

```c
struct i915_user_extension {
    __u64 next_extension;
    __u32 name;
    __u32 flags;
    __u32 rsvd[4];
};
```

**Members**

- `next_extension`: Pointer to the next struct i915_user_extension, or zero if the end.
- `name`: Name of the extension.

  Note that the name here is just some integer.

  Also note that the name space for this is not global for the whole
  driver, but rather its scope/meaning is limited to the specific piece
  of uAPI which has embedded the struct i915_user_extension.
- `flags`: MBZ

  All undefined bits must be zero.
- `rsvd`: MBZ

  Reserved for future use; must be zero.

**Description**

Many interfaces need to grow over time. In most cases we can simply
extend the struct and have userspace pass in more data. Another option,
as demonstrated by Vulkan's approach to providing extensions for forward
and backward compatibility, is to use a list of optional structs to
provide those extra details.

The key advantage to using an extension chain is that it allows us to
redefine the interface more easily than an ever growing struct of
increasing complexity, and for large parts of that interface to be
entirely optional. The downside is more pointer chasing; chasing across
the __user boundary with pointers encapsulated inside u64.

Example chaining:

```C
struct i915_user_extension ext3 {
        .next_extension = 0, // end
        .name = ...,
};
struct i915_user_extension ext2 {
        .next_extension = (uintptr_t)&ext3,
        .name = ...,
};
struct i915_user_extension ext1 {
        .next_extension = (uintptr_t)&ext2,
        .name = ...,
};
```

Typically the struct i915_user_extension would be embedded in some uAPI
struct, and in this case we would feed it the head of the chain(i.e ext1),
which would then apply all of the above extensions.

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

uapi engine type enumeration

**Constants**

- `I915_ENGINE_CLASS_RENDER`: Render engines support instructions used for 3D, Compute (GPGPU),
  and programmable media workloads.  These instructions fetch data and
  dispatch individual work items to threads that operate in parallel.
  The threads run small programs (called "kernels" or "shaders") on
  the GPU's execution units (EUs).
- `I915_ENGINE_CLASS_COPY`: Copy engines (also referred to as "blitters") support instructions
  that move blocks of data from one location in memory to another,
  or that fill a specified location of memory with fixed data.
  Copy engines can perform pre-defined logical or bitwise operations
  on the source, destination, or pattern data.
- `I915_ENGINE_CLASS_VIDEO`: Video engines (also referred to as "bit stream decode" (BSD) or
  "vdbox") support instructions that perform fixed-function media
  decode and encode.
- `I915_ENGINE_CLASS_VIDEO_ENHANCE`: Video enhancement engines (also referred to as "vebox") support
  instructions related to image enhancement.
- `I915_ENGINE_CLASS_COMPUTE`: Compute engines support a subset of the instructions available
  on render engines:  compute engines support Compute (GPGPU) and
  programmable media workloads, but do not support the 3D pipeline.
- `I915_ENGINE_CLASS_INVALID`: Placeholder value to represent an invalid engine class assignment.

**Description**

Different engines serve different roles, and there may be more than one
engine serving each role.  This enum provides a classification of the role
of the engine, which may be used when requesting operations to be performed
on a certain subset of engines, or for providing information about that
group.

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

Engine class/instance identifier

**Definition**

```c
struct i915_engine_class_instance {
        __u16 engine_class;
    #define I915_ENGINE_CLASS_INVALID_NONE -1;
    #define I915_ENGINE_CLASS_INVALID_VIRTUAL -2;
        __u16 engine_instance;
};
```

**Members**

- `engine_class`: Engine class from enum drm_i915_gem_engine_class
- `engine_instance`: Engine instance.

**Description**

There may be more than one engine fulfilling any role within the system.
Each engine of a class is given a unique instance number and therefore
any engine can be specified by its class:instance tuplet. APIs that allow
access to any engine in the system will use struct i915_engine_class_instance
for this identification.

**perf_events exposed by i915 through /sys/bus/event_sources/drivers/i915**

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

Driver parameter query structure.

**Definition**

```c
struct drm_i915_getparam {
    __s32 param;
    int __user *value;
};
```

**Members**

- `param`: Driver parameter to query.
- `value`: Address of memory where queried value should be put.

  WARNING: Using pointers instead of fixed-size u64 means we need to write
  compat32 code. Don't repeat this mistake.

#### <a id="c-drm_i915_getparam_t"></a>`typedef drm_i915_getparam_t`

Driver parameter query structure. See struct drm_i915_getparam.

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

Retrieve an offset so we can mmap this buffer object.

**Definition**

```c
struct drm_i915_gem_mmap_offset {
        __u32 handle;
        __u32 pad;
        __u64 offset;
        __u64 flags;
    #define I915_MMAP_OFFSET_GTT    0;
    #define I915_MMAP_OFFSET_WC     1;
    #define I915_MMAP_OFFSET_WB     2;
    #define I915_MMAP_OFFSET_UC     3;
    #define I915_MMAP_OFFSET_FIXED  4;
        __u64 extensions;
};
```

**Members**

- `handle`: Handle for the object being mapped.
- `pad`: Must be zero
- `offset`: The fake offset to use for subsequent mmap call

  This is a fixed-size type for 32/64 compatibility.
- `flags`: Flags for extended behaviour.

  It is mandatory that one of the `MMAP_OFFSET` types
  should be included:

  - `I915_MMAP_OFFSET_GTT`: Use mmap with the object bound to GTT. (Write-Combined)
  - `I915_MMAP_OFFSET_WC`: Use Write-Combined caching.
  - `I915_MMAP_OFFSET_WB`: Use Write-Back caching.
  - `I915_MMAP_OFFSET_FIXED`: Use object placement to determine caching.

  On devices with local memory `I915_MMAP_OFFSET_FIXED` is the only valid
  type. On devices without local memory, this caching mode is invalid.

  As caching mode when specifying `I915_MMAP_OFFSET_FIXED`, WC or WB will
  be used, depending on the object placement on creation. WB will be used
  when the object can only exist in system memory, WC otherwise.
- `extensions`: Zero-terminated chain of extensions.

  No current extensions defined; mbz.

**Description**

This struct is passed as argument to the `DRM_IOCTL_I915_GEM_MMAP_OFFSET` ioctl,
and is used to retrieve the fake offset to mmap an object specified by `handle`.

The legacy way of using `DRM_IOCTL_I915_GEM_MMAP` is removed on gen12+.
`DRM_IOCTL_I915_GEM_MMAP_GTT` is an older supported alias to this struct, but will behave
as setting the `extensions` to 0, and `flags` to `I915_MMAP_OFFSET_GTT`.

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

Adjust the objects write or read domain, in preparation for accessing the pages via some CPU domain.

**Definition**

```c
struct drm_i915_gem_set_domain {
    __u32 handle;
    __u32 read_domains;
    __u32 write_domain;
};
```

**Members**

- `handle`: Handle for the object.
- `read_domains`: New read domains.
- `write_domain`: New write domain.

  Note that having something in the write domain implies it's in the
  read domain, and only that read domain.

**Description**

Specifying a new write or read domain will flush the object out of the
previous domain(if required), before then updating the objects domain
tracking with the new domain.

Note this might involve waiting for the object first if it is still active on
the GPU.

Supported values for **read_domains** and **write_domain**:

- I915_GEM_DOMAIN_WC: Uncached write-combined domain
- I915_GEM_DOMAIN_CPU: CPU cache domain
- I915_GEM_DOMAIN_GTT: Mappable aperture domain

All other domains are rejected.

Note that for discrete, starting from DG1, this is no longer supported, and
is instead rejected. On such platforms the CPU domain is effectively static,
where we also only support a single [`drm_i915_gem_mmap_offset`](#c-struct-drm_i915_gem_mmap_offset) cache mode,
which can't be set explicitly and instead depends on the object placements,
as per the below.

Implicit caching rules, starting from DG1:

- If any of the object placements (see [`drm_i915_gem_create_ext_memory_regions`](#c-struct-drm_i915_gem_create_ext_memory_regions))
  contain I915_MEMORY_CLASS_DEVICE then the object will be allocated and
  mapped as write-combined only.

- Everything else is always allocated and mapped as write-back, with the
  guarantee that everything is also coherent with the GPU.

Note that this is likely to change in the future again, where we might need
more flexibility on future devices, so making this all explicit as part of a
new [`drm_i915_gem_create_ext`](#c-struct-drm_i915_gem_create_ext) extension is probable.

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

An input or output fence for the execbuf ioctl.

**Definition**

```c
struct drm_i915_gem_exec_fence {
        __u32 handle;
        __u32 flags;
    #define I915_EXEC_FENCE_WAIT            (1<<0);
    #define I915_EXEC_FENCE_SIGNAL          (1<<1);
    #define __I915_EXEC_FENCE_UNKNOWN_FLAGS (-(I915_EXEC_FENCE_SIGNAL << 1));
};
```

**Members**

- `handle`: User's handle for a drm_syncobj to wait on or signal.
- `flags`: Supported flags are:

  I915_EXEC_FENCE_WAIT:
  Wait for the input fence before request submission.

  I915_EXEC_FENCE_SIGNAL:
  Return request completion fence as output

**Description**

The request will wait for input fence to signal before submission.

The returned output fence will be signaled after the completion of the
request.

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

Timeline fences for execbuf ioctl.

**Definition**

```c
struct drm_i915_gem_execbuffer_ext_timeline_fences {
    #define DRM_I915_GEM_EXECBUFFER_EXT_TIMELINE_FENCES 0;
        struct i915_user_extension base;
        __u64 fence_count;
        __u64 handles_ptr;
        __u64 values_ptr;
};
```

**Members**

- `base`: Extension link. See struct i915_user_extension.
- `fence_count`: Number of elements in the **handles_ptr** & **value_ptr**
  arrays.
- `handles_ptr`: Pointer to an array of struct drm_i915_gem_exec_fence
  of length **fence_count**.
- `values_ptr`: Pointer to an array of u64 values of length
  **fence_count**.
  Values must be 0 for a binary drm_syncobj. A Value of 0 for a
  timeline drm_syncobj is invalid as it turns a drm_syncobj into a
  binary one.

**Description**

This structure describes an array of drm_syncobj and associated points for
timeline variants of drm_syncobj. It is invalid to append this structure to
the execbuf if I915_EXEC_FENCE_ARRAY is set.

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

Structure for DRM_I915_GEM_EXECBUFFER2 ioctl.

**Definition**

```c
struct drm_i915_gem_execbuffer2 {
        __u64 buffers_ptr;
        __u32 buffer_count;
        __u32 batch_start_offset;
        __u32 batch_len;
        __u32 DR1;
        __u32 DR4;
        __u32 num_cliprects;
        __u64 cliprects_ptr;
        __u64 flags;
    #define I915_EXEC_RING_MASK              (0x3f);
    #define I915_EXEC_DEFAULT                (0<<0);
    #define I915_EXEC_RENDER                 (1<<0);
    #define I915_EXEC_BSD                    (2<<0);
    #define I915_EXEC_BLT                    (3<<0);
    #define I915_EXEC_VEBOX                  (4<<0);
    #define I915_EXEC_CONSTANTS_MASK        (3<<6);
    #define I915_EXEC_CONSTANTS_REL_GENERAL (0<<6);
    #define I915_EXEC_CONSTANTS_ABSOLUTE    (1<<6);
    #define I915_EXEC_CONSTANTS_REL_SURFACE (2<<6);
    #define I915_EXEC_GEN7_SOL_RESET        (1<<8);
    #define I915_EXEC_SECURE                (1<<9);
    #define I915_EXEC_IS_PINNED             (1<<10);
    #define I915_EXEC_NO_RELOC              (1<<11);
    #define I915_EXEC_HANDLE_LUT            (1<<12);
    #define I915_EXEC_BSD_SHIFT      (13);
    #define I915_EXEC_BSD_MASK       (3 << I915_EXEC_BSD_SHIFT);
    #define I915_EXEC_BSD_DEFAULT    (0 << I915_EXEC_BSD_SHIFT);
    #define I915_EXEC_BSD_RING1      (1 << I915_EXEC_BSD_SHIFT);
    #define I915_EXEC_BSD_RING2      (2 << I915_EXEC_BSD_SHIFT);
    #define I915_EXEC_RESOURCE_STREAMER     (1<<15);
    #define I915_EXEC_FENCE_IN              (1<<16);
    #define I915_EXEC_FENCE_OUT             (1<<17);
    #define I915_EXEC_BATCH_FIRST           (1<<18);
    #define I915_EXEC_FENCE_ARRAY   (1<<19);
    #define I915_EXEC_FENCE_SUBMIT          (1 << 20);
    #define I915_EXEC_USE_EXTENSIONS        (1 << 21);
    #define __I915_EXEC_UNKNOWN_FLAGS (-(I915_EXEC_USE_EXTENSIONS << 1));
        __u64 rsvd1;
        __u64 rsvd2;
};
```

**Members**

- `buffers_ptr`: Pointer to a list of gem_exec_object2 structs
- `buffer_count`: Number of elements in **buffers_ptr** array
- `batch_start_offset`: Offset in the batchbuffer to start execution
  from.
- `batch_len`: Length in bytes of the batch buffer, starting from the
  **batch_start_offset**. If 0, length is assumed to be the batch buffer
  object size.
- `DR1`: deprecated
- `DR4`: deprecated
- `num_cliprects`: See **cliprects_ptr**
- `cliprects_ptr`: Kernel clipping was a DRI1 misfeature.

  It is invalid to use this field if I915_EXEC_FENCE_ARRAY or
  I915_EXEC_USE_EXTENSIONS flags are not set.

  If I915_EXEC_FENCE_ARRAY is set, then this is a pointer to an array
  of [`drm_i915_gem_exec_fence`](#c-struct-drm_i915_gem_exec_fence) and **num_cliprects** is the length of the
  array.

  If I915_EXEC_USE_EXTENSIONS is set, then this is a pointer to a
  single [`i915_user_extension`](#c-struct-i915_user_extension) and num_cliprects is 0.
- `flags`: Execbuf flags
- `rsvd1`: Context id
- `rsvd2`: in and out sync_file file descriptors.

  When I915_EXEC_FENCE_IN or I915_EXEC_FENCE_SUBMIT flag is set, the
  lower 32 bits of this field will have the in sync_file fd (input).

  When I915_EXEC_FENCE_OUT flag is set, the upper 32 bits of this
  field will have the out sync_file fd (output).

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

Set or get the caching for given object handle.

**Definition**

```c
struct drm_i915_gem_caching {
        __u32 handle;
    #define I915_CACHING_NONE               0;
    #define I915_CACHING_CACHED             1;
    #define I915_CACHING_DISPLAY            2;
        __u32 caching;
};
```

**Members**

- `handle`: Handle of the buffer to set/get the caching level.
- `caching`: The GTT caching level to apply or possible return value.

  The supported **caching** values:

  I915_CACHING_NONE:

  GPU access is not coherent with CPU caches.  Default for machines
  without an LLC. This means manual flushing might be needed, if we
  want GPU access to be coherent.

  I915_CACHING_CACHED:

  GPU access is coherent with CPU caches and furthermore the data is
  cached in last-level caches shared between CPU cores and the GPU GT.

  I915_CACHING_DISPLAY:

  Special GPU caching mode which is coherent with the scanout engines.
  Transparently falls back to I915_CACHING_NONE on platforms where no
  special cache mode (like write-through or gfdt flushing) is
  available. The kernel automatically sets this mode when using a
  buffer as a scanout target.  Userspace can manually set this mode to
  avoid a costly stall and clflush in the hotpath of drawing the first
  frame.

**Description**

Allow userspace to control the GTT caching bits for a given object when the
object is later mapped through the ppGTT(or GGTT on older platforms lacking
ppGTT support, or if the object is used for scanout). Note that this might
require unbinding the object from the GTT first, if its current caching value
doesn't match.

Note that this all changes on discrete platforms, starting from DG1, the
set/get caching is no longer supported, and is now rejected.  Instead the CPU
caching attributes(WB vs WC) will become an immutable creation time property
for the object, along with the GTT caching level. For now we don't expose any
new uAPI for this, instead on DG1 this is all implicit, although this largely
shouldn't matter since DG1 is coherent by default(without any way of
controlling it).

Implicit caching rules, starting from DG1:

- If any of the object placements (see [`drm_i915_gem_create_ext_memory_regions`](#c-struct-drm_i915_gem_create_ext_memory_regions))
  contain I915_MEMORY_CLASS_DEVICE then the object will be allocated and
  mapped as write-combined only.

- Everything else is always allocated and mapped as write-back, with the
  guarantee that everything is also coherent with the GPU.

Note that this is likely to change in the future again, where we might need
more flexibility on future devices, so making this all explicit as part of a
new [`drm_i915_gem_create_ext`](#c-struct-drm_i915_gem_create_ext) extension is probable.

Side note: Part of the reason for this is that changing the at-allocation-time CPU
caching attributes for the pages might be required(and is expensive) if we
need to then CPU map the pages later with different caching attributes. This
inconsistent caching behaviour, while supported on x86, is not universally
supported on other architectures. So for simplicity we opt for setting
everything at creation time, whilst also making it immutable, on discrete
platforms.

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

Structure for creating contexts.

**Definition**

```c
struct drm_i915_gem_context_create_ext {
        __u32 ctx_id;
        __u32 flags;
    #define I915_CONTEXT_CREATE_FLAGS_USE_EXTENSIONS        (1u << 0);
    #define I915_CONTEXT_CREATE_FLAGS_SINGLE_TIMELINE       (1u << 1);
    #define I915_CONTEXT_CREATE_FLAGS_UNKNOWN         (-(I915_CONTEXT_CREATE_FLAGS_SINGLE_TIMELINE << 1));
        __u64 extensions;
    #define I915_CONTEXT_CREATE_EXT_SETPARAM 0;
    #define I915_CONTEXT_CREATE_EXT_CLONE 1;
};
```

**Members**

- `ctx_id`: Id of the created context (output)
- `flags`: Supported flags are:

  I915_CONTEXT_CREATE_FLAGS_USE_EXTENSIONS:

  Extensions may be appended to this structure and driver must check
  for those. See **extensions**.

  I915_CONTEXT_CREATE_FLAGS_SINGLE_TIMELINE

  Created context will have single timeline.
- `extensions`: Zero-terminated chain of extensions.

  I915_CONTEXT_CREATE_EXT_SETPARAM:
  Context parameter to set or query during context creation.
  See struct drm_i915_gem_context_create_ext_setparam.

  I915_CONTEXT_CREATE_EXT_CLONE:
  This extension has been removed. On the off chance someone somewhere
  has attempted to use it, never re-use this extension number.

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

Context parameter to set or query.

**Definition**

```c
struct drm_i915_gem_context_param {
        __u32 ctx_id;
        __u32 size;
        __u64 param;
    #define I915_CONTEXT_PARAM_BAN_PERIOD   0x1;
    #define I915_CONTEXT_PARAM_NO_ZEROMAP   0x2;
    #define I915_CONTEXT_PARAM_GTT_SIZE     0x3;
    #define I915_CONTEXT_PARAM_NO_ERROR_CAPTURE     0x4;
    #define I915_CONTEXT_PARAM_BANNABLE     0x5;
    #define I915_CONTEXT_PARAM_PRIORITY     0x6;
    #define I915_CONTEXT_MAX_USER_PRIORITY        1023;
    #define I915_CONTEXT_DEFAULT_PRIORITY         0;
    #define I915_CONTEXT_MIN_USER_PRIORITY        -1023;
    #define I915_CONTEXT_PARAM_SSEU         0x7;
    #define I915_CONTEXT_PARAM_RECOVERABLE  0x8;
    #define I915_CONTEXT_PARAM_VM           0x9;
    #define I915_CONTEXT_PARAM_ENGINES      0xa;
    #define I915_CONTEXT_PARAM_PERSISTENCE  0xb;
    #define I915_CONTEXT_PARAM_RINGSIZE     0xc;
    #define I915_CONTEXT_PARAM_PROTECTED_CONTENT    0xd;
    #define I915_CONTEXT_PARAM_LOW_LATENCY          0xe;
    #define I915_CONTEXT_PARAM_CONTEXT_IMAGE        0xf;
        __u64 value;
};
```

**Members**

- `ctx_id`: Context id
- `size`: Size of the parameter **value**
- `param`: Parameter to set or query
- `value`: Context parameter value to be set or queried

**Virtual Engine uAPI**

Virtual engine is a concept where userspace is able to configure a set of
physical engines, submit a batch buffer, and let the driver execute it on any
engine from the set as it sees fit.

This is primarily useful on parts which have multiple instances of a same
class engine, like for example GT3+ Skylake parts with their two VCS engines.

For instance userspace can enumerate all engines of a certain class using the
previously described `Engine Discovery uAPI`. After that userspace can
create a GEM context with a placeholder slot for the virtual engine (using
`I915_ENGINE_CLASS_INVALID` and `I915_ENGINE_CLASS_INVALID_NONE` for class
and instance respectively) and finally using the
`I915_CONTEXT_ENGINES_EXT_LOAD_BALANCE` extension place a virtual engine in
the same reserved slot.

Example of creating a virtual engine and submitting a batch buffer to it:

```C
I915_DEFINE_CONTEXT_ENGINES_LOAD_BALANCE(virtual, 2) = {
        .base.name = I915_CONTEXT_ENGINES_EXT_LOAD_BALANCE,
        .engine_index = 0, // Place this virtual engine into engine map slot 0
        .num_siblings = 2,
        .engines = { { I915_ENGINE_CLASS_VIDEO, 0 },
                     { I915_ENGINE_CLASS_VIDEO, 1 }, },
};
I915_DEFINE_CONTEXT_PARAM_ENGINES(engines, 1) = {
        .engines = { { I915_ENGINE_CLASS_INVALID,
                       I915_ENGINE_CLASS_INVALID_NONE } },
        .extensions = to_user_pointer(&virtual), // Chains after load_balance extension
};
struct drm_i915_gem_context_create_ext_setparam p_engines = {
        .base = {
                .name = I915_CONTEXT_CREATE_EXT_SETPARAM,
        },
        .param = {
                .param = I915_CONTEXT_PARAM_ENGINES,
                .value = to_user_pointer(&engines),
                .size = sizeof(engines),
        },
};
struct drm_i915_gem_context_create_ext create = {
        .flags = I915_CONTEXT_CREATE_FLAGS_USE_EXTENSIONS,
        .extensions = to_user_pointer(&p_engines);
};

ctx_id = gem_context_create_ext(drm_fd, &create);

// Now we have created a GEM context with its engine map containing a
// single virtual engine. Submissions to this slot can go either to
// vcs0 or vcs1, depending on the load balancing algorithm used inside
// the driver. The load balancing is dynamic from one batch buffer to
// another and transparent to userspace.

...
execbuf.rsvd1 = ctx_id;
execbuf.flags = 0; // Submits to index 0 which is the virtual engine
gem_execbuf(drm_fd, &execbuf);
```

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

Configure engine for parallel submission.

**Definition**

```c
struct i915_context_engines_parallel_submit {
    struct i915_user_extension base;
    __u16 engine_index;
    __u16 width;
    __u16 num_siblings;
    __u16 mbz16;
    __u64 flags;
    __u64 mbz64[3];
    struct i915_engine_class_instance engines[];
};
```

**Members**

- `base`: base user extension.
- `engine_index`: slot for parallel engine
- `width`: number of contexts per parallel engine or in other words the
  number of batches in each submission
- `num_siblings`: number of siblings per context or in other words the
  number of possible placements for each submission
- `mbz16`: reserved for future use; must be zero
- `flags`: all undefined flags must be zero, currently not defined flags
- `mbz64`: reserved for future use; must be zero
- `engines`: 2-d array of engine instances to configure parallel engine

  length = width (i) * num_siblings (j)
  index = j + i * num_siblings

**Description**

Setup a slot in the context engine map to allow multiple BBs to be submitted
in a single execbuf IOCTL. Those BBs will then be scheduled to run on the GPU
in parallel. Multiple hardware contexts are created internally in the i915 to
run these BBs. Once a slot is configured for N BBs only N BBs can be
submitted in each execbuf IOCTL and this is implicit behavior e.g. The user
doesn't tell the execbuf IOCTL there are N BBs, the execbuf IOCTL knows how
many BBs there are based on the slot's configuration. The N BBs are the last
N buffer objects or first N if I915_EXEC_BATCH_FIRST is set.

The default placement behavior is to create implicit bonds between each
context if each context maps to more than 1 physical engine (e.g. context is
a virtual engine). Also we only allow contexts of same engine class and these
contexts must be in logically contiguous order. Examples of the placement
behavior are described below. Lastly, the default is to not allow BBs to be
preempted mid-batch. Rather insert coordinated preemption points on all
hardware contexts between each set of BBs. Flags could be added in the future
to change both of these default behaviors.

Returns -EINVAL if hardware context placement configuration is invalid or if
the placement configuration isn't supported on the platform / submission
interface.
Returns -ENODEV if extension isn't supported on the platform / submission
interface.

```none
Examples syntax:
CS[X] = generic engine of same class, logical instance X
INVALID = I915_ENGINE_CLASS_INVALID, I915_ENGINE_CLASS_INVALID_NONE

Example 1 pseudo code:
set_engines(INVALID)
set_parallel(engine_index=0, width=2, num_siblings=1,
             engines=CS[0],CS[1])

Results in the following valid placement:
CS[0], CS[1]

Example 2 pseudo code:
set_engines(INVALID)
set_parallel(engine_index=0, width=2, num_siblings=2,
             engines=CS[0],CS[2],CS[1],CS[3])

Results in the following valid placements:
CS[0], CS[1]
CS[2], CS[3]

This can be thought of as two virtual engines, each containing two
engines thereby making a 2D array. However, there are bonds tying the
entries together and placing restrictions on how they can be scheduled.
Specifically, the scheduler can choose only vertical columns from the 2D
array. That is, CS[0] is bonded to CS[1] and CS[2] to CS[3]. So if the
scheduler wants to submit to CS[0], it must also choose CS[1] and vice
versa. Same for CS[2] requires also using CS[3].
VE[0] = CS[0], CS[2]
VE[1] = CS[1], CS[3]

Example 3 pseudo code:
set_engines(INVALID)
set_parallel(engine_index=0, width=2, num_siblings=2,
             engines=CS[0],CS[1],CS[1],CS[3])

Results in the following valid and invalid placements:
CS[0], CS[1]
CS[1], CS[3] - Not logically contiguous, return -EINVAL
```

**Context Engine Map uAPI**

Context engine map is a new way of addressing engines when submitting batch-
buffers, replacing the existing way of using identifiers like `I915_EXEC_BLT`
inside the flags field of `struct drm_i915_gem_execbuffer2`.

To use it created GEM contexts need to be configured with a list of engines
the user is intending to submit to. This is accomplished using the
`I915_CONTEXT_PARAM_ENGINES` parameter and `struct i915_context_param_engines`.

For such contexts the `I915_EXEC_RING_MASK` field becomes an index into the
configured map.

Example of creating such context and submitting against it:

```C
I915_DEFINE_CONTEXT_PARAM_ENGINES(engines, 2) = {
        .engines = { { I915_ENGINE_CLASS_RENDER, 0 },
                     { I915_ENGINE_CLASS_COPY, 0 } }
};
struct drm_i915_gem_context_create_ext_setparam p_engines = {
        .base = {
                .name = I915_CONTEXT_CREATE_EXT_SETPARAM,
        },
        .param = {
                .param = I915_CONTEXT_PARAM_ENGINES,
                .value = to_user_pointer(&engines),
                .size = sizeof(engines),
        },
};
struct drm_i915_gem_context_create_ext create = {
        .flags = I915_CONTEXT_CREATE_FLAGS_USE_EXTENSIONS,
        .extensions = to_user_pointer(&p_engines);
};

ctx_id = gem_context_create_ext(drm_fd, &create);

// We have now created a GEM context with two engines in the map:
// Index 0 points to rcs0 while index 1 points to bcs0. Other engines
// will not be accessible from this context.

...
execbuf.rsvd1 = ctx_id;
execbuf.flags = 0; // Submits to index 0, which is rcs0 for this context
gem_execbuf(drm_fd, &execbuf);

...
execbuf.rsvd1 = ctx_id;
execbuf.flags = 1; // Submits to index 0, which is bcs0 for this context
gem_execbuf(drm_fd, &execbuf);
```

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

Context parameter to set or query during context creation.

**Definition**

```c
struct drm_i915_gem_context_create_ext_setparam {
    struct i915_user_extension base;
    struct drm_i915_gem_context_param param;
};
```

**Members**

- `base`: Extension link. See struct i915_user_extension.
- `param`: Context parameter to set or query.
  See struct drm_i915_gem_context_param.

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

Structure to create or destroy VM.

**Definition**

```c
struct drm_i915_gem_vm_control {
    __u64 extensions;
    __u32 flags;
    __u32 vm_id;
};
```

**Members**

- `extensions`: Zero-terminated chain of extensions.
- `flags`: reserved for future usage, currently MBZ
- `vm_id`: Id of the VM created or to be destroyed

**Description**

DRM_I915_GEM_VM_CREATE -

Create a new virtual memory address space (ppGTT) for use within a context
on the same file. Extensions can be provided to configure exactly how the
address space is setup upon creation.

The id of new VM (bound to the fd) for use with I915_CONTEXT_PARAM_VM is
returned in the outparam **id**.

An extension chain maybe provided, starting with **extensions**, and terminated
by the **next_extension** being 0. Currently, no extensions are defined.

DRM_I915_GEM_VM_DESTROY -

Destroys a previously created VM id, specified in **vm_id**.

No extensions or flags are allowed currently, and so must be zero.

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

Create GEM object from user allocated memory.

**Definition**

```c
struct drm_i915_gem_userptr {
        __u64 user_ptr;
        __u64 user_size;
        __u32 flags;
    #define I915_USERPTR_READ_ONLY 0x1;
    #define I915_USERPTR_PROBE 0x2;
    #define I915_USERPTR_UNSYNCHRONIZED 0x80000000;
        __u32 handle;
};
```

**Members**

- `user_ptr`: The pointer to the allocated memory.

  Needs to be aligned to PAGE_SIZE.
- `user_size`: The size in bytes for the allocated memory. This will also become the
  object size.

  Needs to be aligned to PAGE_SIZE, and should be at least PAGE_SIZE,
  or larger.
- `flags`: Supported flags:

  I915_USERPTR_READ_ONLY:

  Mark the object as readonly, this also means GPU access can only be
  readonly. This is only supported on HW which supports readonly access
  through the GTT. If the HW can't support readonly access, an error is
  returned.

  I915_USERPTR_PROBE:

  Probe the provided **user_ptr** range and validate that the **user_ptr** is
  indeed pointing to normal memory and that the range is also valid.
  For example if some garbage address is given to the kernel, then this
  should complain.

  Returns -EFAULT if the probe failed.

  Note that this doesn't populate the backing pages, and also doesn't
  guarantee that the object will remain valid when the object is
  eventually used.

  The kernel supports this feature if I915_PARAM_HAS_USERPTR_PROBE
  returns a non-zero value.

  I915_USERPTR_UNSYNCHRONIZED:

  NOT USED. Setting this flag will result in an error.
- `handle`: Returned handle for the object.

  Object handles are nonzero.

**Description**

Userptr objects have several restrictions on what ioctls can be used with the
object handle.

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

**Definition**

```c
struct drm_i915_perf_oa_config {
    char uuid[36];
    __u32 n_mux_regs;
    __u32 n_boolean_regs;
    __u32 n_flex_regs;
    __u64 mux_regs_ptr;
    __u64 boolean_regs_ptr;
    __u64 flex_regs_ptr;
};
```

**Members**

- `uuid`: String formatted like "%\08x-%\04x-%\04x-%\04x-%\012x"
- `n_mux_regs`: Number of mux regs in `mux_regs_ptr`.
- `n_boolean_regs`: Number of boolean regs in `boolean_regs_ptr`.
- `n_flex_regs`: Number of flex regs in `flex_regs_ptr`.
- `mux_regs_ptr`: Pointer to tuples of u32 values (register address, value) for mux
  registers.  Expected length of buffer is (2 * sizeof(u32) *
  `n_mux_regs`).
- `boolean_regs_ptr`: Pointer to tuples of u32 values (register address, value) for mux
  registers.  Expected length of buffer is (2 * sizeof(u32) *
  `n_boolean_regs`).
- `flex_regs_ptr`: Pointer to tuples of u32 values (register address, value) for mux
  registers.  Expected length of buffer is (2 * sizeof(u32) *
  `n_flex_regs`).

**Description**

Structure to upload perf dynamic configuration into the kernel.

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

An individual query for the kernel to process.

**Definition**

```c
struct drm_i915_query_item {
        __u64 query_id;
    #define DRM_I915_QUERY_TOPOLOGY_INFO            1;
    #define DRM_I915_QUERY_ENGINE_INFO              2;
    #define DRM_I915_QUERY_PERF_CONFIG              3;
    #define DRM_I915_QUERY_MEMORY_REGIONS           4;
    #define DRM_I915_QUERY_HWCONFIG_BLOB            5;
    #define DRM_I915_QUERY_GEOMETRY_SUBSLICES       6;
    #define DRM_I915_QUERY_GUC_SUBMISSION_VERSION   7;
        __s32 length;
        __u32 flags;
    #define DRM_I915_QUERY_PERF_CONFIG_LIST          1;
    #define DRM_I915_QUERY_PERF_CONFIG_DATA_FOR_UUID 2;
    #define DRM_I915_QUERY_PERF_CONFIG_DATA_FOR_ID   3;
        __u64 data_ptr;
};
```

**Members**

- `query_id`:

  - The id for this query.  Currently accepted query IDs are:
    - `DRM_I915_QUERY_TOPOLOGY_INFO` (see struct drm_i915_query_topology_info)
    - `DRM_I915_QUERY_ENGINE_INFO` (see struct drm_i915_engine_info)
    - `DRM_I915_QUERY_PERF_CONFIG` (see struct drm_i915_query_perf_config)
    - `DRM_I915_QUERY_MEMORY_REGIONS` (see struct drm_i915_query_memory_regions)
    - `DRM_I915_QUERY_HWCONFIG_BLOB` (see `GuC HWCONFIG blob uAPI`)
    - `DRM_I915_QUERY_GEOMETRY_SUBSLICES` (see struct drm_i915_query_topology_info)
    - `DRM_I915_QUERY_GUC_SUBMISSION_VERSION` (see struct drm_i915_query_guc_submission_version)
- `length`: When set to zero by userspace, this is filled with the size of the
  data to be written at the **data_ptr** pointer. The kernel sets this
  value to a negative value to signal an error on a particular query
  item.
- `flags`: When `query_id` == `DRM_I915_QUERY_TOPOLOGY_INFO`, must be 0.

  When `query_id` == `DRM_I915_QUERY_PERF_CONFIG`, must be one of the
  following:

  - `DRM_I915_QUERY_PERF_CONFIG_LIST`
  - `DRM_I915_QUERY_PERF_CONFIG_DATA_FOR_UUID`
  - `DRM_I915_QUERY_PERF_CONFIG_FOR_UUID`

  When `query_id` == `DRM_I915_QUERY_GEOMETRY_SUBSLICES` must contain
  a struct i915_engine_class_instance that references a render engine.
- `data_ptr`: Data will be written at the location pointed by **data_ptr** when the
  value of **length** matches the length of the data to be written by the
  kernel.

**Description**

The behaviour is determined by the **query_id**. Note that exactly what
**data_ptr** is also depends on the specific **query_id**.

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

Supply an array of struct drm_i915_query_item for the kernel to fill out.

**Definition**

```c
struct drm_i915_query {
    __u32 num_items;
    __u32 flags;
    __u64 items_ptr;
};
```

**Members**

- `num_items`: The number of elements in the **items_ptr** array
- `flags`: Unused for now. Must be cleared to zero.
- `items_ptr`: Pointer to an array of struct drm_i915_query_item. The number of
  array elements is **num_items**.

**Description**

Note that this is generally a two step process for each struct
drm_i915_query_item in the array:

1. Call the DRM_IOCTL_I915_QUERY, giving it our array of struct
   drm_i915_query_item, with [`drm_i915_query_item.length`](#c-struct-drm_i915_query_item) set to zero. The
   kernel will then fill in the size, in bytes, which tells userspace how
   memory it needs to allocate for the blob(say for an array of properties).

2. Next we call DRM_IOCTL_I915_QUERY again, this time with the
   [`drm_i915_query_item.data_ptr`](#c-struct-drm_i915_query_item) equal to our newly allocated blob. Note that
   the [`drm_i915_query_item.length`](#c-struct-drm_i915_query_item) should still be the same as what the
   kernel previously set. At this point the kernel can fill in the blob.

Note that for some query items it can make sense for userspace to just pass
in a buffer/blob equal to or larger than the required size. In this case only
a single ioctl call is needed. For some smaller query items this can work
quite well.

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

**Definition**

```c
struct drm_i915_query_topology_info {
    __u16 flags;
    __u16 max_slices;
    __u16 max_subslices;
    __u16 max_eus_per_subslice;
    __u16 subslice_offset;
    __u16 subslice_stride;
    __u16 eu_offset;
    __u16 eu_stride;
    __u8 data[];
};
```

**Members**

- `flags`: Unused for now. Must be cleared to zero.
- `max_slices`: The number of bits used to express the slice mask.
- `max_subslices`: The number of bits used to express the subslice mask.
- `max_eus_per_subslice`: The number of bits in the EU mask that correspond to a single
  subslice's EUs.
- `subslice_offset`: Offset in data\[\] at which the subslice masks are stored.
- `subslice_stride`: Stride at which each of the subslice masks for each slice are
  stored.
- `eu_offset`: Offset in data\[\] at which the EU masks are stored.
- `eu_stride`: Stride at which each of the EU masks for each subslice are stored.
- `data`: Contains 3 pieces of information :

  - The slice mask with one bit per slice telling whether a slice is
    available. The availability of slice X can be queried with the
    following formula :

  ```c
  (data[X / 8] >> (X % 8)) & 1
  ```

  Starting with Xe_HP platforms, Intel hardware no longer has
  traditional slices so i915 will always report a single slice
  (hardcoded slicemask = 0x1) which contains all of the platform's
  subslices.  I.e., the mask here does not reflect any of the newer
  hardware concepts such as "gslices" or "cslices" since userspace
  is capable of inferring those from the subslice mask.

  - The subslice mask for each slice with one bit per subslice telling
    whether a subslice is available.  Starting with Gen12 we use the
    term "subslice" to refer to what the hardware documentation
    describes as a "dual-subslices."  The availability of subslice Y
    in slice X can be queried with the following formula :

  ```c
  (data[subslice_offset + X * subslice_stride + Y / 8] >> (Y % 8)) & 1
  ```

  - The EU mask for each subslice in each slice, with one bit per EU
    telling whether an EU is available. The availability of EU Z in
    subslice Y in slice X can be queried with the following formula :

  ```c
  (data[eu_offset +
        (X * max_subslices + Y) * eu_stride +
        Z / 8
   ] >> (Z % 8)) & 1
  ```

**Description**

Describes slice/subslice/EU information queried by
`DRM_I915_QUERY_TOPOLOGY_INFO`

**Engine Discovery uAPI**

Engine discovery uAPI is a way of enumerating physical engines present in a
GPU associated with an open i915 DRM file descriptor. This supersedes the old
way of using `DRM_IOCTL_I915_GETPARAM` and engine identifiers like
`I915_PARAM_HAS_BLT`.

The need for this interface came starting with Icelake and newer GPUs, which
started to establish a pattern of having multiple engines of a same class,
where not all instances were always completely functionally equivalent.

Entry point for this uapi is `DRM_IOCTL_I915_QUERY` with the
`DRM_I915_QUERY_ENGINE_INFO` as the queried item id.

Example for getting the list of engines:

```C
struct drm_i915_query_engine_info *info;
struct drm_i915_query_item item = {
        .query_id = DRM_I915_QUERY_ENGINE_INFO;
};
struct drm_i915_query query = {
        .num_items = 1,
        .items_ptr = (uintptr_t)&item,
};
int err, i;

// First query the size of the blob we need, this needs to be large
// enough to hold our array of engines. The kernel will fill out the
// item.length for us, which is the number of bytes we need.
//
// Alternatively a large buffer can be allocated straightaway enabling
// querying in one pass, in which case item.length should contain the
// length of the provided buffer.
err = ioctl(fd, DRM_IOCTL_I915_QUERY, &query);
if (err) ...

info = calloc(1, item.length);
// Now that we allocated the required number of bytes, we call the ioctl
// again, this time with the data_ptr pointing to our newly allocated
// blob, which the kernel can then populate with info on all engines.
item.data_ptr = (uintptr_t)&info;

err = ioctl(fd, DRM_IOCTL_I915_QUERY, &query);
if (err) ...

// We can now access each engine in the array
for (i = 0; i < info->num_engines; i++) {
        struct drm_i915_engine_info einfo = info->engines[i];
        u16 class = einfo.engine.class;
        u16 instance = einfo.engine.instance;
        ....
}

free(info);
```

Each of the enumerated engines, apart from being defined by its class and
instance (see `struct i915_engine_class_instance`), also can have flags and
capabilities defined as documented in i915_drm.h.

For instance video engines which support HEVC encoding will have the
`I915_VIDEO_CLASS_CAPABILITY_HEVC` capability bit set.

Engine discovery only fully comes to its own when combined with the new way
of addressing engines when submitting batch buffers using contexts with
engine maps configured.

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

**Definition**

```c
struct drm_i915_engine_info {
        struct i915_engine_class_instance engine;
        __u32 rsvd0;
        __u64 flags;
    #define I915_ENGINE_INFO_HAS_LOGICAL_INSTANCE           (1 << 0);
        __u64 capabilities;
    #define I915_VIDEO_CLASS_CAPABILITY_HEVC                (1 << 0);
    #define I915_VIDEO_AND_ENHANCE_CLASS_CAPABILITY_SFC     (1 << 1);
        __u16 logical_instance;
        __u16 rsvd1[3];
        __u64 rsvd2[3];
};
```

**Members**

- `engine`: Engine class and instance.
- `rsvd0`: Reserved field.
- `flags`: Engine flags.
- `capabilities`: Capabilities of this engine.
- `logical_instance`: Logical instance of engine
- `rsvd1`: Reserved fields.
- `rsvd2`: Reserved fields.

**Description**

Describes one engine and its capabilities as known to the driver.

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

**Definition**

```c
struct drm_i915_query_engine_info {
    __u32 num_engines;
    __u32 rsvd[3];
    struct drm_i915_engine_info engines[];
};
```

**Members**

- `num_engines`: Number of struct drm_i915_engine_info structs following.
- `rsvd`: MBZ
- `engines`: Marker for drm_i915_engine_info structures.

**Description**

Engine info query enumerates all engines known to the driver by filling in
an array of struct drm_i915_engine_info structures.

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

**Definition**

```c
struct drm_i915_query_perf_config {
    union {
        __u64 n_configs;
        __u64 config;
        char uuid[36];
    };
    __u32 flags;
    __u8 data[];
};
```

**Members**

- `{unnamed_union}`: anonymous
- `n_configs`: When [`drm_i915_query_item.flags`](#c-struct-drm_i915_query_item) ==
  `DRM_I915_QUERY_PERF_CONFIG_LIST`, i915 sets this fields to
  the number of configurations available.
- `config`: When [`drm_i915_query_item.flags`](#c-struct-drm_i915_query_item) ==
  `DRM_I915_QUERY_PERF_CONFIG_DATA_FOR_ID`, i915 will use the
  value in this field as configuration identifier to decide
  what data to write into config_ptr.
- `uuid`: When [`drm_i915_query_item.flags`](#c-struct-drm_i915_query_item) ==
  `DRM_I915_QUERY_PERF_CONFIG_DATA_FOR_UUID`, i915 will use the
  value in this field as configuration identifier to decide
  what data to write into config_ptr.

  String formatted like "`08x-``04x-``04x-``04x-``012x`"
- `flags`: Unused for now. Must be cleared to zero.
- `data`: When [`drm_i915_query_item.flags`](#c-struct-drm_i915_query_item) == `DRM_I915_QUERY_PERF_CONFIG_LIST`,
  i915 will write an array of __u64 of configuration identifiers.

  When [`drm_i915_query_item.flags`](#c-struct-drm_i915_query_item) == `DRM_I915_QUERY_PERF_CONFIG_DATA`,
  i915 will write a struct drm_i915_perf_oa_config. If the following
  fields of struct drm_i915_perf_oa_config are not set to 0, i915 will
  write into the associated pointers the values of submitted when the
  configuration was created :

  - [`drm_i915_perf_oa_config.n_mux_regs`](#c-struct-drm_i915_perf_oa_config)
  - [`drm_i915_perf_oa_config.n_boolean_regs`](#c-struct-drm_i915_perf_oa_config)
  - [`drm_i915_perf_oa_config.n_flex_regs`](#c-struct-drm_i915_perf_oa_config)

**Description**

Data written by the kernel with query `DRM_I915_QUERY_PERF_CONFIG` and
`DRM_I915_QUERY_GEOMETRY_SUBSLICES`.

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

Supported memory classes

**Constants**

- `I915_MEMORY_CLASS_SYSTEM`: System memory
- `I915_MEMORY_CLASS_DEVICE`: Device local-memory

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

Identify particular memory region

**Definition**

```c
struct drm_i915_gem_memory_class_instance {
    __u16 memory_class;
    __u16 memory_instance;
};
```

**Members**

- `memory_class`: See enum drm_i915_gem_memory_class
- `memory_instance`: Which instance

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

Describes one region as known to the driver.

**Definition**

```c
struct drm_i915_memory_region_info {
    struct drm_i915_gem_memory_class_instance region;
    __u32 rsvd0;
    __u64 probed_size;
    __u64 unallocated_size;
    union {
        __u64 rsvd1[8];
        struct {
            __u64 probed_cpu_visible_size;
            __u64 unallocated_cpu_visible_size;
        };
    };
};
```

**Members**

- `region`: The class:instance pair encoding
- `rsvd0`: MBZ
- `probed_size`: Memory probed by the driver

  Note that it should not be possible to ever encounter a zero value
  here, also note that no current region type will ever return -1 here.
  Although for future region types, this might be a possibility. The
  same applies to the other size fields.
- `unallocated_size`: Estimate of memory remaining

  Requires CAP_PERFMON or CAP_SYS_ADMIN to get reliable accounting.
  Without this (or if this is an older kernel) the value here will
  always equal the **probed_size**. Note this is only currently tracked
  for I915_MEMORY_CLASS_DEVICE regions (for other types the value here
  will always equal the **probed_size**).
- `{unnamed_union}`: anonymous
- `rsvd1`: MBZ
- `{unnamed_struct}`: anonymous
- `probed_cpu_visible_size`: Memory probed by the driver
  that is CPU accessible.

  This will be always be \<= **probed_size**, and the
  remainder (if there is any) will not be CPU
  accessible.

  On systems without small BAR, the **probed_size** will
  always equal the **probed_cpu_visible_size**, since all
  of it will be CPU accessible.

  Note this is only tracked for
  I915_MEMORY_CLASS_DEVICE regions (for other types the
  value here will always equal the **probed_size**).

  Note that if the value returned here is zero, then
  this must be an old kernel which lacks the relevant
  small-bar uAPI support (including
  I915_GEM_CREATE_EXT_FLAG_NEEDS_CPU_ACCESS), but on
  such systems we should never actually end up with a
  small BAR configuration, assuming we are able to load
  the kernel module. Hence it should be safe to treat
  this the same as when **probed_cpu_visible_size** ==
  **probed_size**.
- `unallocated_cpu_visible_size`: Estimate of CPU
  visible memory remaining.

  Note this is only tracked for
  I915_MEMORY_CLASS_DEVICE regions (for other types the
  value here will always equal the
  **probed_cpu_visible_size**).

  Requires CAP_PERFMON or CAP_SYS_ADMIN to get reliable
  accounting.  Without this the value here will always
  equal the **probed_cpu_visible_size**. Note this is only
  currently tracked for I915_MEMORY_CLASS_DEVICE
  regions (for other types the value here will also
  always equal the **probed_cpu_visible_size**).

  If this is an older kernel the value here will be
  zero, see also **probed_cpu_visible_size**.

**Description**

Note this is using both struct drm_i915_query_item and struct drm_i915_query.
For this new query we are adding the new query id DRM_I915_QUERY_MEMORY_REGIONS
at [`drm_i915_query_item.query_id`](#c-struct-drm_i915_query_item).

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

**Definition**

```c
struct drm_i915_query_memory_regions {
    __u32 num_regions;
    __u32 rsvd[3];
    struct drm_i915_memory_region_info regions[];
};
```

**Members**

- `num_regions`: Number of supported regions
- `rsvd`: MBZ
- `regions`: Info about each supported region

**Description**

The region info query enumerates all regions known to the driver by filling
in an array of struct drm_i915_memory_region_info structures.

Example for getting the list of supported regions:

```C
struct drm_i915_query_memory_regions *info;
struct drm_i915_query_item item = {
        .query_id = DRM_I915_QUERY_MEMORY_REGIONS;
};
struct drm_i915_query query = {
        .num_items = 1,
        .items_ptr = (uintptr_t)&item,
};
int err, i;

// First query the size of the blob we need, this needs to be large
// enough to hold our array of regions. The kernel will fill out the
// item.length for us, which is the number of bytes we need.
err = ioctl(fd, DRM_IOCTL_I915_QUERY, &query);
if (err) ...

info = calloc(1, item.length);
// Now that we allocated the required number of bytes, we call the ioctl
// again, this time with the data_ptr pointing to our newly allocated
// blob, which the kernel can then populate with the all the region info.
item.data_ptr = (uintptr_t)&info,

err = ioctl(fd, DRM_IOCTL_I915_QUERY, &query);
if (err) ...

// We can now access each region in the array
for (i = 0; i < info->num_regions; i++) {
        struct drm_i915_memory_region_info mr = info->regions[i];
        u16 class = mr.region.class;
        u16 instance = mr.region.instance;

        ....
}

free(info);
```

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

query GuC submission interface version

**Definition**

```c
struct drm_i915_query_guc_submission_version {
    __u32 branch;
    __u32 major;
    __u32 minor;
    __u32 patch;
};
```

**Members**

- `branch`: Firmware branch version.
- `major`: Firmware major version.
- `minor`: Firmware minor version.
- `patch`: Firmware patch version.

**GuC HWCONFIG blob uAPI**

The GuC produces a blob with information about the current device.
i915 reads this blob from GuC and makes it available via this uAPI.

The format and meaning of the blob content are documented in the
Programmer's Reference Manual.

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

Existing gem_create behaviour, with added extension support using struct i915_user_extension.

**Definition**

```c
struct drm_i915_gem_create_ext {
        __u64 size;
        __u32 handle;
    #define I915_GEM_CREATE_EXT_FLAG_NEEDS_CPU_ACCESS (1 << 0);
        __u32 flags;
    #define I915_GEM_CREATE_EXT_MEMORY_REGIONS 0;
    #define I915_GEM_CREATE_EXT_PROTECTED_CONTENT 1;
    #define I915_GEM_CREATE_EXT_SET_PAT 2;
        __u64 extensions;
};
```

**Members**

- `size`: Requested size for the object.

  The (page-aligned) allocated size for the object will be returned.

  On platforms like DG2/ATS the kernel will always use 64K or larger
  pages for I915_MEMORY_CLASS_DEVICE. The kernel also requires a
  minimum of 64K GTT alignment for such objects.

  NOTE: Previously the ABI here required a minimum GTT alignment of 2M
  on DG2/ATS, due to how the hardware implemented 64K GTT page support,
  where we had the following complications:

  1) The entire PDE (which covers a 2MB virtual address range), must
     contain only 64K PTEs, i.e mixing 4K and 64K PTEs in the same
     PDE is forbidden by the hardware.

  2) We still need to support 4K PTEs for I915_MEMORY_CLASS_SYSTEM
     objects.

  However on actual production HW this was completely changed to now
  allow setting a TLB hint at the PTE level (see PS64), which is a lot
  more flexible than the above. With this the 2M restriction was
  dropped where we now only require 64K.
- `handle`: Returned handle for the object.

  Object handles are nonzero.
- `flags`: Optional flags.

  Supported values:

  I915_GEM_CREATE_EXT_FLAG_NEEDS_CPU_ACCESS - Signal to the kernel that
  the object will need to be accessed via the CPU.

  Only valid when placing objects in I915_MEMORY_CLASS_DEVICE, and only
  strictly required on configurations where some subset of the device
  memory is directly visible/mappable through the CPU (which we also
  call small BAR), like on some DG2+ systems. Note that this is quite
  undesirable, but due to various factors like the client CPU, BIOS etc
  it's something we can expect to see in the wild. See
  [`drm_i915_memory_region_info.probed_cpu_visible_size`](#c-struct-drm_i915_memory_region_info) for how to
  determine if this system applies.

  Note that one of the placements MUST be I915_MEMORY_CLASS_SYSTEM, to
  ensure the kernel can always spill the allocation to system memory,
  if the object can't be allocated in the mappable part of
  I915_MEMORY_CLASS_DEVICE.

  Also note that since the kernel only supports flat-CCS on objects
  that can *only* be placed in I915_MEMORY_CLASS_DEVICE, we therefore
  don't support I915_GEM_CREATE_EXT_FLAG_NEEDS_CPU_ACCESS together with
  flat-CCS.

  Without this hint, the kernel will assume that non-mappable
  I915_MEMORY_CLASS_DEVICE is preferred for this object. Note that the
  kernel can still migrate the object to the mappable part, as a last
  resort, if userspace ever CPU faults this object, but this might be
  expensive, and so ideally should be avoided.

  On older kernels which lack the relevant small-bar uAPI support (see
  also [`drm_i915_memory_region_info.probed_cpu_visible_size`](#c-struct-drm_i915_memory_region_info)),
  usage of the flag will result in an error, but it should NEVER be
  possible to end up with a small BAR configuration, assuming we can
  also successfully load the i915 kernel module. In such cases the
  entire I915_MEMORY_CLASS_DEVICE region will be CPU accessible, and as
  such there are zero restrictions on where the object can be placed.
- `extensions`: The chain of extensions to apply to this object.

  This will be useful in the future when we need to support several
  different extensions, and we need to apply more than one when
  creating the object. See struct i915_user_extension.

  If we don't supply any extensions then we get the same old gem_create
  behaviour.

  For I915_GEM_CREATE_EXT_MEMORY_REGIONS usage see
  struct drm_i915_gem_create_ext_memory_regions.

  For I915_GEM_CREATE_EXT_PROTECTED_CONTENT usage see
  struct drm_i915_gem_create_ext_protected_content.

  For I915_GEM_CREATE_EXT_SET_PAT usage see
  struct drm_i915_gem_create_ext_set_pat.

**Description**

Note that new buffer flags should be added here, at least for the stuff that
is immutable. Previously we would have two ioctls, one to create the object
with gem_create, and another to apply various parameters, however this
creates some ambiguity for the params which are considered immutable. Also in
general we're phasing out the various SET/GET ioctls.

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

The I915_GEM_CREATE_EXT_MEMORY_REGIONS extension.

**Definition**

```c
struct drm_i915_gem_create_ext_memory_regions {
    struct i915_user_extension base;
    __u32 pad;
    __u32 num_regions;
    __u64 regions;
};
```

**Members**

- `base`: Extension link. See struct i915_user_extension.
- `pad`: MBZ
- `num_regions`: Number of elements in the **regions** array.
- `regions`: The regions/placements array.

  An array of struct drm_i915_gem_memory_class_instance.

**Description**

Set the object with the desired set of placements/regions in priority
order. Each entry must be unique and supported by the device.

This is provided as an array of struct drm_i915_gem_memory_class_instance, or
an equivalent layout of class:instance pair encodings. See struct
drm_i915_query_memory_regions and DRM_I915_QUERY_MEMORY_REGIONS for how to
query the supported regions for a device.

As an example, on discrete devices, if we wish to set the placement as
device local-memory we can do something like:

```C
struct drm_i915_gem_memory_class_instance region_lmem = {
        .memory_class = I915_MEMORY_CLASS_DEVICE,
        .memory_instance = 0,
};
struct drm_i915_gem_create_ext_memory_regions regions = {
        .base = { .name = I915_GEM_CREATE_EXT_MEMORY_REGIONS },
        .regions = (uintptr_t)&region_lmem,
        .num_regions = 1,
};
struct drm_i915_gem_create_ext create_ext = {
        .size = 16 * PAGE_SIZE,
        .extensions = (uintptr_t)&regions,
};

int err = ioctl(fd, DRM_IOCTL_I915_GEM_CREATE_EXT, &create_ext);
if (err) ...
```

At which point we get the object handle in [`drm_i915_gem_create_ext.handle`](#c-struct-drm_i915_gem_create_ext),
along with the final object size in [`drm_i915_gem_create_ext.size`](#c-struct-drm_i915_gem_create_ext), which
should account for any rounding up, if required.

Note that userspace has no means of knowing the current backing region
for objects where **num_regions** is larger than one. The kernel will only
ensure that the priority order of the **regions** array is honoured, either
when initially placing the object, or when moving memory around due to
memory pressure

On Flat-CCS capable HW, compression is supported for the objects residing
in I915_MEMORY_CLASS_DEVICE. When such objects (compressed) have other
memory class in **regions** and migrated (by i915, due to memory
constraints) to the non I915_MEMORY_CLASS_DEVICE region, then i915 needs to
decompress the content. But i915 doesn't have the required information to
decompress the userspace compressed objects.

So i915 supports Flat-CCS, on the objects which can reside only on
I915_MEMORY_CLASS_DEVICE regions.

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

The I915_OBJECT_PARAM_PROTECTED_CONTENT extension.

**Definition**

```c
struct drm_i915_gem_create_ext_protected_content {
    struct i915_user_extension base;
    __u32 flags;
};
```

**Members**

- `base`: Extension link. See struct i915_user_extension.
- `flags`: reserved for future usage, currently MBZ

**Description**

If this extension is provided, buffer contents are expected to be protected
by PXP encryption and require decryption for scan out and processing. This
is only possible on platforms that have PXP enabled, on all other scenarios
using this extension will cause the ioctl to fail and return -ENODEV. The
flags parameter is reserved for future expansion and must currently be set
to zero.

The buffer contents are considered invalid after a PXP session teardown.

The encryption is guaranteed to be processed correctly only if the object
is submitted with a context created using the
I915_CONTEXT_PARAM_PROTECTED_CONTENT flag. This will also enable extra checks
at submission time on the validity of the objects involved.

Below is an example on how to create a protected object:

```C
struct drm_i915_gem_create_ext_protected_content protected_ext = {
        .base = { .name = I915_GEM_CREATE_EXT_PROTECTED_CONTENT },
        .flags = 0,
};
struct drm_i915_gem_create_ext create_ext = {
        .size = PAGE_SIZE,
        .extensions = (uintptr_t)&protected_ext,
};

int err = ioctl(fd, DRM_IOCTL_I915_GEM_CREATE_EXT, &create_ext);
if (err) ...
```

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

The I915_GEM_CREATE_EXT_SET_PAT extension.

**Definition**

```c
struct drm_i915_gem_create_ext_set_pat {
    struct i915_user_extension base;
    __u32 pat_index;
    __u32 rsvd;
};
```

**Members**

- `base`: Extension link. See struct i915_user_extension.
- `pat_index`: PAT index to be set
  PAT index is a bit field in Page Table Entry to control caching
  behaviors for GPU accesses. The definition of PAT index is
  platform dependent and can be found in hardware specifications,
- `rsvd`: reserved for future use

**Description**

If this extension is provided, the specified caching policy (PAT index) is
applied to the buffer object.

Below is an example on how to create an object with specific caching policy:

```C
struct drm_i915_gem_create_ext_set_pat set_pat_ext = {
        .base = { .name = I915_GEM_CREATE_EXT_SET_PAT },
        .pat_index = 0,
};
struct drm_i915_gem_create_ext create_ext = {
        .size = PAGE_SIZE,
        .extensions = (uintptr_t)&set_pat_ext,
};

int err = ioctl(fd, DRM_IOCTL_I915_GEM_CREATE_EXT, &create_ext);
if (err) ...
```


<a id="rst-drm-nouveau-uapi"></a>

## drm/nouveau uAPI

<a id="rst-vm-bind-exec-uapi"></a>

### VM_BIND / EXEC uAPI


Nouveau's VM_BIND / EXEC UAPI consists of three ioctls: DRM_NOUVEAU_VM_INIT,
DRM_NOUVEAU_VM_BIND and DRM_NOUVEAU_EXEC.

In order to use the UAPI firstly a user client must initialize the VA space
using the DRM_NOUVEAU_VM_INIT ioctl specifying which region of the VA space
should be managed by the kernel and which by the UMD.

The DRM_NOUVEAU_VM_BIND ioctl provides clients an interface to manage the
userspace-managable portion of the VA space. It provides operations to map
and unmap memory. Mappings may be flagged as sparse. Sparse mappings are not
backed by a GEM object and the kernel will ignore GEM handles provided
alongside a sparse mapping.

Userspace may request memory backed mappings either within or outside of the
bounds (but not crossing those bounds) of a previously mapped sparse
mapping. Subsequently requested memory backed mappings within a sparse
mapping will take precedence over the corresponding range of the sparse
mapping. If such memory backed mappings are unmapped the kernel will make
sure that the corresponding sparse mapping will take their place again.
Requests to unmap a sparse mapping that still contains memory backed mappings
will result in those memory backed mappings being unmapped first.

Unmap requests are not bound to the range of existing mappings and can even
overlap the bounds of sparse mappings. For such a request the kernel will
make sure to unmap all memory backed mappings within the given range,
splitting up memory backed mappings which are only partially contained
within the given range. Unmap requests with the sparse flag set must match
the range of a previously mapped sparse mapping exactly though.

While the kernel generally permits arbitrary sequences and ranges of memory
backed mappings being mapped and unmapped, either within a single or multiple
VM_BIND ioctl calls, there are some restrictions for sparse mappings.

- The kernel does not permit to:
  - unmap non-existent sparse mappings
  - unmap a sparse mapping and map a new sparse mapping overlapping the range
    of the previously unmapped sparse mapping within the same VM_BIND ioctl
  - unmap a sparse mapping and map new memory backed mappings overlapping the
    range of the previously unmapped sparse mapping within the same VM_BIND
    ioctl

When using the VM_BIND ioctl to request the kernel to map memory to a given
virtual address in the GPU's VA space there is no guarantee that the actual
mappings are created in the GPU's MMU. If the given memory is swapped out
at the time the bind operation is executed the kernel will stash the mapping
details into it's internal allocator and create the actual MMU mappings once
the memory is swapped back in. While this is transparent for userspace, it is
guaranteed that all the backing memory is swapped back in and all the memory
mappings, as requested by userspace previously, are actually mapped once the
DRM_NOUVEAU_EXEC ioctl is called to submit an exec job.

A VM_BIND job can be executed either synchronously or asynchronously. If
executed asynchronously, userspace may provide a list of syncobjs this job
will wait for and/or a list of syncobj the kernel will signal once the
VM_BIND job finished execution. If executed synchronously the ioctl will
block until the bind job is finished. For synchronous jobs the kernel will
not permit any syncobjs submitted to the kernel.

To execute a push buffer the UAPI provides the DRM_NOUVEAU_EXEC ioctl. EXEC
jobs are always executed asynchronously, and, equal to VM_BIND jobs, provide
the option to synchronize them with syncobjs.

Besides that, EXEC jobs can be scheduled for a specified channel to execute on.

Since VM_BIND jobs update the GPU's VA space on job submit, EXEC jobs do have
an up to date view of the VA space. However, the actual mappings might still
be pending. Hence, EXEC jobs require to have the particular fences - of
the corresponding VM_BIND jobs they depend on - attached to them.



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

sync object

**Definition**

```c
struct drm_nouveau_sync {
        __u32 flags;
    #define DRM_NOUVEAU_SYNC_SYNCOBJ 0x0;
    #define DRM_NOUVEAU_SYNC_TIMELINE_SYNCOBJ 0x1;
    #define DRM_NOUVEAU_SYNC_TYPE_MASK 0xf;
        __u32 handle;
        __u64 timeline_value;
};
```

**Members**

- `flags`: the flags for a sync object

  The first 8 bits are used to determine the type of the sync object.
- `handle`: the handle of the sync object
- `timeline_value`: The timeline point of the sync object in case the syncobj is of
  type DRM_NOUVEAU_SYNC_TIMELINE_SYNCOBJ.

**Description**

This structure serves as synchronization mechanism for (potentially)
asynchronous operations such as EXEC or VM_BIND.

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

GPU VA space init structure

**Definition**

```c
struct drm_nouveau_vm_init {
    __u64 kernel_managed_addr;
    __u64 kernel_managed_size;
};
```

**Members**

- `kernel_managed_addr`: start address of the kernel managed VA space
  region
- `kernel_managed_size`: size of the kernel managed VA space region in
  bytes

**Description**

Used to initialize the GPU's VA space for a user client, telling the kernel
which portion of the VA space is managed by the UMD and kernel respectively.

For the UMD to use the VM_BIND uAPI, this must be called before any BOs or
channels are created; if called afterwards DRM_IOCTL_NOUVEAU_VM_INIT fails
with -ENOSYS.

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

VM_BIND operation

**Definition**

```c
struct drm_nouveau_vm_bind_op {
        __u32 op;
    #define DRM_NOUVEAU_VM_BIND_OP_MAP 0x0;
    #define DRM_NOUVEAU_VM_BIND_OP_UNMAP 0x1;
        __u32 flags;
    #define DRM_NOUVEAU_VM_BIND_SPARSE (1 << 8);
        __u32 handle;
        __u32 pad;
        __u64 addr;
        __u64 bo_offset;
        __u64 range;
};
```

**Members**

- `op`: the operation type

  Supported values:

  `DRM_NOUVEAU_VM_BIND_OP_MAP` - Map a GEM object to the GPU's VA
  space. Optionally, the `DRM_NOUVEAU_VM_BIND_SPARSE` flag can be
  passed to instruct the kernel to create sparse mappings for the
  given range.

  `DRM_NOUVEAU_VM_BIND_OP_UNMAP` - Unmap an existing mapping in the
  GPU's VA space. If the region the mapping is located in is a
  sparse region, new sparse mappings are created where the unmapped
  (memory backed) mapping was mapped previously. To remove a sparse
  region the `DRM_NOUVEAU_VM_BIND_SPARSE` must be set.
- `flags`: the flags for a [`drm_nouveau_vm_bind_op`](#c-struct-drm_nouveau_vm_bind_op)

  Supported values:

  `DRM_NOUVEAU_VM_BIND_SPARSE` - Indicates that an allocated VA
  space region should be sparse.
- `handle`: the handle of the DRM GEM object to map
- `pad`: 32 bit padding, should be 0
- `addr`: the address the VA space region or (memory backed) mapping should be mapped to
- `bo_offset`: the offset within the BO backing the mapping
- `range`: the size of the requested mapping in bytes

**Description**

This structure represents a single VM_BIND operation. UMDs should pass
an array of this structure via struct drm_nouveau_vm_bind's `op_ptr` field.

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

structure for DRM_IOCTL_NOUVEAU_VM_BIND

**Definition**

```c
struct drm_nouveau_vm_bind {
        __u32 op_count;
        __u32 flags;
    #define DRM_NOUVEAU_VM_BIND_RUN_ASYNC 0x1;
        __u32 wait_count;
        __u32 sig_count;
        __u64 wait_ptr;
        __u64 sig_ptr;
        __u64 op_ptr;
};
```

**Members**

- `op_count`: the number of [`drm_nouveau_vm_bind_op`](#c-struct-drm_nouveau_vm_bind_op)
- `flags`: the flags for a [`drm_nouveau_vm_bind`](#c-struct-drm_nouveau_vm_bind) ioctl

  Supported values:

  `DRM_NOUVEAU_VM_BIND_RUN_ASYNC` - Indicates that the given VM_BIND
  operation should be executed asynchronously by the kernel.

  If this flag is not supplied the kernel executes the associated
  operations synchronously and doesn't accept any [`drm_nouveau_sync`](#c-struct-drm_nouveau_sync)
  objects.
- `wait_count`: the number of wait `drm_nouveau_syncs`
- `sig_count`: the number of `drm_nouveau_syncs` to signal when finished
- `wait_ptr`: pointer to `drm_nouveau_syncs` to wait for
- `sig_ptr`: pointer to `drm_nouveau_syncs` to signal when finished
- `op_ptr`: pointer to the `drm_nouveau_vm_bind_ops` to execute

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

EXEC push operation

**Definition**

```c
struct drm_nouveau_exec_push {
        __u64 va;
        __u32 va_len;
        __u32 flags;
    #define DRM_NOUVEAU_EXEC_PUSH_NO_PREFETCH 0x1;
};
```

**Members**

- `va`: the virtual address of the push buffer mapping
- `va_len`: the length of the push buffer mapping
- `flags`: the flags for this push buffer mapping

**Description**

This structure represents a single EXEC push operation. UMDs should pass an
array of this structure via struct drm_nouveau_exec's `push_ptr` field.

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

structure for DRM_IOCTL_NOUVEAU_EXEC

**Definition**

```c
struct drm_nouveau_exec {
    __u32 channel;
    __u32 push_count;
    __u32 wait_count;
    __u32 sig_count;
    __u64 wait_ptr;
    __u64 sig_ptr;
    __u64 push_ptr;
};
```

**Members**

- `channel`: the channel to execute the push buffer in
- `push_count`: the number of [`drm_nouveau_exec_push`](#c-struct-drm_nouveau_exec_push) ops
- `wait_count`: the number of wait `drm_nouveau_syncs`
- `sig_count`: the number of `drm_nouveau_syncs` to signal when finished
- `wait_ptr`: pointer to `drm_nouveau_syncs` to wait for
- `sig_ptr`: pointer to `drm_nouveau_syncs` to signal when finished
- `push_ptr`: pointer to [`drm_nouveau_exec_push`](#c-struct-drm_nouveau_exec_push) ops


<a id="rst-drm-panthor-uapi"></a>

## drm/panthor uAPI


**Introduction**

This documentation describes the Panthor IOCTLs.

Just a few generic rules about the data passed to the Panthor IOCTLs:

- Structures must be aligned on 64-bit/8-byte. If the object is not
  naturally aligned, a padding field must be added.
- Fields must be explicitly aligned to their natural type alignment with
  pad\[0..N\] fields.
- All padding fields will be checked by the driver to make sure they are
  zeroed.
- Flags can be added, but not removed/replaced.
- New fields can be added to the main structures (the structures
  directly passed to the ioctl). Those fields can be added at the end of
  the structure, or replace existing padding fields. Any new field being
  added must preserve the behavior that existed before those fields were
  added when a value of zero is passed.
- New fields can be added to indirect objects (objects pointed by the
  main structure), iff those objects are passed a size to reflect the
  size known by the userspace driver (see drm_panthor_obj_array::stride
  or drm_panthor_dev_query::size).
- If the kernel driver is too old to know some fields, those will be
  ignored if zero, and otherwise rejected (and so will be zero on output).
- If userspace is too old to know some fields, those will be zeroed
  (input) before the structure is parsed by the kernel driver.
- Each new flag/field addition must come with a driver version update so
  the userspace driver doesn't have to trial and error to know which
  flags are supported.
- Structures should not contain unions, as this would defeat the
  extensibility of such structures.
- IOCTLs can't be removed or replaced. New IOCTL IDs should be placed
  at the end of the drm_panthor_ioctl_id enum.

**MMIO regions exposed to userspace.**

#### <a id="c-DRM_PANTHOR_USER_MMIO_OFFSET"></a>`DRM_PANTHOR_USER_MMIO_OFFSET`

File offset for all MMIO regions being exposed to userspace. Don't use
this value directly, use DRM_PANTHOR_USER_\<name>_OFFSET values instead.
pgoffset passed to `mmap2()` is an unsigned long, which forces us to use a
different offset on 32-bit and 64-bit systems.

#### <a id="c-DRM_PANTHOR_USER_FLUSH_ID_MMIO_OFFSET"></a>`DRM_PANTHOR_USER_FLUSH_ID_MMIO_OFFSET`

File offset for the LATEST_FLUSH_ID register. The Userspace driver controls
GPU cache flushing through CS instructions, but the flush reduction
mechanism requires a flush_id. This flush_id could be queried with an
ioctl, but Arm provides a well-isolated register page containing only this
read-only register, so let's expose this page through a static mmap offset
and allow direct mapping of this MMIO region so we can avoid the
user \<-> kernel round-trip.

**IOCTL IDs**

enum drm_panthor_ioctl_id - IOCTL IDs

Place new ioctls at the end, don't re-order, don't replace or remove entries.

These IDs are not meant to be used directly. Use the DRM_IOCTL_PANTHOR_xxx
definitions instead.

**IOCTL arguments**

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

Object array.

**Definition**

```c
struct drm_panthor_obj_array {
    __u32 stride;
    __u32 count;
    __u64 array;
};
```

**Members**

- `stride`: Stride of object struct. Used for versioning.
- `count`: Number of objects in the array.
- `array`: User pointer to an array of objects.

**Description**

This object is used to pass an array of objects whose size is subject to changes in
future versions of the driver. In order to support this mutability, we pass a stride
describing the size of the object as known by userspace.

You shouldn't fill drm_panthor_obj_array fields directly. You should instead use
the [`DRM_PANTHOR_OBJ_ARRAY()`](#c-DRM_PANTHOR_OBJ_ARRAY) macro that takes care of initializing the stride to
the object size.

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

```c
DRM_PANTHOR_OBJ_ARRAY(cnt, ptr)
```

Initialize a drm_panthor_obj_array field.

**Parameters**

- `cnt`: Number of elements in the array.
- `ptr`: Pointer to the array to pass to the kernel.

**Description**

Macro initializing a drm_panthor_obj_array based on the object size as known
by userspace.

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

Synchronization operation flags.

**Constants**

- `DRM_PANTHOR_SYNC_OP_HANDLE_TYPE_MASK`: Synchronization handle type mask.
- `DRM_PANTHOR_SYNC_OP_HANDLE_TYPE_SYNCOBJ`: Synchronization object type.
- `DRM_PANTHOR_SYNC_OP_HANDLE_TYPE_TIMELINE_SYNCOBJ`: Timeline synchronization
  object type.
- `DRM_PANTHOR_SYNC_OP_WAIT`: Wait operation.
- `DRM_PANTHOR_SYNC_OP_SIGNAL`: Signal operation.

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

Synchronization operation.

**Definition**

```c
struct drm_panthor_sync_op {
    __u32 flags;
    __u32 handle;
    __u64 timeline_value;
};
```

**Members**

- `flags`: Synchronization operation flags. Combination of DRM_PANTHOR_SYNC_OP values.
- `handle`: Sync handle.
- `timeline_value`: MBZ if
  (flags & DRM_PANTHOR_SYNC_OP_HANDLE_TYPE_MASK) !=
  DRM_PANTHOR_SYNC_OP_HANDLE_TYPE_TIMELINE_SYNCOBJ.

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

Query type

**Constants**

- `DRM_PANTHOR_DEV_QUERY_GPU_INFO`: Query GPU information.
- `DRM_PANTHOR_DEV_QUERY_CSIF_INFO`: Query command-stream interface information.
- `DRM_PANTHOR_DEV_QUERY_TIMESTAMP_INFO`: Query timestamp information.
- `DRM_PANTHOR_DEV_QUERY_GROUP_PRIORITIES_INFO`: Query allowed group priorities information.

**Description**

Place new types at the end, don't re-order, don't remove or replace.

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

Type of GPU coherency

**Constants**

- `DRM_PANTHOR_GPU_COHERENCY_ACE_LITE`: ACE Lite coherency.
- `DRM_PANTHOR_GPU_COHERENCY_ACE`: ACE coherency.
- `DRM_PANTHOR_GPU_COHERENCY_NONE`: No coherency.

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

GPU information

**Definition**

```c
struct drm_panthor_gpu_info {
        __u32 gpu_id;
    #define DRM_PANTHOR_ARCH_MAJOR(x)               ((x) >> 28);
    #define DRM_PANTHOR_ARCH_MINOR(x)               (((x) >> 24) & 0xf);
    #define DRM_PANTHOR_ARCH_REV(x)                 (((x) >> 20) & 0xf);
    #define DRM_PANTHOR_PRODUCT_MAJOR(x)            (((x) >> 16) & 0xf);
    #define DRM_PANTHOR_VERSION_MAJOR(x)            (((x) >> 12) & 0xf);
    #define DRM_PANTHOR_VERSION_MINOR(x)            (((x) >> 4) & 0xff);
    #define DRM_PANTHOR_VERSION_STATUS(x)           ((x) & 0xf);
        __u32 gpu_rev;
        __u32 csf_id;
    #define DRM_PANTHOR_CSHW_MAJOR(x)               (((x) >> 26) & 0x3f);
    #define DRM_PANTHOR_CSHW_MINOR(x)               (((x) >> 20) & 0x3f);
    #define DRM_PANTHOR_CSHW_REV(x)                 (((x) >> 16) & 0xf);
    #define DRM_PANTHOR_MCU_MAJOR(x)                (((x) >> 10) & 0x3f);
    #define DRM_PANTHOR_MCU_MINOR(x)                (((x) >> 4) & 0x3f);
    #define DRM_PANTHOR_MCU_REV(x)                  ((x) & 0xf);
        __u32 l2_features;
        __u32 tiler_features;
        __u32 mem_features;
        __u32 mmu_features;
    #define DRM_PANTHOR_MMU_VA_BITS(x)              ((x) & 0xff);
        __u32 thread_features;
        __u32 max_threads;
        __u32 thread_max_workgroup_size;
        __u32 thread_max_barrier_size;
        __u32 coherency_features;
        __u32 texture_features[4];
        __u32 as_present;
        __u32 selected_coherency;
        __u64 shader_present;
        __u64 l2_present;
        __u64 tiler_present;
        __u32 core_features;
        __u32 pad;
        __u64 gpu_features;
};
```

**Members**

- `gpu_id`: GPU ID.
- `gpu_rev`: GPU revision.
- `csf_id`: Command stream frontend ID.
- `l2_features`: L2-cache features.
- `tiler_features`: Tiler features.
- `mem_features`: Memory features.
- `mmu_features`: MMU features.
- `thread_features`: Thread features.
- `max_threads`: Maximum number of threads.
- `thread_max_workgroup_size`: Maximum workgroup size.
- `thread_max_barrier_size`: Maximum number of threads that can wait
  simultaneously on a barrier.
- `coherency_features`: Coherency features.

  Combination of drm_panthor_gpu_coherency flags.

  Note that this is just what the coherency protocols supported by the
  GPU, but the actual coherency in place depends on the SoC
  integration and is reflected by
  drm_panthor_gpu_info::selected_coherency.
- `texture_features`: Texture features.
- `as_present`: Bitmask encoding the number of address-space exposed by the MMU.
- `selected_coherency`: Coherency selected for this device.

  One of drm_panthor_gpu_coherency.
- `shader_present`: Bitmask encoding the shader cores exposed by the GPU.
- `l2_present`: Bitmask encoding the L2 caches exposed by the GPU.
- `tiler_present`: Bitmask encoding the tiler units exposed by the GPU.
- `core_features`: Used to discriminate core variants when they exist.
- `pad`: MBZ.
- `gpu_features`: Bitmask describing supported GPU-wide features

**Description**

Structure grouping all queryable information relating to the GPU.

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

Command stream interface information

**Definition**

```c
struct drm_panthor_csif_info {
    __u32 csg_slot_count;
    __u32 cs_slot_count;
    __u32 cs_reg_count;
    __u32 scoreboard_slot_count;
    __u32 unpreserved_cs_reg_count;
    __u32 pad;
};
```

**Members**

- `csg_slot_count`: Number of command stream group slots exposed by the firmware.
- `cs_slot_count`: Number of command stream slots per group.
- `cs_reg_count`: Number of command stream registers.
- `scoreboard_slot_count`: Number of scoreboard slots.
- `unpreserved_cs_reg_count`: Number of command stream registers reserved by
  the kernel driver to call a userspace command stream.

  All registers can be used by a userspace command stream, but the
  \[cs_slot_count - unpreserved_cs_reg_count .. cs_slot_count\] registers are
  used by the kernel when DRM_PANTHOR_IOCTL_GROUP_SUBMIT is called.
- `pad`: Padding field, set to zero.

**Description**

Structure grouping all queryable information relating to the command stream interface.

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

Timestamp information

**Definition**

```c
struct drm_panthor_timestamp_info {
    __u64 timestamp_frequency;
    __u64 current_timestamp;
    __u64 timestamp_offset;
};
```

**Members**

- `timestamp_frequency`: The frequency of the timestamp timer or 0 if
  unknown.
- `current_timestamp`: The current timestamp.
- `timestamp_offset`: The offset of the timestamp timer.

**Description**

Structure grouping all queryable information relating to the GPU timestamp.

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

Group priorities information

**Definition**

```c
struct drm_panthor_group_priorities_info {
    __u8 allowed_mask;
    __u8 pad[3];
};
```

**Members**

- `allowed_mask`: Bitmask of the allowed group priorities.

  Each bit represents a variant of the enum drm_panthor_group_priority.
- `pad`: Padding fields, MBZ.

**Description**

Structure grouping all queryable information relating to the allowed group priorities.

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

Arguments passed to DRM_PANTHOR_IOCTL_DEV_QUERY

**Definition**

```c
struct drm_panthor_dev_query {
    __u32 type;
    __u32 size;
    __u64 pointer;
};
```

**Members**

- `type`: the query type (see drm_panthor_dev_query_type).
- `size`: size of the type being queried.

  If pointer is NULL, size is updated by the driver to provide the
  output structure size. If pointer is not NULL, the driver will
  only copy min(size, actual_structure_size) bytes to the pointer,
  and update the size accordingly. This allows us to extend query
  types without breaking userspace.
- `pointer`: user pointer to a query type struct.

  Pointer can be NULL, in which case, nothing is copied, but the
  actual structure size is returned. If not NULL, it must point to
  a location that's large enough to hold size bytes.

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

Arguments passed to DRM_PANTHOR_IOCTL_VM_CREATE

**Definition**

```c
struct drm_panthor_vm_create {
    __u32 flags;
    __u32 id;
    __u64 user_va_range;
};
```

**Members**

- `flags`: VM flags, MBZ.
- `id`: Returned VM ID.
- `user_va_range`: Size of the VA space reserved for user objects.

  The kernel will pick the remaining space to map kernel-only objects to the
  VM (heap chunks, heap context, ring buffers, kernel synchronization objects,
  ...). If the space left for kernel objects is too small, kernel object
  allocation will fail further down the road. One can use
  drm_panthor_gpu_info::mmu_features to extract the total virtual address
  range, and chose a user_va_range that leaves some space to the kernel.

  If user_va_range is zero, the kernel will pick a sensible value based on
  TASK_SIZE and the virtual range supported by the GPU MMU (the kernel/user
  split should leave enough VA space for userspace processes to support SVM,
  while still allowing the kernel to map some amount of kernel objects in
  the kernel VA range). The value chosen by the driver will be returned in
  **user_va_range**.

  User VA space always starts at 0x0, kernel VA space is always placed after
  the user VA range.

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

Arguments passed to DRM_PANTHOR_IOCTL_VM_DESTROY

**Definition**

```c
struct drm_panthor_vm_destroy {
    __u32 id;
    __u32 pad;
};
```

**Members**

- `id`: ID of the VM to destroy.
- `pad`: MBZ.

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

VM bind operation flags

**Constants**

- `DRM_PANTHOR_VM_BIND_OP_MAP_READONLY`: Map the memory read-only.

  Only valid with DRM_PANTHOR_VM_BIND_OP_TYPE_MAP.
- `DRM_PANTHOR_VM_BIND_OP_MAP_NOEXEC`: Map the memory not-executable.

  Only valid with DRM_PANTHOR_VM_BIND_OP_TYPE_MAP.
- `DRM_PANTHOR_VM_BIND_OP_MAP_UNCACHED`: Map the memory uncached.

  Only valid with DRM_PANTHOR_VM_BIND_OP_TYPE_MAP.
- `DRM_PANTHOR_VM_BIND_OP_TYPE_MASK`: Mask used to determine the type of operation.
- `DRM_PANTHOR_VM_BIND_OP_TYPE_MAP`: Map operation.
- `DRM_PANTHOR_VM_BIND_OP_TYPE_UNMAP`: Unmap operation.
- `DRM_PANTHOR_VM_BIND_OP_TYPE_SYNC_ONLY`: No VM operation.

  Just serves as a synchronization point on a VM queue.

  Only valid if `DRM_PANTHOR_VM_BIND_ASYNC` is set in drm_panthor_vm_bind::flags,
  and drm_panthor_vm_bind_op::syncs contains at least one element.

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

VM bind operation

**Definition**

```c
struct drm_panthor_vm_bind_op {
    __u32 flags;
    __u32 bo_handle;
    __u64 bo_offset;
    __u64 va;
    __u64 size;
    struct drm_panthor_obj_array syncs;
};
```

**Members**

- `flags`: Combination of drm_panthor_vm_bind_op_flags flags.
- `bo_handle`: Handle of the buffer object to map.
  MBZ for unmap or sync-only operations.
- `bo_offset`: Buffer object offset.
  MBZ for unmap or sync-only operations.
- `va`: Virtual address to map/unmap.
  MBZ for sync-only operations.
- `size`: Size to map/unmap.
  MBZ for sync-only operations.
- `syncs`: Array of struct drm_panthor_sync_op synchronization
  operations.

  This array must be empty if `DRM_PANTHOR_VM_BIND_ASYNC` is not set on
  the drm_panthor_vm_bind object containing this VM bind operation.

  This array shall not be empty for sync-only operations.

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

VM bind flags

**Constants**

- `DRM_PANTHOR_VM_BIND_ASYNC`: VM bind operations are queued to the VM
  queue instead of being executed synchronously.

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

Arguments passed to DRM_IOCTL_PANTHOR_VM_BIND

**Definition**

```c
struct drm_panthor_vm_bind {
    __u32 vm_id;
    __u32 flags;
    struct drm_panthor_obj_array ops;
};
```

**Members**

- `vm_id`: VM targeted by the bind request.
- `flags`: Combination of drm_panthor_vm_bind_flags flags.
- `ops`: Array of struct drm_panthor_vm_bind_op bind operations.

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

VM states.

**Constants**

- `DRM_PANTHOR_VM_STATE_USABLE`: VM is usable.

  New VM operations will be accepted on this VM.
- `DRM_PANTHOR_VM_STATE_UNUSABLE`: VM is unusable.

  Something put the VM in an unusable state (like an asynchronous
  VM_BIND request failing for any reason).

  Once the VM is in this state, all new MAP operations will be
  rejected, and any GPU job targeting this VM will fail.
  UNMAP operations are still accepted.

  The only way to recover from an unusable VM is to create a new
  VM, and destroy the old one.

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

Get VM state.

**Definition**

```c
struct drm_panthor_vm_get_state {
    __u32 vm_id;
    __u32 state;
};
```

**Members**

- `vm_id`: VM targeted by the get_state request.
- `state`: state returned by the driver.

  Must be one of the enum drm_panthor_vm_state values.

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

Buffer object flags, passed at creation time.

**Constants**

- `DRM_PANTHOR_BO_NO_MMAP`: The buffer object will never be CPU-mapped in userspace.
- `DRM_PANTHOR_BO_WB_MMAP`: Force "Write-Back Cacheable" CPU mapping.

  CPU map the buffer object in userspace by forcing the "Write-Back
  Cacheable" cacheability attribute. The mapping otherwise uses the
  "Non-Cacheable" attribute if the GPU is not IO coherent.

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

Arguments passed to DRM_IOCTL_PANTHOR_BO_CREATE.

**Definition**

```c
struct drm_panthor_bo_create {
    __u64 size;
    __u32 flags;
    __u32 exclusive_vm_id;
    __u32 handle;
    __u32 pad;
};
```

**Members**

- `size`: Requested size for the object

  The (page-aligned) allocated size for the object will be returned.
- `flags`: Flags. Must be a combination of drm_panthor_bo_flags flags.
- `exclusive_vm_id`: Exclusive VM this buffer object will be mapped to.

  - If not zero, the field must refer to a valid VM ID, and implies that:
    - the buffer object will only ever be bound to that VM
    - cannot be exported as a PRIME fd
- `handle`: Returned handle for the object.

  Object handles are nonzero.
- `pad`: MBZ.

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

Arguments passed to DRM_IOCTL_PANTHOR_BO_MMAP_OFFSET.

**Definition**

```c
struct drm_panthor_bo_mmap_offset {
    __u32 handle;
    __u32 pad;
    __u64 offset;
};
```

**Members**

- `handle`: Handle of the object we want an mmap offset for.
- `pad`: MBZ.
- `offset`: The fake offset to use for subsequent mmap calls.

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

Queue creation arguments.

**Definition**

```c
struct drm_panthor_queue_create {
    __u8 priority;
    __u8 pad[3];
    __u32 ringbuf_size;
};
```

**Members**

- `priority`: Defines the priority of queues inside a group. Goes from 0 to 15,
  15 being the highest priority.
- `pad`: Padding fields, MBZ.
- `ringbuf_size`: Size of the ring buffer to allocate to this queue.

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

Scheduling group priority

**Constants**

- `PANTHOR_GROUP_PRIORITY_LOW`: Low priority group.
- `PANTHOR_GROUP_PRIORITY_MEDIUM`: Medium priority group.
- `PANTHOR_GROUP_PRIORITY_HIGH`: High priority group.

  Requires CAP_SYS_NICE or DRM_MASTER.
- `PANTHOR_GROUP_PRIORITY_REALTIME`: Realtime priority group.

  Requires CAP_SYS_NICE or DRM_MASTER.

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

Arguments passed to DRM_IOCTL_PANTHOR_GROUP_CREATE

**Definition**

```c
struct drm_panthor_group_create {
    struct drm_panthor_obj_array queues;
    __u8 max_compute_cores;
    __u8 max_fragment_cores;
    __u8 max_tiler_cores;
    __u8 priority;
    __u32 pad;
    __u64 compute_core_mask;
    __u64 fragment_core_mask;
    __u64 tiler_core_mask;
    __u32 vm_id;
    __u32 group_handle;
};
```

**Members**

- `queues`: Array of drm_panthor_queue_create elements.
- `max_compute_cores`: Maximum number of cores that can be used by compute
  jobs across CS queues bound to this group.

  Must be less or equal to the number of bits set in **compute_core_mask**.
- `max_fragment_cores`: Maximum number of cores that can be used by fragment
  jobs across CS queues bound to this group.

  Must be less or equal to the number of bits set in **fragment_core_mask**.
- `max_tiler_cores`: Maximum number of tilers that can be used by tiler jobs
  across CS queues bound to this group.

  Must be less or equal to the number of bits set in **tiler_core_mask**.
- `priority`: Group priority (see enum drm_panthor_group_priority).
- `pad`: Padding field, MBZ.
- `compute_core_mask`: Mask encoding cores that can be used for compute jobs.

  This field must have at least **max_compute_cores** bits set.

  The bits set here should also be set in drm_panthor_gpu_info::shader_present.
- `fragment_core_mask`: Mask encoding cores that can be used for fragment jobs.

  This field must have at least **max_fragment_cores** bits set.

  The bits set here should also be set in drm_panthor_gpu_info::shader_present.
- `tiler_core_mask`: Mask encoding cores that can be used for tiler jobs.

  This field must have at least **max_tiler_cores** bits set.

  The bits set here should also be set in drm_panthor_gpu_info::tiler_present.
- `vm_id`: VM ID to bind this group to.

  All submission to queues bound to this group will use this VM.
- `group_handle`: Returned group handle. Passed back when submitting jobs or
  destroying a group.

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

Arguments passed to DRM_IOCTL_PANTHOR_GROUP_DESTROY

**Definition**

```c
struct drm_panthor_group_destroy {
    __u32 group_handle;
    __u32 pad;
};
```

**Members**

- `group_handle`: Group to destroy
- `pad`: Padding field, MBZ.

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

Job submission arguments.

**Definition**

```c
struct drm_panthor_queue_submit {
    __u32 queue_index;
    __u32 stream_size;
    __u64 stream_addr;
    __u32 latest_flush;
    __u32 pad;
    struct drm_panthor_obj_array syncs;
};
```

**Members**

- `queue_index`: Index of the queue inside a group.
- `stream_size`: Size of the command stream to execute.

  Must be 64-bit/8-byte aligned (the size of a CS instruction)

  Can be zero if stream_addr is zero too.

  When the stream size is zero, the queue submit serves as a
  synchronization point.
- `stream_addr`: GPU address of the command stream to execute.

  Must be aligned on 64-byte.

  Can be zero is stream_size is zero too.
- `latest_flush`: FLUSH_ID read at the time the stream was built.

  This allows cache flush elimination for the automatic
  flush+invalidate(all) done at submission time, which is needed to
  ensure the GPU doesn't get garbage when reading the indirect command
  stream buffers. If you want the cache flush to happen
  unconditionally, pass a zero here.

  Ignored when stream_size is zero.
- `pad`: MBZ.
- `syncs`: Array of struct drm_panthor_sync_op sync operations.

**Description**

This is describing the userspace command stream to call from the kernel
command stream ring-buffer. Queue submission is always part of a group
submission, taking one or more jobs to submit to the underlying queues.

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

Arguments passed to DRM_IOCTL_PANTHOR_GROUP_SUBMIT

**Definition**

```c
struct drm_panthor_group_submit {
    __u32 group_handle;
    __u32 pad;
    struct drm_panthor_obj_array queue_submits;
};
```

**Members**

- `group_handle`: Handle of the group to queue jobs to.
- `pad`: MBZ.
- `queue_submits`: Array of drm_panthor_queue_submit objects.

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

Group state flags

**Constants**

- `DRM_PANTHOR_GROUP_STATE_TIMEDOUT`: Group had unfinished jobs.

  When a group ends up with this flag set, no jobs can be submitted to its queues.
- `DRM_PANTHOR_GROUP_STATE_FATAL_FAULT`: Group had fatal faults.

  When a group ends up with this flag set, no jobs can be submitted to its queues.
- `DRM_PANTHOR_GROUP_STATE_INNOCENT`: Group was killed during a reset caused by other
  groups.

  This flag can only be set if DRM_PANTHOR_GROUP_STATE_TIMEDOUT is set and
  DRM_PANTHOR_GROUP_STATE_FATAL_FAULT is not.

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

Arguments passed to DRM_IOCTL_PANTHOR_GROUP_GET_STATE

**Definition**

```c
struct drm_panthor_group_get_state {
    __u32 group_handle;
    __u32 state;
    __u32 fatal_queues;
    __u32 pad;
};
```

**Members**

- `group_handle`: Handle of the group to query state on
- `state`: Combination of DRM_PANTHOR_GROUP_STATE_* flags encoding the
  group state.
- `fatal_queues`: Bitmask of queues that faced fatal faults.
- `pad`: MBZ

**Description**

Used to query the state of a group and decide whether a new group should be created to
replace it.

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

Arguments passed to DRM_IOCTL_PANTHOR_TILER_HEAP_CREATE

**Definition**

```c
struct drm_panthor_tiler_heap_create {
    __u32 vm_id;
    __u32 initial_chunk_count;
    __u32 chunk_size;
    __u32 max_chunks;
    __u32 target_in_flight;
    __u32 handle;
    __u64 tiler_heap_ctx_gpu_va;
    __u64 first_heap_chunk_gpu_va;
};
```

**Members**

- `vm_id`: VM ID the tiler heap should be mapped to
- `initial_chunk_count`: Initial number of chunks to allocate. Must be at least one.
- `chunk_size`: Chunk size.

  Must be page-aligned and lie in the \[128k:8M\] range.
- `max_chunks`: Maximum number of chunks that can be allocated.

  Must be at least **initial_chunk_count**.
- `target_in_flight`: Maximum number of in-flight render passes.

  If the heap has more than tiler jobs in-flight, the FW will wait for render
  passes to finish before queuing new tiler jobs.
- `handle`: Returned heap handle. Passed back to DESTROY_TILER_HEAP.
- `tiler_heap_ctx_gpu_va`: Returned heap GPU virtual address returned
- `first_heap_chunk_gpu_va`: First heap chunk.

  The tiler heap is formed of heap chunks forming a single-link list. This
  is the first element in the list.

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

Arguments passed to DRM_IOCTL_PANTHOR_TILER_HEAP_DESTROY

**Definition**

```c
struct drm_panthor_tiler_heap_destroy {
    __u32 handle;
    __u32 pad;
};
```

**Members**

- `handle`: Handle of the tiler heap to destroy.

  Must be a valid heap handle returned by DRM_IOCTL_PANTHOR_TILER_HEAP_CREATE.
- `pad`: Padding field, MBZ.

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

Arguments passed to DRM_IOCTL_PANTHOR_BO_SET_LABEL

**Definition**

```c
struct drm_panthor_bo_set_label {
    __u32 handle;
    __u32 pad;
    __u64 label;
};
```

**Members**

- `handle`: Handle of the buffer object to label.
- `pad`: MBZ.
- `label`: User pointer to a NUL-terminated string

  Length cannot be greater than 4096

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

Arguments passed to DRM_IOCTL_PANTHOR_SET_USER_MMIO_OFFSET

**Definition**

```c
struct drm_panthor_set_user_mmio_offset {
    __u64 offset;
};
```

**Members**

- `offset`: User MMIO offset to use.

  Must be either DRM_PANTHOR_USER_MMIO_OFFSET_32BIT or
  DRM_PANTHOR_USER_MMIO_OFFSET_64BIT.

  Use DRM_PANTHOR_USER_MMIO_OFFSET (which selects OFFSET_32BIT or
  OFFSET_64BIT based on the size of an unsigned long) unless you
  have a very good reason to overrule this decision.

**Description**

This ioctl is only really useful if you want to support userspace
CPU emulation environments where the size of an unsigned long differs
between the host and the guest architectures.

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

BO sync type

**Constants**

- `DRM_PANTHOR_BO_SYNC_CPU_CACHE_FLUSH`: Flush CPU caches.
- `DRM_PANTHOR_BO_SYNC_CPU_CACHE_FLUSH_AND_INVALIDATE`: Flush and invalidate CPU caches.

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

BO map sync op

**Definition**

```c
struct drm_panthor_bo_sync_op {
    __u32 handle;
    __u32 type;
    __u64 offset;
    __u64 size;
};
```

**Members**

- `handle`: Handle of the buffer object to sync.
- `type`: Type of operation.
- `offset`: Offset into the BO at which the sync range starts.

  This will be rounded down to the nearest cache line as needed.
- `size`: Size of the range to sync

  **size** + **offset** will be rounded up to the nearest cache line as
  needed.

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

BO map sync request

**Definition**

```c
struct drm_panthor_bo_sync {
    struct drm_panthor_obj_array ops;
};
```

**Members**

- `ops`: Array of struct drm_panthor_bo_sync_op sync operations.

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

Set of flags returned on a BO_QUERY_INFO request

**Constants**

- `DRM_PANTHOR_BO_IS_IMPORTED`: BO has been imported from an external driver.

  Note that imported dma-buf handles are not flagged as imported if they
  where exported by panthor. Only buffers that are coming from other drivers
  (dma heaps, other GPUs, display controllers, V4L, ...).

  It's also important to note that all imported BOs are mapped cached and can't
  be considered IO-coherent even if the GPU is. This means they require explicit
  syncs that must go through the DRM_PANTHOR_BO_SYNC ioctl (userland cache
  maintenance is not allowed in that case, because extra operations might be
  needed to make changes visible to the CPU/device, like buffer migration when the
  exporter is a GPU with its own VRAM).

**Description**

Those are flags reflecting BO properties that are not directly coming from the flags
passed are creation time, or information on BOs that were imported from other drivers.

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

Query BO info

**Definition**

```c
struct drm_panthor_bo_query_info {
    __u32 handle;
    __u32 extra_flags;
    __u32 create_flags;
    __u32 pad;
};
```

**Members**

- `handle`: Handle of the buffer object to query flags on.
- `extra_flags`: Combination of enum drm_panthor_bo_extra_flags flags.
- `create_flags`: Flags passed at creation time.

  Combination of enum drm_panthor_bo_flags flags.
  Will be zero if the buffer comes from a different driver.
- `pad`: Will be zero on return.

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

```c
DRM_IOCTL_PANTHOR(__access, __id, __type)
```

Build a Panthor IOCTL number

**Parameters**

- `__access`: Access type. Must be R, W or RW.
- `__id`: One of the DRM_PANTHOR_xxx id.
- `__type`: Suffix of the type being passed to the IOCTL.

**Description**

Don't use this macro directly, use the DRM_IOCTL_PANTHOR_xxx
values instead.

**Return**

An IOCTL number to be passed to `ioctl()` from userspace.


<a id="rst-drm-xe-uapi"></a>

## drm/xe uAPI


**Xe Device Block Diagram**

The diagram below represents a high-level simplification of a discrete
GPU supported by the Xe driver. It shows some device components which
are necessary to understand this API, as well as how their relations
to each other. This diagram does not represent real hardware:

```text
┌──────────────────────────────────────────────────────────────────┐
│ ┌──────────────────────────────────────────────────┐ ┌─────────┐ │
│ │        ┌───────────────────────┐   ┌─────┐       │ │ ┌─────┐ │ │
│ │        │         VRAM0         ├───┤ ... │       │ │ │VRAM1│ │ │
│ │        └───────────┬───────────┘   └─GT1─┘       │ │ └──┬──┘ │ │
│ │ ┌──────────────────┴───────────────────────────┐ │ │ ┌──┴──┐ │ │
│ │ │ ┌─────────────────────┐  ┌─────────────────┐ │ │ │ │     │ │ │
│ │ │ │ ┌──┐ ┌──┐ ┌──┐ ┌──┐ │  │ ┌─────┐ ┌─────┐ │ │ │ │ │     │ │ │
│ │ │ │ │EU│ │EU│ │EU│ │EU│ │  │ │RCS0 │ │BCS0 │ │ │ │ │ │     │ │ │
│ │ │ │ └──┘ └──┘ └──┘ └──┘ │  │ └─────┘ └─────┘ │ │ │ │ │     │ │ │
│ │ │ │ ┌──┐ ┌──┐ ┌──┐ ┌──┐ │  │ ┌─────┐ ┌─────┐ │ │ │ │ │     │ │ │
│ │ │ │ │EU│ │EU│ │EU│ │EU│ │  │ │VCS0 │ │VCS1 │ │ │ │ │ │     │ │ │
│ │ │ │ └──┘ └──┘ └──┘ └──┘ │  │ └─────┘ └─────┘ │ │ │ │ │     │ │ │
│ │ │ │ ┌──┐ ┌──┐ ┌──┐ ┌──┐ │  │ ┌─────┐ ┌─────┐ │ │ │ │ │     │ │ │
│ │ │ │ │EU│ │EU│ │EU│ │EU│ │  │ │VECS0│ │VECS1│ │ │ │ │ │ ... │ │ │
│ │ │ │ └──┘ └──┘ └──┘ └──┘ │  │ └─────┘ └─────┘ │ │ │ │ │     │ │ │
│ │ │ │ ┌──┐ ┌──┐ ┌──┐ ┌──┐ │  │ ┌─────┐ ┌─────┐ │ │ │ │ │     │ │ │
│ │ │ │ │EU│ │EU│ │EU│ │EU│ │  │ │CCS0 │ │CCS1 │ │ │ │ │ │     │ │ │
│ │ │ │ └──┘ └──┘ └──┘ └──┘ │  │ └─────┘ └─────┘ │ │ │ │ │     │ │ │
│ │ │ └─────────DSS─────────┘  │ ┌─────┐ ┌─────┐ │ │ │ │ │     │ │ │
│ │ │                          │ │CCS2 │ │CCS3 │ │ │ │ │ │     │ │ │
│ │ │ ┌─────┐ ┌─────┐ ┌─────┐  │ └─────┘ └─────┘ │ │ │ │ │     │ │ │
│ │ │ │ ... │ │ ... │ │ ... │  │                 │ │ │ │ │     │ │ │
│ │ │ └─DSS─┘ └─DSS─┘ └─DSS─┘  └─────Engines─────┘ │ │ │ │     │ │ │
│ │ └───────────────────────────GT0────────────────┘ │ │ └─GT2─┘ │ │
│ └────────────────────────────Tile0─────────────────┘ └─ Tile1──┘ │
└─────────────────────────────Device0───────┬──────────────────────┘
                                            │
                     ───────────────────────┴────────── PCI bus
```

**Xe uAPI Overview**

This section aims to describe the Xe's IOCTL entries, its structs, and other
Xe related uAPI such as uevents and PMU (Platform Monitoring Unit) related
entries and usage.

- List of supported IOCTLs:
  - `DRM_IOCTL_XE_DEVICE_QUERY`
  - `DRM_IOCTL_XE_GEM_CREATE`
  - `DRM_IOCTL_XE_GEM_MMAP_OFFSET`
  - `DRM_IOCTL_XE_VM_CREATE`
  - `DRM_IOCTL_XE_VM_DESTROY`
  - `DRM_IOCTL_XE_VM_BIND`
  - `DRM_IOCTL_XE_EXEC_QUEUE_CREATE`
  - `DRM_IOCTL_XE_EXEC_QUEUE_DESTROY`
  - `DRM_IOCTL_XE_EXEC_QUEUE_GET_PROPERTY`
  - `DRM_IOCTL_XE_EXEC`
  - `DRM_IOCTL_XE_WAIT_USER_FENCE`
  - `DRM_IOCTL_XE_OBSERVATION`
  - `DRM_IOCTL_XE_MADVISE`
  - `DRM_IOCTL_XE_VM_QUERY_MEM_RANGE_ATTRS`

**Xe IOCTL Extensions**

Before detailing the IOCTLs and its structs, it is important to highlight
that every IOCTL in Xe is extensible.

Many interfaces need to grow over time. In most cases we can simply
extend the struct and have userspace pass in more data. Another option,
as demonstrated by Vulkan's approach to providing extensions for forward
and backward compatibility, is to use a list of optional structs to
provide those extra details.

The key advantage to using an extension chain is that it allows us to
redefine the interface more easily than an ever growing struct of
increasing complexity, and for large parts of that interface to be
entirely optional. The downside is more pointer chasing; chasing across
the __user boundary with pointers encapsulated inside u64.

Example chaining:

```C
struct drm_xe_user_extension ext3 {
        .next_extension = 0, // end
        .name = ...,
};
struct drm_xe_user_extension ext2 {
        .next_extension = (uintptr_t)&ext3,
        .name = ...,
};
struct drm_xe_user_extension ext1 {
        .next_extension = (uintptr_t)&ext2,
        .name = ...,
};
```

Typically the struct drm_xe_user_extension would be embedded in some uAPI
struct, and in this case we would feed it the head of the chain(i.e ext1),
which would then apply all of the above extensions.

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

Base class for defining a chain of extensions

**Definition**

```c
struct drm_xe_user_extension {
    __u64 next_extension;
    __u32 name;
    __u32 pad;
};
```

**Members**

- `next_extension`: Pointer to the next struct drm_xe_user_extension, or zero if the end.
- `name`: Name of the extension.

  Note that the name here is just some integer.

  Also note that the name space for this is not global for the whole
  driver, but rather its scope/meaning is limited to the specific piece
  of uAPI which has embedded the struct drm_xe_user_extension.
- `pad`: MBZ

  All undefined bits must be zero.

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

Generic set property extension

**Definition**

```c
struct drm_xe_ext_set_property {
    struct drm_xe_user_extension base;
    __u32 property;
    __u32 pad;
    union {
        __u64 value;
        __u64 ptr;
    };
    __u64 reserved[2];
};
```

**Members**

- `base`: base user extension
- `property`: property to set
- `pad`: MBZ
- `{unnamed_union}`: anonymous
- `value`: property value
- `ptr`: pointer to user value
- `reserved`: Reserved

**Description**

A generic struct that allows any of the Xe's IOCTL to be extended
with a set_property operation.

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

instance of an engine class

**Definition**

```c
struct drm_xe_engine_class_instance {
    #define DRM_XE_ENGINE_CLASS_RENDER              0;
    #define DRM_XE_ENGINE_CLASS_COPY                1;
    #define DRM_XE_ENGINE_CLASS_VIDEO_DECODE        2;
    #define DRM_XE_ENGINE_CLASS_VIDEO_ENHANCE       3;
    #define DRM_XE_ENGINE_CLASS_COMPUTE             4;
    #define DRM_XE_ENGINE_CLASS_VM_BIND             5;
        __u16 engine_class;
        __u16 engine_instance;
        __u16 gt_id;
        __u16 pad;
};
```

**Members**

- `engine_class`: engine class id
- `engine_instance`: engine instance id
- `gt_id`: Unique ID of this GT within the PCI Device
- `pad`: MBZ

**Description**

It is returned as part of the **drm_xe_engine**, but it also is used as
the input of engine selection for both **drm_xe_exec_queue_create** and
**drm_xe_query_engine_cycles**

- The **engine_class** can be:
  - `DRM_XE_ENGINE_CLASS_RENDER`
  - `DRM_XE_ENGINE_CLASS_COPY`
  - `DRM_XE_ENGINE_CLASS_VIDEO_DECODE`
  - `DRM_XE_ENGINE_CLASS_VIDEO_ENHANCE`
  - `DRM_XE_ENGINE_CLASS_COMPUTE`
  - `DRM_XE_ENGINE_CLASS_VM_BIND` - Kernel only classes (not actual
    hardware engine class). Used for creating ordered queues of VM
    bind operations.

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

describe hardware engine

**Definition**

```c
struct drm_xe_engine {
    struct drm_xe_engine_class_instance instance;
    __u64 reserved[3];
};
```

**Members**

- `instance`: The **drm_xe_engine_class_instance**
- `reserved`: Reserved

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

describe engines

**Definition**

```c
struct drm_xe_query_engines {
    __u32 num_engines;
    __u32 pad;
    struct drm_xe_engine engines[];
};
```

**Members**

- `num_engines`: number of engines returned in **engines**
- `pad`: MBZ
- `engines`: The returned engines for this device

**Description**

If a query is made with a struct **drm_xe_device_query** where .query
is equal to `DRM_XE_DEVICE_QUERY_ENGINES`, then the reply uses an array of
struct **drm_xe_query_engines** in .data.

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

Supported memory classes.

**Constants**

- `DRM_XE_MEM_REGION_CLASS_SYSMEM`: Represents system memory.
- `DRM_XE_MEM_REGION_CLASS_VRAM`: On discrete platforms, this
  represents the memory that is local to the device, which we
  call VRAM. Not valid on integrated platforms.

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

Describes some region as known to the driver.

**Definition**

```c
struct drm_xe_mem_region {
    __u16 mem_class;
    __u16 instance;
    __u32 min_page_size;
    __u64 total_size;
    __u64 used;
    __u64 cpu_visible_size;
    __u64 cpu_visible_used;
    __u64 reserved[6];
};
```

**Members**

- `mem_class`: The memory class describing this region.

  See enum drm_xe_memory_class for supported values.
- `instance`: The unique ID for this region, which serves as the
  index in the placement bitmask used as argument for
  `DRM_IOCTL_XE_GEM_CREATE`
- `min_page_size`: Min page-size in bytes for this region.

  When the kernel allocates memory for this region, the
  underlying pages will be at least **min_page_size** in size.
  Buffer objects with an allowable placement in this region must be
  created with a size aligned to this value.
  GPU virtual address mappings of (parts of) buffer objects that
  may be placed in this region must also have their GPU virtual
  address and range aligned to this value.
  Affected IOCTLS will return `-EINVAL` if alignment restrictions are
  not met.
- `total_size`: The usable size in bytes for this region.
- `used`: Estimate of the memory used in bytes for this region.

  Requires CAP_PERFMON or CAP_SYS_ADMIN to get reliable
  accounting.  Without this the value here will always equal
  zero.
- `cpu_visible_size`: How much of this region can be CPU
  accessed, in bytes.

  This will always be \<= **total_size**, and the remainder (if
  any) will not be CPU accessible. If the CPU accessible part
  is smaller than **total_size** then this is referred to as a
  small BAR system.

  On systems without small BAR (full BAR), the probed_size will
  always equal the **total_size**, since all of it will be CPU
  accessible.

  Note this is only tracked for DRM_XE_MEM_REGION_CLASS_VRAM
  regions (for other types the value here will always equal
  zero).
- `cpu_visible_used`: Estimate of CPU visible memory used, in
  bytes.

  Requires CAP_PERFMON or CAP_SYS_ADMIN to get reliable
  accounting. Without this the value here will always equal
  zero.  Note this is only currently tracked for
  DRM_XE_MEM_REGION_CLASS_VRAM regions (for other types the value
  here will always be zero).
- `reserved`: Reserved

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

describe memory regions

**Definition**

```c
struct drm_xe_query_mem_regions {
    __u32 num_mem_regions;
    __u32 pad;
    struct drm_xe_mem_region mem_regions[];
};
```

**Members**

- `num_mem_regions`: number of memory regions returned in **mem_regions**
- `pad`: MBZ
- `mem_regions`: The returned memory regions for this device

**Description**

If a query is made with a struct drm_xe_device_query where .query
is equal to DRM_XE_DEVICE_QUERY_MEM_REGIONS, then the reply uses
struct drm_xe_query_mem_regions in .data.

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

describe the device configuration

**Definition**

```c
struct drm_xe_query_config {
        __u32 num_params;
        __u32 pad;
    #define DRM_XE_QUERY_CONFIG_REV_AND_DEVICE_ID   0;
    #define DRM_XE_QUERY_CONFIG_FLAGS                       1;
    #define DRM_XE_QUERY_CONFIG_FLAG_HAS_VRAM       (1 << 0);
    #define DRM_XE_QUERY_CONFIG_FLAG_HAS_LOW_LATENCY        (1 << 1);
    #define DRM_XE_QUERY_CONFIG_FLAG_HAS_CPU_ADDR_MIRROR    (1 << 2);
    #define DRM_XE_QUERY_CONFIG_FLAG_HAS_NO_COMPRESSION_HINT (1 << 3);
    #define DRM_XE_QUERY_CONFIG_MIN_ALIGNMENT               2;
    #define DRM_XE_QUERY_CONFIG_VA_BITS                     3;
    #define DRM_XE_QUERY_CONFIG_MAX_EXEC_QUEUE_PRIORITY     4;
        __u64 info[];
};
```

**Members**

- `num_params`: number of parameters returned in info
- `pad`: MBZ
- `info`: array of elements containing the config info

**Description**

If a query is made with a struct drm_xe_device_query where .query
is equal to DRM_XE_DEVICE_QUERY_CONFIG, then the reply uses
struct drm_xe_query_config in .data.

- The index in **info** can be:
  - `DRM_XE_QUERY_CONFIG_REV_AND_DEVICE_ID` - Device ID (lower 16 bits)
    and the device revision (next 8 bits)
  - `DRM_XE_QUERY_CONFIG_FLAGS` - Flags describing the device
    configuration, see list below

    - `DRM_XE_QUERY_CONFIG_FLAG_HAS_VRAM` - Flag is set if the device
      has usable VRAM
    - `DRM_XE_QUERY_CONFIG_FLAG_HAS_LOW_LATENCY` - Flag is set if the device
      has low latency hint support
    - `DRM_XE_QUERY_CONFIG_FLAG_HAS_CPU_ADDR_MIRROR` - Flag is set if the
      device has CPU address mirroring support
    - `DRM_XE_QUERY_CONFIG_FLAG_HAS_NO_COMPRESSION_HINT` - Flag is set if the
      device supports the userspace hint `DRM_XE_GEM_CREATE_FLAG_NO_COMPRESSION`.
      This is exposed only on Xe2+.
  - `DRM_XE_QUERY_CONFIG_MIN_ALIGNMENT` - Minimal memory alignment
    required by this device, typically SZ_4K or SZ_64K
  - `DRM_XE_QUERY_CONFIG_VA_BITS` - Maximum bits of a virtual address
  - `DRM_XE_QUERY_CONFIG_MAX_EXEC_QUEUE_PRIORITY` - Value of the highest
    available exec queue priority

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

describe an individual GT.

**Definition**

```c
struct drm_xe_gt {
    #define DRM_XE_QUERY_GT_TYPE_MAIN               0;
    #define DRM_XE_QUERY_GT_TYPE_MEDIA              1;
        __u16 type;
        __u16 tile_id;
        __u16 gt_id;
        __u16 pad[3];
        __u32 reference_clock;
        __u64 near_mem_regions;
        __u64 far_mem_regions;
        __u16 ip_ver_major;
        __u16 ip_ver_minor;
        __u16 ip_ver_rev;
        __u16 pad2;
        __u64 reserved[7];
};
```

**Members**

- `type`: GT type: Main or Media
- `tile_id`: Tile ID where this GT lives (Information only)
- `gt_id`: Unique ID of this GT within the PCI Device
- `pad`: MBZ
- `reference_clock`: A clock frequency for timestamp
- `near_mem_regions`: Bit mask of instances from
  drm_xe_query_mem_regions that are nearest to the current engines
  of this GT.
  Each index in this mask refers directly to the struct
  drm_xe_query_mem_regions' instance, no assumptions should
  be made about order. The type of each region is described
  by struct drm_xe_query_mem_regions' mem_class.
- `far_mem_regions`: Bit mask of instances from
  drm_xe_query_mem_regions that are far from the engines of this GT.
  In general, they have extra indirections when compared to the
  **near_mem_regions**. For a discrete device this could mean system
  memory and memory living in a different tile.
  Each index in this mask refers directly to the struct
  drm_xe_query_mem_regions' instance, no assumptions should
  be made about order. The type of each region is described
  by struct drm_xe_query_mem_regions' mem_class.
- `ip_ver_major`: Graphics/media IP major version on GMD_ID platforms
- `ip_ver_minor`: Graphics/media IP minor version on GMD_ID platforms
- `ip_ver_rev`: Graphics/media IP revision version on GMD_ID platforms
- `pad2`: MBZ
- `reserved`: Reserved

**Description**

To be used with drm_xe_query_gt_list, which will return a list with all the
existing GT individual descriptions.
Graphics Technology (GT) is a subset of a GPU/tile that is responsible for
implementing graphics and/or media operations.

- The index in **type** can be:
  - `DRM_XE_QUERY_GT_TYPE_MAIN`
  - `DRM_XE_QUERY_GT_TYPE_MEDIA`

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

A list with GT description items.

**Definition**

```c
struct drm_xe_query_gt_list {
    __u32 num_gt;
    __u32 pad;
    struct drm_xe_gt gt_list[];
};
```

**Members**

- `num_gt`: number of GT items returned in gt_list
- `pad`: MBZ
- `gt_list`: The GT list returned for this device

**Description**

If a query is made with a struct drm_xe_device_query where .query
is equal to DRM_XE_DEVICE_QUERY_GT_LIST, then the reply uses struct
drm_xe_query_gt_list in .data.

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

describe the topology mask of a GT

**Definition**

```c
struct drm_xe_query_topology_mask {
        __u16 gt_id;
    #define DRM_XE_TOPO_DSS_GEOMETRY        1;
    #define DRM_XE_TOPO_DSS_COMPUTE         2;
    #define DRM_XE_TOPO_L3_BANK             3;
    #define DRM_XE_TOPO_EU_PER_DSS          4;
    #define DRM_XE_TOPO_SIMD16_EU_PER_DSS   5;
        __u16 type;
        __u32 num_bytes;
        __u8 mask[];
};
```

**Members**

- `gt_id`: GT ID the mask is associated with
- `type`: type of mask
- `num_bytes`: number of bytes in requested mask
- `mask`: little-endian mask of **num_bytes**

**Description**

This is the hardware topology which reflects the internal physical
structure of the GPU.

If a query is made with a struct drm_xe_device_query where .query
is equal to DRM_XE_DEVICE_QUERY_GT_TOPOLOGY, then the reply uses
struct drm_xe_query_topology_mask in .data.

- The **type** can be:
  - `DRM_XE_TOPO_DSS_GEOMETRY` - To query the mask of Dual Sub Slices
    (DSS) available for geometry operations. For example a query response
    containing the following in mask:
    `DSS_GEOMETRY    ff ff ff ff 00 00 00 00`
    means 32 DSS are available for geometry.
  - `DRM_XE_TOPO_DSS_COMPUTE` - To query the mask of Dual Sub Slices
    (DSS) available for compute operations. For example a query response
    containing the following in mask:
    `DSS_COMPUTE    ff ff ff ff 00 00 00 00`
    means 32 DSS are available for compute.
  - `DRM_XE_TOPO_L3_BANK` - To query the mask of enabled L3 banks.  This type
    may be omitted if the driver is unable to query the mask from the
    hardware.
  - `DRM_XE_TOPO_EU_PER_DSS` - To query the mask of Execution Units (EU)
    available per Dual Sub Slices (DSS). For example a query response
    containing the following in mask:
    `EU_PER_DSS    ff ff 00 00 00 00 00 00`
    means each DSS has 16 SIMD8 EUs. This type may be omitted if device
    doesn't have SIMD8 EUs.
  - `DRM_XE_TOPO_SIMD16_EU_PER_DSS` - To query the mask of SIMD16 Execution
    Units (EU) available per Dual Sub Slices (DSS). For example a query
    response containing the following in mask:
    `SIMD16_EU_PER_DSS    ff ff 00 00 00 00 00 00`
    means each DSS has 16 SIMD16 EUs. This type may be omitted if device
    doesn't have SIMD16 EUs.

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

correlate CPU and GPU timestamps

**Definition**

```c
struct drm_xe_query_engine_cycles {
    struct drm_xe_engine_class_instance eci;
    __s32 clockid;
    __u32 width;
    __u64 engine_cycles;
    __u64 cpu_timestamp;
    __u64 cpu_delta;
};
```

**Members**

- `eci`: This is input by the user and is the engine for which command
  streamer cycles is queried.
- `clockid`: This is input by the user and is the reference clock id for
  CPU timestamp. For definition, see clock_gettime(2) and
  perf_event_open(2). Supported clock ids are CLOCK_MONOTONIC,
  CLOCK_MONOTONIC_RAW, CLOCK_REALTIME, CLOCK_BOOTTIME, CLOCK_TAI.
- `width`: Width of the engine cycle counter in bits.
- `engine_cycles`: Engine cycles as read from its register
  at 0x358 offset.
- `cpu_timestamp`: CPU timestamp in ns. The timestamp is captured before
  reading the engine_cycles register using the reference clockid set by the
  user.
- `cpu_delta`: Time delta in ns captured around reading the lower dword
  of the engine_cycles register.

**Description**

If a query is made with a struct drm_xe_device_query where .query is equal to
DRM_XE_DEVICE_QUERY_ENGINE_CYCLES, then the reply uses struct drm_xe_query_engine_cycles
in .data. struct drm_xe_query_engine_cycles is allocated by the user and
.data points to this allocated structure.

The query returns the engine cycles, which along with GT's **reference_clock**,
can be used to calculate the engine timestamp. In addition the
query returns a set of cpu timestamps that indicate when the command
streamer cycle count was captured.

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

query a micro-controller firmware version

**Definition**

```c
struct drm_xe_query_uc_fw_version {
    #define XE_QUERY_UC_TYPE_GUC_SUBMISSION 0;
    #define XE_QUERY_UC_TYPE_HUC 1;
        __u16 uc_type;
        __u16 pad;
        __u32 branch_ver;
        __u32 major_ver;
        __u32 minor_ver;
        __u32 patch_ver;
        __u32 pad2;
        __u64 reserved;
};
```

**Members**

- `uc_type`: The micro-controller type to query firmware version
- `pad`: MBZ
- `branch_ver`: branch uc fw version
- `major_ver`: major uc fw version
- `minor_ver`: minor uc fw version
- `patch_ver`: patch uc fw version
- `pad2`: MBZ
- `reserved`: Reserved

**Description**

Given a uc_type this will return the branch, major, minor and patch version
of the micro-controller firmware.

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

query if PXP is ready

**Definition**

```c
struct drm_xe_query_pxp_status {
    __u32 status;
    __u32 supported_session_types;
};
```

**Members**

- `status`: current PXP status
- `supported_session_types`: bitmask of supported PXP session types

**Description**

If PXP is enabled and no fatal error has occurred, the status will be set to
one of the following values:
0: PXP init still in progress
1: PXP init complete

If PXP is not enabled or something has gone wrong, the query will be failed
with one of the following error codes:
-ENODEV: PXP not supported or disabled;
-EIO: fatal error occurred during init, so PXP will never be enabled;
-EINVAL: incorrect value provided as part of the query;
-EFAULT: error copying the memory between kernel and userspace.

The status can only be 0 in the first few seconds after driver load. If
everything works as expected, the status will transition to init complete in
less than 1 second, while in case of errors the driver might take longer to
start returning an error code, but it should still take less than 10 seconds.

The supported session type bitmask is based on the values in
enum drm_xe_pxp_session_type. TYPE_NONE is always supported and therefore
is not reported in the bitmask.

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

Input of `DRM_IOCTL_XE_DEVICE_QUERY` - main structure to query device information

**Definition**

```c
struct drm_xe_device_query {
        __u64 extensions;
    #define DRM_XE_DEVICE_QUERY_ENGINES             0;
    #define DRM_XE_DEVICE_QUERY_MEM_REGIONS         1;
    #define DRM_XE_DEVICE_QUERY_CONFIG              2;
    #define DRM_XE_DEVICE_QUERY_GT_LIST             3;
    #define DRM_XE_DEVICE_QUERY_HWCONFIG            4;
    #define DRM_XE_DEVICE_QUERY_GT_TOPOLOGY         5;
    #define DRM_XE_DEVICE_QUERY_ENGINE_CYCLES       6;
    #define DRM_XE_DEVICE_QUERY_UC_FW_VERSION       7;
    #define DRM_XE_DEVICE_QUERY_OA_UNITS            8;
    #define DRM_XE_DEVICE_QUERY_PXP_STATUS          9;
    #define DRM_XE_DEVICE_QUERY_EU_STALL            10;
        __u32 query;
        __u32 size;
        __u64 data;
        __u64 reserved[2];
};
```

**Members**

- `extensions`: Pointer to the first extension struct, if any
- `query`: The type of data to query
- `size`: Size of the queried data
- `data`: Queried data is placed here
- `reserved`: Reserved

**Description**

The user selects the type of data to query among DRM_XE_DEVICE_QUERY_*
and sets the value in the query member. This determines the type of
the structure provided by the driver in data, among struct drm_xe_query_*.

- The **query** can be:
  - `DRM_XE_DEVICE_QUERY_ENGINES`
  - `DRM_XE_DEVICE_QUERY_MEM_REGIONS`
  - `DRM_XE_DEVICE_QUERY_CONFIG`
  - `DRM_XE_DEVICE_QUERY_GT_LIST`
  - `DRM_XE_DEVICE_QUERY_HWCONFIG` - Query type to retrieve the hardware
    configuration of the device such as information on slices, memory,
    caches, and so on. It is provided as a table of key / value
    attributes.
  - `DRM_XE_DEVICE_QUERY_GT_TOPOLOGY`
  - `DRM_XE_DEVICE_QUERY_ENGINE_CYCLES`
  - `DRM_XE_DEVICE_QUERY_PXP_STATUS`

If size is set to 0, the driver fills it with the required size for
the requested type of data to query. If size is equal to the required
size, the queried information is copied into data. If size is set to
a value different from 0 and different from the required size, the
IOCTL call returns -EINVAL.

For example the following code snippet allows retrieving and printing
information about the device engines with DRM_XE_DEVICE_QUERY_ENGINES:

```C
struct drm_xe_query_engines *engines;
struct drm_xe_device_query query = {
    .extensions = 0,
    .query = DRM_XE_DEVICE_QUERY_ENGINES,
    .size = 0,
    .data = 0,
};
ioctl(fd, DRM_IOCTL_XE_DEVICE_QUERY, &query);
engines = malloc(query.size);
query.data = (uintptr_t)engines;
ioctl(fd, DRM_IOCTL_XE_DEVICE_QUERY, &query);
for (int i = 0; i < engines->num_engines; i++) {
    printf("Engine %d: %s\n", i,
        engines->engines[i].instance.engine_class ==
            DRM_XE_ENGINE_CLASS_RENDER ? "RENDER":
        engines->engines[i].instance.engine_class ==
            DRM_XE_ENGINE_CLASS_COPY ? "COPY":
        engines->engines[i].instance.engine_class ==
            DRM_XE_ENGINE_CLASS_VIDEO_DECODE ? "VIDEO_DECODE":
        engines->engines[i].instance.engine_class ==
            DRM_XE_ENGINE_CLASS_VIDEO_ENHANCE ? "VIDEO_ENHANCE":
        engines->engines[i].instance.engine_class ==
            DRM_XE_ENGINE_CLASS_COMPUTE ? "COMPUTE":
        "UNKNOWN");
}
free(engines);
```

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

Input of `DRM_IOCTL_XE_GEM_CREATE` - A structure for gem creation

**Definition**

```c
struct drm_xe_gem_create {
    #define DRM_XE_GEM_CREATE_EXTENSION_SET_PROPERTY        0;
    #define DRM_XE_GEM_CREATE_SET_PROPERTY_PXP_TYPE       0;
        __u64 extensions;
        __u64 size;
        __u32 placement;
    #define DRM_XE_GEM_CREATE_FLAG_DEFER_BACKING            (1 << 0);
    #define DRM_XE_GEM_CREATE_FLAG_SCANOUT                  (1 << 1);
    #define DRM_XE_GEM_CREATE_FLAG_NEEDS_VISIBLE_VRAM       (1 << 2);
    #define DRM_XE_GEM_CREATE_FLAG_NO_COMPRESSION           (1 << 3);
        __u32 flags;
        __u32 vm_id;
        __u32 handle;
    #define DRM_XE_GEM_CPU_CACHING_WB                      1;
    #define DRM_XE_GEM_CPU_CACHING_WC                      2;
        __u16 cpu_caching;
        __u16 pad[3];
        __u64 reserved[2];
};
```

**Members**

- `extensions`: Pointer to the first extension struct, if any
- `size`: Size of the object to be created, must match region
  (system or vram) minimum alignment (`min_page_size`).
- `placement`: A mask of memory instances of where BO can be placed.
  Each index in this mask refers directly to the struct
  drm_xe_query_mem_regions' instance, no assumptions should
  be made about order. The type of each region is described
  by struct drm_xe_query_mem_regions' mem_class.
- `flags`: Flags, currently a mask of memory instances of where BO can
  be placed
- `vm_id`: Attached VM, if any

  If a VM is specified, this BO must:

  1. Only ever be bound to that VM.
  2. Cannot be exported as a PRIME fd.
- `handle`: Returned handle for the object.

  Object handles are nonzero.
- `cpu_caching`: The CPU caching mode to select for this object. If
  mmaping the object the mode selected here will also be used. The
  exception is when mapping system memory (including data evicted
  to system) on discrete GPUs. The caching mode selected will
  then be overridden to DRM_XE_GEM_CPU_CACHING_WB, and coherency
  between GPU- and CPU is guaranteed. The caching mode of
  existing CPU-mappings will be updated transparently to
  user-space clients.
- `pad`: MBZ
- `reserved`: Reserved

**Description**

- The **flags** can be:
  - `DRM_XE_GEM_CREATE_FLAG_DEFER_BACKING` - Modify the GEM object
    allocation strategy by deferring physical memory allocation
    until the object is either bound to a virtual memory region via
    VM_BIND or accessed by the CPU. As a result, no backing memory is
    reserved at the time of GEM object creation.
  - `DRM_XE_GEM_CREATE_FLAG_SCANOUT` - Indicates that the GEM object is
    intended for scanout via the display engine. When set, kernel ensures
    that the allocation is placed in a memory region compatible with the
    display engine requirements. This may impose restrictions on tiling,
    alignment, and memory placement to guarantee proper display functionality.
  - `DRM_XE_GEM_CREATE_FLAG_NEEDS_VISIBLE_VRAM` - When using VRAM as a
    possible placement, ensure that the corresponding VRAM allocation
    will always use the CPU accessible part of VRAM. This is important
    for small-bar systems (on full-bar systems this gets turned into a
    noop).
    Note1: System memory can be used as an extra placement if the kernel
    should spill the allocation to system memory, if space can't be made
    available in the CPU accessible part of VRAM (giving the same
    behaviour as the i915 interface, see
    I915_GEM_CREATE_EXT_FLAG_NEEDS_CPU_ACCESS).
    Note2: For clear-color CCS surfaces the kernel needs to read the
    clear-color value stored in the buffer, and on discrete platforms we
    need to use VRAM for display surfaces, therefore the kernel requires
    setting this flag for such objects, otherwise an error is thrown on
    small-bar systems.
  - `DRM_XE_GEM_CREATE_FLAG_NO_COMPRESSION` - Allows userspace to
    hint that compression (CCS) should be disabled for the buffer being
    created. This can avoid unnecessary memory operations and CCS state
    management.
    On pre-Xe2 platforms, this flag is currently rejected as compression
    control is not supported via PAT index. On Xe2+ platforms, compression
    is controlled via PAT entries. If this flag is set, the driver will reject
    any VM bind that requests a PAT index enabling compression for this BO.

**Note**

- On dGPU platforms, there is currently no change in behavior with

  this flag, but future improvements may leverage it. The current benefit is
  primarily applicable to iGPU platforms.

- **cpu_caching** supports the following values:
  - `DRM_XE_GEM_CPU_CACHING_WB` - Allocate the pages with write-back
    caching. On iGPU this can't be used for scanout surfaces. Currently
    not allowed for objects placed in VRAM.
  - `DRM_XE_GEM_CPU_CACHING_WC` - Allocate the pages as write-combined. This
    is uncached. Scanout surfaces should likely use this. All objects
    that can be placed in VRAM must use this.

This ioctl supports setting the following properties via the
`DRM_XE_GEM_CREATE_EXTENSION_SET_PROPERTY` extension, which uses the
generic **drm_xe_ext_set_property** struct:

- `DRM_XE_GEM_CREATE_SET_PROPERTY_PXP_TYPE` - set the type of PXP session
  this object will be used with. Valid values are listed in enum
  drm_xe_pxp_session_type. `DRM_XE_PXP_TYPE_NONE` is the default behavior, so
  there is no need to explicitly set that. Objects used with session of type
  `DRM_XE_PXP_TYPE_HWDRM` will be marked as invalid if a PXP invalidation
  event occurs after their creation. Attempting to flip an invalid object
  will cause a black frame to be displayed instead. Submissions with invalid
  objects mapped in the VM will be rejected.

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

Input of `DRM_IOCTL_XE_GEM_MMAP_OFFSET`

**Definition**

```c
struct drm_xe_gem_mmap_offset {
        __u64 extensions;
        __u32 handle;
    #define DRM_XE_MMAP_OFFSET_FLAG_PCI_BARRIER     (1 << 0);
        __u32 flags;
        __u64 offset;
        __u64 reserved[2];
};
```

**Members**

- `extensions`: Pointer to the first extension struct, if any
- `handle`: Handle for the object being mapped.
- `flags`: Flags
- `offset`: The fake offset to use for subsequent mmap call
- `reserved`: Reserved

**Description**

- The **flags** can be:
  - `DRM_XE_MMAP_OFFSET_FLAG_PCI_BARRIER` - For user to query special offset
    for use in mmap ioctl. Writing to the returned mmap address will generate a
    PCI memory barrier with low overhead (avoiding IOCTL call as well as writing
    to VRAM which would also add overhead), acting like an MI_MEM_FENCE
    instruction.

**Note**

The mmap size can be at most 4K, due to HW limitations. As a result
this interface is only supported on CPU architectures that support 4K page
size. The mmap_offset ioctl will detect this and gracefully return an
error, where userspace is expected to have a different fallback method for
triggering a barrier.

Roughly the usage would be as follows:

```C
struct drm_xe_gem_mmap_offset mmo = {
    .handle = 0, // must be set to 0
    .flags = DRM_XE_MMAP_OFFSET_FLAG_PCI_BARRIER,
};

err = ioctl(fd, DRM_IOCTL_XE_GEM_MMAP_OFFSET, &mmo);
map = mmap(NULL, size, PROT_WRITE, MAP_SHARED, fd, mmo.offset);
map[i] = 0xdeadbeaf; // issue barrier
```

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

Input of `DRM_IOCTL_XE_VM_CREATE`

**Definition**

```c
struct drm_xe_vm_create {
        __u64 extensions;
    #define DRM_XE_VM_CREATE_FLAG_SCRATCH_PAGE      (1 << 0);
    #define DRM_XE_VM_CREATE_FLAG_LR_MODE           (1 << 1);
    #define DRM_XE_VM_CREATE_FLAG_FAULT_MODE        (1 << 2);
        __u32 flags;
        __u32 vm_id;
        __u64 reserved[2];
};
```

**Members**

- `extensions`: Pointer to the first extension struct, if any
- `flags`: Flags
- `vm_id`: Returned VM ID
- `reserved`: Reserved

**Description**

- The **flags** can be:
  - `DRM_XE_VM_CREATE_FLAG_SCRATCH_PAGE` - Map the whole virtual address
    space of the VM to scratch page. A vm_bind would overwrite the scratch
    page mapping. This flag is mutually exclusive with the
    `DRM_XE_VM_CREATE_FLAG_FAULT_MODE` flag, with an exception of on x2 and
    xe3 platform.
  - `DRM_XE_VM_CREATE_FLAG_LR_MODE` - An LR, or Long Running VM accepts
    exec submissions to its exec_queues that don't have an upper time
    limit on the job execution time. But exec submissions to these
    don't allow any of the sync types DRM_XE_SYNC_TYPE_SYNCOBJ,
    DRM_XE_SYNC_TYPE_TIMELINE_SYNCOBJ, used as out-syncobjs, that is,
    together with sync flag DRM_XE_SYNC_FLAG_SIGNAL.
    LR VMs can be created in recoverable page-fault mode using
    DRM_XE_VM_CREATE_FLAG_FAULT_MODE, if the device supports it.
    If that flag is omitted, the UMD can not rely on the slightly
    different per-VM overcommit semantics that are enabled by
    DRM_XE_VM_CREATE_FLAG_FAULT_MODE (see below), but KMD may
    still enable recoverable pagefaults if supported by the device.
  - `DRM_XE_VM_CREATE_FLAG_FAULT_MODE` - Requires also
    DRM_XE_VM_CREATE_FLAG_LR_MODE. It allows memory to be allocated on
    demand when accessed, and also allows per-VM overcommit of memory.
    The xe driver internally uses recoverable pagefaults to implement
    this.

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

Input of `DRM_IOCTL_XE_VM_DESTROY`

**Definition**

```c
struct drm_xe_vm_destroy {
    __u32 vm_id;
    __u32 pad;
    __u64 reserved[2];
};
```

**Members**

- `vm_id`: VM ID
- `pad`: MBZ
- `reserved`: Reserved

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

run bind operations

**Definition**

```c
struct drm_xe_vm_bind_op {
        __u64 extensions;
        __u32 obj;
        __u16 pat_index;
        __u16 pad;
        union {
            __u64 obj_offset;
            __u64 userptr;
            __s64 cpu_addr_mirror_offset;
        };
        __u64 range;
        __u64 addr;
    #define DRM_XE_VM_BIND_OP_MAP           0x0;
    #define DRM_XE_VM_BIND_OP_UNMAP         0x1;
    #define DRM_XE_VM_BIND_OP_MAP_USERPTR   0x2;
    #define DRM_XE_VM_BIND_OP_UNMAP_ALL     0x3;
    #define DRM_XE_VM_BIND_OP_PREFETCH      0x4;
        __u32 op;
    #define DRM_XE_VM_BIND_FLAG_READONLY    (1 << 0);
    #define DRM_XE_VM_BIND_FLAG_IMMEDIATE   (1 << 1);
    #define DRM_XE_VM_BIND_FLAG_NULL        (1 << 2);
    #define DRM_XE_VM_BIND_FLAG_DUMPABLE    (1 << 3);
    #define DRM_XE_VM_BIND_FLAG_CHECK_PXP   (1 << 4);
    #define DRM_XE_VM_BIND_FLAG_CPU_ADDR_MIRROR     (1 << 5);
    #define DRM_XE_VM_BIND_FLAG_MADVISE_AUTORESET   (1 << 6);
        __u32 flags;
    #define DRM_XE_CONSULT_MEM_ADVISE_PREF_LOC      -1;
        __u32 prefetch_mem_region_instance;
        __u32 pad2;
        __u64 reserved[3];
};
```

**Members**

- `extensions`: Pointer to the first extension struct, if any
- `obj`: GEM object to operate on, MBZ for MAP_USERPTR, MBZ for UNMAP
- `pat_index`: The platform defined **pat_index** to use for this mapping.
  The index basically maps to some predefined memory attributes,
  including things like caching, coherency, compression etc.  The exact
  meaning of the pat_index is platform specific and defined in the
  Bspec and PRMs.  When the KMD sets up the binding the index here is
  encoded into the ppGTT PTE.

  For coherency the **pat_index** needs to be at least 1way coherent when
  drm_xe_gem_create.cpu_caching is DRM_XE_GEM_CPU_CACHING_WB. The KMD
  will extract the coherency mode from the **pat_index** and reject if
  there is a mismatch (see note below for pre-MTL platforms).

  Note: On pre-MTL platforms there is only a caching mode and no
  explicit coherency mode, but on such hardware there is always a
  shared-LLC (or is dgpu) so all GT memory accesses are coherent with
  CPU caches even with the caching mode set as uncached.  It's only the
  display engine that is incoherent (on dgpu it must be in VRAM which
  is always mapped as WC on the CPU). However to keep the uapi somewhat
  consistent with newer platforms the KMD groups the different cache
  levels into the following coherency buckets on all pre-MTL platforms:

  ppGTT UC -> COH_NONE
  ppGTT WC -> COH_NONE
  ppGTT WT -> COH_NONE
  ppGTT WB -> COH_AT_LEAST_1WAY

  In practice UC/WC/WT should only ever used for scanout surfaces on
  such platforms (or perhaps in general for dma-buf if shared with
  another device) since it is only the display engine that is actually
  incoherent.  Everything else should typically use WB given that we
  have a shared-LLC.  On MTL+ this completely changes and the HW
  defines the coherency mode as part of the **pat_index**, where
  incoherent GT access is possible.

  Note: For userptr and externally imported dma-buf the kernel expects
  either 1WAY or 2WAY for the **pat_index**.

  For DRM_XE_VM_BIND_FLAG_NULL bindings there are no KMD restrictions
  on the **pat_index**. For such mappings there is no actual memory being
  mapped (the address in the PTE is invalid), so the various PAT memory
  attributes likely do not apply.  Simply leaving as zero is one
  option (still a valid pat_index). Same applies to
  DRM_XE_VM_BIND_FLAG_CPU_ADDR_MIRROR bindings as for such mapping
  there is no actual memory being mapped.
- `pad`: MBZ
- `{unnamed_union}`: anonymous
- `obj_offset`: Offset into the object, MBZ for CLEAR_RANGE,
  ignored for unbind
- `userptr`: user pointer to bind on
- `cpu_addr_mirror_offset`: Offset from GPU **addr** to create
  CPU address mirror mappings. MBZ with current level of
  support (e.g. 1 to 1 mapping between GPU and CPU mappings
  only supported).
- `range`: Number of bytes from the object to bind to addr, MBZ for UNMAP_ALL
- `addr`: Address to operate on, MBZ for UNMAP_ALL
- `op`: Bind operation to perform
- `flags`: Bind flags
- `prefetch_mem_region_instance`: Memory region to prefetch VMA to.
  It is a region instance, not a mask.
  To be used only with `DRM_XE_VM_BIND_OP_PREFETCH` operation.
- `pad2`: MBZ
- `reserved`: Reserved

**Description**

- The **op** can be:
  - `DRM_XE_VM_BIND_OP_MAP`
  - `DRM_XE_VM_BIND_OP_UNMAP`
  - `DRM_XE_VM_BIND_OP_MAP_USERPTR`
  - `DRM_XE_VM_BIND_OP_UNMAP_ALL`
  - `DRM_XE_VM_BIND_OP_PREFETCH`

- and the **flags** can be:
  - `DRM_XE_VM_BIND_FLAG_READONLY` - Setup the page tables as read-only
    to ensure write protection
  - `DRM_XE_VM_BIND_FLAG_IMMEDIATE` - On a faulting VM, do the
    MAP operation immediately rather than deferring the MAP to the page
    fault handler. This is implied on a non-faulting VM as there is no
    fault handler to defer to.
  - `DRM_XE_VM_BIND_FLAG_NULL` - When the NULL flag is set, the page
    tables are setup with a special bit which indicates writes are
    dropped and all reads return zero. In the future, the NULL flags
    will only be valid for DRM_XE_VM_BIND_OP_MAP operations, the BO
    handle MBZ, and the BO offset MBZ. This flag is intended to
    implement VK sparse bindings.
  - `DRM_XE_VM_BIND_FLAG_CHECK_PXP` - If the object is encrypted via PXP,
    reject the binding if the encryption key is no longer valid. This
    flag has no effect on BOs that are not marked as using PXP.
  - `DRM_XE_VM_BIND_FLAG_CPU_ADDR_MIRROR` - When the CPU address mirror flag is
    set, no mappings are created rather the range is reserved for CPU address
    mirroring which will be populated on GPU page faults or prefetches. Only
    valid on VMs with DRM_XE_VM_CREATE_FLAG_FAULT_MODE set. The CPU address
    mirror flag are only valid for DRM_XE_VM_BIND_OP_MAP operations, the BO
    handle MBZ, and the BO offset MBZ.
  - `DRM_XE_VM_BIND_FLAG_MADVISE_AUTORESET` - Can be used in combination with
    `DRM_XE_VM_BIND_FLAG_CPU_ADDR_MIRROR` to reset madvises when the underlying
    CPU address space range is unmapped (typically with munmap(2) or brk(2)).
    The madvise values set with `DRM_IOCTL_XE_MADVISE` are reset to the values
    that were present immediately after the `DRM_IOCTL_XE_VM_BIND`.
    The reset GPU virtual address range is the intersection of the range bound
    using `DRM_IOCTL_XE_VM_BIND` and the virtual CPU address space range
    unmapped.
    This functionality is present to mimic the behaviour of CPU address space
    madvises set using madvise(2), which are typically reset on unmap.

**Note**

- free(3) may or may not call munmap(2) and/or brk(2), and may thus

  not invoke autoreset. Neither will stack variables going out of scope.
  Therefore it's recommended to always explicitly reset the madvises when
  freeing the memory backing a region used in a `DRM_IOCTL_XE_MADVISE` call.

- The **prefetch_mem_region_instance** for `DRM_XE_VM_BIND_OP_PREFETCH` can also be:
  - `DRM_XE_CONSULT_MEM_ADVISE_PREF_LOC`, which ensures prefetching occurs in
    the memory region advised by madvise.

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

Input of `DRM_IOCTL_XE_VM_BIND`

**Definition**

```c
struct drm_xe_vm_bind {
    __u64 extensions;
    __u32 vm_id;
    __u32 exec_queue_id;
    __u32 pad;
    __u32 num_binds;
    union {
        struct drm_xe_vm_bind_op bind;
        __u64 vector_of_binds;
    };
    __u32 pad2;
    __u32 num_syncs;
    __u64 syncs;
    __u64 reserved[2];
};
```

**Members**

- `extensions`: Pointer to the first extension struct, if any
- `vm_id`: The ID of the VM to bind to
- `exec_queue_id`: exec_queue_id, must be of class DRM_XE_ENGINE_CLASS_VM_BIND
  and exec queue must have same vm_id. If zero, the default VM bind engine
  is used.
- `pad`: MBZ
- `num_binds`: number of binds in this IOCTL
- `{unnamed_union}`: anonymous
- `bind`: used if num_binds == 1
- `vector_of_binds`: userptr to array of struct
  drm_xe_vm_bind_op if num_binds > 1
- `pad2`: MBZ
- `num_syncs`: amount of syncs to wait on
- `syncs`: pointer to struct drm_xe_sync array
- `reserved`: Reserved

**Description**

Below is an example of a minimal use of **drm_xe_vm_bind** to
asynchronously bind the buffer `data` at address `BIND_ADDRESS` to
illustrate `userptr`. It can be synchronized by using the example
provided for **drm_xe_sync**.

```C
data = aligned_alloc(ALIGNMENT, BO_SIZE);
struct drm_xe_vm_bind bind = {
    .vm_id = vm,
    .num_binds = 1,
    .bind.obj = 0,
    .bind.obj_offset = to_user_pointer(data),
    .bind.range = BO_SIZE,
    .bind.addr = BIND_ADDRESS,
    .bind.op = DRM_XE_VM_BIND_OP_MAP_USERPTR,
    .bind.flags = 0,
    .num_syncs = 1,
    .syncs = &sync,
    .exec_queue_id = 0,
};
ioctl(fd, DRM_IOCTL_XE_VM_BIND, &bind);
```

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

Input of `DRM_IOCTL_XE_EXEC_QUEUE_CREATE`

**Definition**

```c
struct drm_xe_exec_queue_create {
    #define DRM_XE_EXEC_QUEUE_EXTENSION_SET_PROPERTY                0;
    #define DRM_XE_EXEC_QUEUE_SET_PROPERTY_PRIORITY               0;
    #define DRM_XE_EXEC_QUEUE_SET_PROPERTY_TIMESLICE              1;
    #define DRM_XE_EXEC_QUEUE_SET_PROPERTY_PXP_TYPE               2;
    #define DRM_XE_EXEC_QUEUE_SET_HANG_REPLAY_STATE               3;
    #define DRM_XE_EXEC_QUEUE_SET_PROPERTY_MULTI_GROUP            4;
    #define DRM_XE_MULTI_GROUP_CREATE                           (1ull << 63);
    #define DRM_XE_EXEC_QUEUE_SET_PROPERTY_MULTI_QUEUE_PRIORITY   5;
        __u64 extensions;
        __u16 width;
        __u16 num_placements;
        __u32 vm_id;
    #define DRM_XE_EXEC_QUEUE_LOW_LATENCY_HINT      (1 << 0);
        __u32 flags;
        __u32 exec_queue_id;
        __u64 instances;
        __u64 reserved[2];
};
```

**Members**

- `extensions`: Pointer to the first extension struct, if any
- `width`: submission width (number BB per exec) for this exec queue
- `num_placements`: number of valid placements for this exec queue
- `vm_id`: VM to use for this exec queue
- `flags`: flags to use for this exec queue
- `exec_queue_id`: Returned exec queue ID
- `instances`: user pointer to a 2-d array of struct
  drm_xe_engine_class_instance

  length = width (i) * num_placements (j)
  index = j + i * width
- `reserved`: Reserved

**Description**

This ioctl supports setting the following properties via the
`DRM_XE_EXEC_QUEUE_EXTENSION_SET_PROPERTY` extension, which uses the
generic **drm_xe_ext_set_property** struct:

- `DRM_XE_EXEC_QUEUE_SET_PROPERTY_PRIORITY` - set the queue priority.
  CAP_SYS_NICE is required to set a value above normal.
- `DRM_XE_EXEC_QUEUE_SET_PROPERTY_TIMESLICE` - set the queue timeslice
  duration in microseconds.
- `DRM_XE_EXEC_QUEUE_SET_PROPERTY_PXP_TYPE` - set the type of PXP session
  this queue will be used with. Valid values are listed in enum
  drm_xe_pxp_session_type. `DRM_XE_PXP_TYPE_NONE` is the default behavior, so
  there is no need to explicitly set that. When a queue of type
  `DRM_XE_PXP_TYPE_HWDRM` is created, the PXP default HWDRM session
  (`XE_PXP_HWDRM_DEFAULT_SESSION`) will be started, if isn't already running.
  The user is expected to query the PXP status via the query ioctl (see
  `DRM_XE_DEVICE_QUERY_PXP_STATUS`) and to wait for PXP to be ready before
  attempting to create a queue with this property. When a queue is created
  before PXP is ready, the ioctl will return -EBUSY if init is still in
  progress or -EIO if init failed.
  Given that going into a power-saving state kills PXP HWDRM sessions,
  runtime PM will be blocked while queues of this type are alive.
  All PXP queues will be killed if a PXP invalidation event occurs.
- `DRM_XE_EXEC_QUEUE_SET_PROPERTY_MULTI_GROUP` - Create a multi-queue group
  or add secondary queues to a multi-queue group.
  If the extension's 'value' field has `DRM_XE_MULTI_GROUP_CREATE` flag set,
  then a new multi-queue group is created with this queue as the primary queue
  (Q0). Otherwise, the queue gets added to the multi-queue group whose primary
  queue's exec_queue_id is specified in the lower 32 bits of the 'value' field.
  All the other non-relevant bits of extension's 'value' field while adding the
  primary or the secondary queues of the group must be set to 0.
- `DRM_XE_EXEC_QUEUE_SET_PROPERTY_MULTI_QUEUE_PRIORITY` - Set the queue
  priority within the multi-queue group. Current valid priority values are 0–2
  (default is 1), with higher values indicating higher priority.

The example below shows how to use **drm_xe_exec_queue_create** to create
a simple exec_queue (no parallel submission) of class
`DRM_XE_ENGINE_CLASS_RENDER`.

```C
struct drm_xe_engine_class_instance instance = {
    .engine_class = DRM_XE_ENGINE_CLASS_RENDER,
};
struct drm_xe_exec_queue_create exec_queue_create = {
     .extensions = 0,
     .vm_id = vm,
     .num_bb_per_exec = 1,
     .num_eng_per_bb = 1,
     .instances = to_user_pointer(&instance),
};
ioctl(fd, DRM_IOCTL_XE_EXEC_QUEUE_CREATE, &exec_queue_create);

Allow users to provide a hint to kernel for cases demanding low latency
profile. Please note it will have impact on power consumption. User can
indicate low latency hint with flag while creating exec queue as
mentioned below,

struct drm_xe_exec_queue_create exec_queue_create = {
     .flags = DRM_XE_EXEC_QUEUE_LOW_LATENCY_HINT,
     .extensions = 0,
     .vm_id = vm,
     .num_bb_per_exec = 1,
     .num_eng_per_bb = 1,
     .instances = to_user_pointer(&instance),
};
ioctl(fd, DRM_IOCTL_XE_EXEC_QUEUE_CREATE, &exec_queue_create);
```

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

Input of `DRM_IOCTL_XE_EXEC_QUEUE_DESTROY`

**Definition**

```c
struct drm_xe_exec_queue_destroy {
    __u32 exec_queue_id;
    __u32 pad;
    __u64 reserved[2];
};
```

**Members**

- `exec_queue_id`: Exec queue ID
- `pad`: MBZ
- `reserved`: Reserved

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

Input of `DRM_IOCTL_XE_EXEC_QUEUE_GET_PROPERTY`

**Definition**

```c
struct drm_xe_exec_queue_get_property {
        __u64 extensions;
        __u32 exec_queue_id;
    #define DRM_XE_EXEC_QUEUE_GET_PROPERTY_BAN      0;
        __u32 property;
        __u64 value;
        __u64 reserved[2];
};
```

**Members**

- `extensions`: Pointer to the first extension struct, if any
- `exec_queue_id`: Exec queue ID
- `property`: property to get
- `value`: property value
- `reserved`: Reserved

**Description**

- The **property** can be:
  - `DRM_XE_EXEC_QUEUE_GET_PROPERTY_BAN`

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

sync object

**Definition**

```c
struct drm_xe_sync {
        __u64 extensions;
    #define DRM_XE_SYNC_TYPE_SYNCOBJ                0x0;
    #define DRM_XE_SYNC_TYPE_TIMELINE_SYNCOBJ       0x1;
    #define DRM_XE_SYNC_TYPE_USER_FENCE             0x2;
        __u32 type;
    #define DRM_XE_SYNC_FLAG_SIGNAL (1 << 0);
        __u32 flags;
        union {
            __u32 handle;
            __u64 addr;
        };
        __u64 timeline_value;
        __u64 reserved[2];
};
```

**Members**

- `extensions`: Pointer to the first extension struct, if any
- `type`: Type of the this sync object
- `flags`: Sync Flags
- `{unnamed_union}`: anonymous
- `handle`: Handle for the object
- `addr`: Address of user fence. When sync is passed in via exec
  IOCTL this is a GPU address in the VM. When sync passed in via
  VM bind IOCTL this is a user pointer. In either case, it is
  the users responsibility that this address is present and
  mapped when the user fence is signalled. Must be qword
  aligned.
- `timeline_value`: Input for the timeline sync object. Needs to be
  different than 0 when used with `DRM_XE_SYNC_TYPE_TIMELINE_SYNCOBJ`.
- `reserved`: Reserved

**Description**

- The **type** can be:
  - `DRM_XE_SYNC_TYPE_SYNCOBJ`
  - `DRM_XE_SYNC_TYPE_TIMELINE_SYNCOBJ`
  - `DRM_XE_SYNC_TYPE_USER_FENCE`

- and the **flags** can be:
  - `DRM_XE_SYNC_FLAG_SIGNAL`

A minimal use of **drm_xe_sync** looks like this:

```C
struct drm_xe_sync sync = {
    .flags = DRM_XE_SYNC_FLAG_SIGNAL,
    .type = DRM_XE_SYNC_TYPE_SYNCOBJ,
};
struct drm_syncobj_create syncobj_create = { 0 };
ioctl(fd, DRM_IOCTL_SYNCOBJ_CREATE, &syncobj_create);
sync.handle = syncobj_create.handle;
    ...
    use of &sync in drm_xe_exec or drm_xe_vm_bind
    ...
struct drm_syncobj_wait wait = {
    .handles = &sync.handle,
    .timeout_nsec = INT64_MAX,
    .count_handles = 1,
    .flags = 0,
    .first_signaled = 0,
    .pad = 0,
};
ioctl(fd, DRM_IOCTL_SYNCOBJ_WAIT, &wait);
```

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

Input of `DRM_IOCTL_XE_EXEC`

**Definition**

```c
struct drm_xe_exec {
        __u64 extensions;
        __u32 exec_queue_id;
    #define DRM_XE_MAX_SYNCS 1024;
        __u32 num_syncs;
        __u64 syncs;
        __u64 address;
        __u16 num_batch_buffer;
        __u16 pad[3];
        __u64 reserved[2];
};
```

**Members**

- `extensions`: Pointer to the first extension struct, if any
- `exec_queue_id`: Exec queue ID for the batch buffer
- `num_syncs`: Amount of struct drm_xe_sync in array.
- `syncs`: Pointer to struct drm_xe_sync array.
- `address`: address of batch buffer if num_batch_buffer == 1 or an
  array of batch buffer addresses
- `num_batch_buffer`: number of batch buffer in this exec, must match
  the width of the engine
- `pad`: MBZ
- `reserved`: Reserved

**Description**

This is an example to use **drm_xe_exec** for execution of the object
at BIND_ADDRESS (see example in **drm_xe_vm_bind**) by an exec_queue
(see example in **drm_xe_exec_queue_create**). It can be synchronized
by using the example provided for **drm_xe_sync**.

```C
struct drm_xe_exec exec = {
    .exec_queue_id = exec_queue,
    .syncs = &sync,
    .num_syncs = 1,
    .address = BIND_ADDRESS,
    .num_batch_buffer = 1,
};
ioctl(fd, DRM_IOCTL_XE_EXEC, &exec);
```

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

Input of `DRM_IOCTL_XE_WAIT_USER_FENCE`

**Definition**

```c
struct drm_xe_wait_user_fence {
        __u64 extensions;
        __u64 addr;
    #define DRM_XE_UFENCE_WAIT_OP_EQ        0x0;
    #define DRM_XE_UFENCE_WAIT_OP_NEQ       0x1;
    #define DRM_XE_UFENCE_WAIT_OP_GT        0x2;
    #define DRM_XE_UFENCE_WAIT_OP_GTE       0x3;
    #define DRM_XE_UFENCE_WAIT_OP_LT        0x4;
    #define DRM_XE_UFENCE_WAIT_OP_LTE       0x5;
        __u16 op;
    #define DRM_XE_UFENCE_WAIT_FLAG_ABSTIME (1 << 0);
        __u16 flags;
        __u32 pad;
        __u64 value;
        __u64 mask;
        __s64 timeout;
        __u32 exec_queue_id;
        __u32 pad2;
        __u64 reserved[2];
};
```

**Members**

- `extensions`: Pointer to the first extension struct, if any
- `addr`: user pointer address to wait on, must qword aligned
- `op`: wait operation (type of comparison)
- `flags`: wait flags
- `pad`: MBZ
- `value`: compare value
- `mask`: comparison mask
- `timeout`: how long to wait before bailing, value in nanoseconds.
  Without DRM_XE_UFENCE_WAIT_FLAG_ABSTIME flag set (relative timeout)
  it contains timeout expressed in nanoseconds to wait (fence will
  expire at `now()` + timeout).
  When DRM_XE_UFENCE_WAIT_FLAG_ABSTIME flat is set (absolute timeout) wait
  will end at timeout (uses system MONOTONIC_CLOCK).
  Passing negative timeout leads to neverending wait.

  On relative timeout this value is updated with timeout left
  (for restarting the call in case of signal delivery).
  On absolute timeout this value stays intact (restarted call still
  expire at the same point of time).
- `exec_queue_id`: exec_queue_id returned from xe_exec_queue_create_ioctl
- `pad2`: MBZ
- `reserved`: Reserved

**Description**

Wait on user fence, XE will wake-up on every HW engine interrupt in the
instances list and check if user fence is complete:

```text
(*addr & MASK) OP (VALUE & MASK)
```

Returns to user on user fence completion or timeout.

- The **op** can be:
  - `DRM_XE_UFENCE_WAIT_OP_EQ`
  - `DRM_XE_UFENCE_WAIT_OP_NEQ`
  - `DRM_XE_UFENCE_WAIT_OP_GT`
  - `DRM_XE_UFENCE_WAIT_OP_GTE`
  - `DRM_XE_UFENCE_WAIT_OP_LT`
  - `DRM_XE_UFENCE_WAIT_OP_LTE`

- and the **flags** can be:
  - `DRM_XE_UFENCE_WAIT_FLAG_ABSTIME`
  - `DRM_XE_UFENCE_WAIT_FLAG_SOFT_OP`

- The **mask** values can be for example:
  - 0xffu for u8
  - 0xffffu for u16
  - 0xffffffffu for u32
  - 0xffffffffffffffffu for u64

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

Observation stream types

**Constants**

- `DRM_XE_OBSERVATION_TYPE_OA`: OA observation stream type
- `DRM_XE_OBSERVATION_TYPE_EU_STALL`: EU stall sampling observation stream type

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

Observation stream ops

**Constants**

- `DRM_XE_OBSERVATION_OP_STREAM_OPEN`: Open an observation stream
- `DRM_XE_OBSERVATION_OP_ADD_CONFIG`: Add observation stream config
- `DRM_XE_OBSERVATION_OP_REMOVE_CONFIG`: Remove observation stream config

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

Input of `DRM_XE_OBSERVATION`

**Definition**

```c
struct drm_xe_observation_param {
    __u64 extensions;
    __u64 observation_type;
    __u64 observation_op;
    __u64 param;
};
```

**Members**

- `extensions`: Pointer to the first extension struct, if any
- `observation_type`: observation stream type, of enum **drm_xe_observation_type**
- `observation_op`: observation stream op, of enum **drm_xe_observation_op**
- `param`: Pointer to actual stream params

**Description**

The observation layer enables multiplexing observation streams of
multiple types. The actual params for a particular stream operation are
supplied via the **param** pointer (use __copy_from_user to get these
params).

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

Observation stream fd ioctl's

**Constants**

- `DRM_XE_OBSERVATION_IOCTL_ENABLE`: Enable data capture for an observation stream
- `DRM_XE_OBSERVATION_IOCTL_DISABLE`: Disable data capture for a observation stream
- `DRM_XE_OBSERVATION_IOCTL_CONFIG`: Change observation stream configuration
- `DRM_XE_OBSERVATION_IOCTL_STATUS`: Return observation stream status
- `DRM_XE_OBSERVATION_IOCTL_INFO`: Return observation stream info

**Description**

Information exchanged between userspace and kernel for observation fd
ioctl's is stream type specific

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

OA unit types

**Constants**

- `DRM_XE_OA_UNIT_TYPE_OAG`: OAG OA unit. OAR/OAC are considered
  sub-types of OAG. For OAR/OAC, use OAG.
- `DRM_XE_OA_UNIT_TYPE_OAM`: OAM OA unit
- `DRM_XE_OA_UNIT_TYPE_OAM_SAG`: OAM_SAG OA unit
- `DRM_XE_OA_UNIT_TYPE_MERT`: MERT OA unit

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

describe OA unit

**Definition**

```c
struct drm_xe_oa_unit {
        __u64 extensions;
        __u32 oa_unit_id;
        __u32 oa_unit_type;
        __u64 capabilities;
    #define DRM_XE_OA_CAPS_BASE             (1 << 0);
    #define DRM_XE_OA_CAPS_SYNCS            (1 << 1);
    #define DRM_XE_OA_CAPS_OA_BUFFER_SIZE   (1 << 2);
    #define DRM_XE_OA_CAPS_WAIT_NUM_REPORTS (1 << 3);
    #define DRM_XE_OA_CAPS_OAM              (1 << 4);
    #define DRM_XE_OA_CAPS_OA_UNIT_GT_ID    (1 << 5);
        __u64 oa_timestamp_freq;
        __u16 gt_id;
        __u16 reserved1[3];
        __u64 reserved[3];
        __u64 num_engines;
        struct drm_xe_engine_class_instance eci[];
};
```

**Members**

- `extensions`: Pointer to the first extension struct, if any
- `oa_unit_id`: OA unit ID
- `oa_unit_type`: OA unit type of **drm_xe_oa_unit_type**
- `capabilities`: OA capabilities bit-mask
- `oa_timestamp_freq`: OA timestamp freq
- `gt_id`: gt id for this OA unit
- `reserved1`: MBZ
- `reserved`: MBZ
- `num_engines`: number of engines in **eci** array
- `eci`: engines attached to this OA unit

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

describe OA units

**Definition**

```c
struct drm_xe_query_oa_units {
    __u64 extensions;
    __u32 num_oa_units;
    __u32 pad;
    __u64 oa_units[];
};
```

**Members**

- `extensions`: Pointer to the first extension struct, if any
- `num_oa_units`: number of OA units returned in oau\[\]
- `pad`: MBZ
- `oa_units`: struct **drm_xe_oa_unit** array returned for this device.
  Written below as a u64 array to avoid problems with nested flexible
  arrays with some compilers

**Description**

If a query is made with a struct drm_xe_device_query where .query
is equal to DRM_XE_DEVICE_QUERY_OA_UNITS, then the reply uses struct
drm_xe_query_oa_units in .data.

OA unit properties for all OA units can be accessed using a code block
such as the one below:

```C
struct drm_xe_query_oa_units *qoa;
struct drm_xe_oa_unit *oau;
u8 *poau;

// malloc qoa and issue DRM_XE_DEVICE_QUERY_OA_UNITS. Then:
poau = (u8 *)&qoa->oa_units[0];
for (int i = 0; i < qoa->num_oa_units; i++) {
        oau = (struct drm_xe_oa_unit *)poau;
        // Access 'struct drm_xe_oa_unit' fields here
        poau += sizeof(*oau) + oau->num_engines * sizeof(oau->eci[0]);
}
```

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

OA format types as specified in PRM/Bspec 52198/60942

**Constants**

- `DRM_XE_OA_FMT_TYPE_OAG`: OAG report format
- `DRM_XE_OA_FMT_TYPE_OAR`: OAR report format
- `DRM_XE_OA_FMT_TYPE_OAM`: OAM report format
- `DRM_XE_OA_FMT_TYPE_OAC`: OAC report format
- `DRM_XE_OA_FMT_TYPE_OAM_MPEC`: OAM SAMEDIA or OAM MPEC report format
- `DRM_XE_OA_FMT_TYPE_PEC`: PEC report format

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

OA stream property id's

**Constants**

- `DRM_XE_OA_PROPERTY_OA_UNIT_ID`: ID of the OA unit on which to open
  the OA stream, see **oa_unit_id** in 'struct
  drm_xe_query_oa_units'. Defaults to 0 if not provided.
- `DRM_XE_OA_PROPERTY_SAMPLE_OA`: A value of 1 requests inclusion of raw
  OA unit reports or stream samples in a global buffer attached to an
  OA unit.
- `DRM_XE_OA_PROPERTY_OA_METRIC_SET`: OA metrics defining contents of OA
  reports, previously added via **DRM_XE_OBSERVATION_OP_ADD_CONFIG**.
- `DRM_XE_OA_PROPERTY_OA_FORMAT`: OA counter report format
- `DRM_XE_OA_PROPERTY_OA_PERIOD_EXPONENT`: Requests periodic OA unit
  sampling with sampling frequency proportional to 2^(period_exponent + 1)
- `DRM_XE_OA_PROPERTY_OA_DISABLED`: A value of 1 will open the OA
  stream in a DISABLED state (see **DRM_XE_OBSERVATION_IOCTL_ENABLE**).
- `DRM_XE_OA_PROPERTY_EXEC_QUEUE_ID`: Open the stream for a specific
  **exec_queue_id**. OA queries can be executed on this exec queue.
- `DRM_XE_OA_PROPERTY_OA_ENGINE_INSTANCE`: Optional engine instance to
  pass along with **DRM_XE_OA_PROPERTY_EXEC_QUEUE_ID** or will default to 0.
- `DRM_XE_OA_PROPERTY_NO_PREEMPT`: Allow preemption and timeslicing
  to be disabled for the stream exec queue.
- `DRM_XE_OA_PROPERTY_NUM_SYNCS`: Number of syncs in the sync array
  specified in **DRM_XE_OA_PROPERTY_SYNCS**
- `DRM_XE_OA_PROPERTY_SYNCS`: Pointer to struct **drm_xe_sync** array
  with array size specified via **DRM_XE_OA_PROPERTY_NUM_SYNCS**. OA
  configuration will wait till input fences signal. Output fences
  will signal after the new OA configuration takes effect. For
  **DRM_XE_SYNC_TYPE_USER_FENCE**, **addr** is a user pointer, similar
  to the VM bind case.
- `DRM_XE_OA_PROPERTY_OA_BUFFER_SIZE`: Size of OA buffer to be
  allocated by the driver in bytes. Supported sizes are powers of
  2 from 128 KiB to 128 MiB. When not specified, a 16 MiB OA
  buffer is allocated by default.
- `DRM_XE_OA_PROPERTY_WAIT_NUM_REPORTS`: Number of reports to wait
  for before unblocking poll or read

**Description**

Stream params are specified as a chain of **drm_xe_ext_set_property**
struct's, with **property** values from enum **drm_xe_oa_property_id** and
**drm_xe_user_extension** base.name set to **DRM_XE_OA_EXTENSION_SET_PROPERTY**.
**param** field in struct **drm_xe_observation_param** points to the first
**drm_xe_ext_set_property** struct.

Exactly the same mechanism is also used for stream reconfiguration using the
**DRM_XE_OBSERVATION_IOCTL_CONFIG** observation stream fd ioctl, though only a
subset of properties below can be specified for stream reconfiguration.

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

OA metric configuration

**Definition**

```c
struct drm_xe_oa_config {
    __u64 extensions;
    char uuid[36];
    __u32 n_regs;
    __u64 regs_ptr;
};
```

**Members**

- `extensions`: Pointer to the first extension struct, if any
- `uuid`: String formatted like "%\08x-%\04x-%\04x-%\04x-%\012x"
- `n_regs`: Number of regs in **regs_ptr**
- `regs_ptr`: Pointer to (register address, value) pairs for OA config
  registers. Expected length of buffer is: (2 * sizeof(u32) * **n_regs**).

**Description**

Multiple OA configs can be added using **DRM_XE_OBSERVATION_OP_ADD_CONFIG**. A
particular config can be specified when opening an OA stream using
**DRM_XE_OA_PROPERTY_OA_METRIC_SET** property.

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

OA stream status returned from **DRM_XE_OBSERVATION_IOCTL_STATUS** observation stream fd ioctl. Userspace can call the ioctl to query stream status in response to EIO errno from observation fd `read()`.

**Definition**

```c
struct drm_xe_oa_stream_status {
        __u64 extensions;
        __u64 oa_status;
    #define DRM_XE_OASTATUS_MMIO_TRG_Q_FULL         (1 << 3);
    #define DRM_XE_OASTATUS_COUNTER_OVERFLOW        (1 << 2);
    #define DRM_XE_OASTATUS_BUFFER_OVERFLOW         (1 << 1);
    #define DRM_XE_OASTATUS_REPORT_LOST             (1 << 0);
        __u64 reserved[3];
};
```

**Members**

- `extensions`: Pointer to the first extension struct, if any
- `oa_status`: OA stream status (see Bspec 46717/61226)
- `reserved`: reserved for future use

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

OA stream info returned from **DRM_XE_OBSERVATION_IOCTL_INFO** observation stream fd ioctl

**Definition**

```c
struct drm_xe_oa_stream_info {
    __u64 extensions;
    __u64 oa_buf_size;
    __u64 reserved[3];
};
```

**Members**

- `extensions`: Pointer to the first extension struct, if any
- `oa_buf_size`: OA buffer size
- `reserved`: reserved for future use

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

Supported PXP session types.

**Constants**

- `DRM_XE_PXP_TYPE_NONE`: PXP not used
- `DRM_XE_PXP_TYPE_HWDRM`: HWDRM sessions are used for content that ends
  up on the display.

**Description**

We currently only support HWDRM sessions, which are used for protected
content that ends up being displayed, but the HW supports multiple types, so
we might extend support in the future.

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

EU stall sampling input property ids.

**Constants**

- `DRM_XE_EU_STALL_PROP_GT_ID`:

  **gt_id** of the GT on which
  EU stall data will be captured.
- `DRM_XE_EU_STALL_PROP_SAMPLE_RATE`: Sampling rate in
  GPU cycles from **sampling_rates** in struct **drm_xe_query_eu_stall**
- `DRM_XE_EU_STALL_PROP_WAIT_NUM_REPORTS`: Minimum number of
  EU stall data reports to be present in the kernel buffer
  before unblocking a blocked poll or read.

**Description**

These properties are passed to the driver at open as a chain of
**drm_xe_ext_set_property** structures with **property** set to these
properties' enums and **value** set to the corresponding values of these
properties. **drm_xe_user_extension** base.name should be set to
**DRM_XE_EU_STALL_EXTENSION_SET_PROPERTY**.

With the file descriptor obtained from open, user space must enable
the EU stall stream fd with **DRM_XE_OBSERVATION_IOCTL_ENABLE** before
calling `read()`. EIO errno from `read()` indicates HW dropped data
due to full buffer.

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

Information about EU stall sampling.

**Definition**

```c
struct drm_xe_query_eu_stall {
        __u64 extensions;
        __u64 capabilities;
    #define DRM_XE_EU_STALL_CAPS_BASE               (1 << 0);
        __u64 record_size;
        __u64 per_xecore_buf_size;
        __u64 reserved[5];
        __u64 num_sampling_rates;
        __u64 sampling_rates[];
};
```

**Members**

- `extensions`: Pointer to the first extension struct, if any
- `capabilities`: EU stall capabilities bit-mask
- `record_size`: size of each EU stall data record
- `per_xecore_buf_size`: internal per XeCore buffer size
- `reserved`: Reserved
- `num_sampling_rates`: Number of sampling rates in **sampling_rates** array
- `sampling_rates`: Flexible array of sampling rates
  sorted in the fastest to slowest order.
  Sampling rates are specified in GPU clock cycles.

**Description**

If a query is made with a struct **drm_xe_device_query** where .query
is equal to **DRM_XE_DEVICE_QUERY_EU_STALL**, then the reply uses
struct **drm_xe_query_eu_stall** in .data.

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

Input of `DRM_IOCTL_XE_MADVISE`

**Definition**

```c
struct drm_xe_madvise {
        __u64 extensions;
        __u64 start;
        __u64 range;
        __u32 vm_id;
    #define DRM_XE_MEM_RANGE_ATTR_PREFERRED_LOC     0;
    #define DRM_XE_MEM_RANGE_ATTR_ATOMIC            1;
    #define DRM_XE_MEM_RANGE_ATTR_PAT               2;
        __u32 type;
        union {
            struct {
    #define DRM_XE_PREFERRED_LOC_DEFAULT_DEVICE     0;
    #define DRM_XE_PREFERRED_LOC_DEFAULT_SYSTEM     -1;
                __u32 devmem_fd;
    #define DRM_XE_MIGRATE_ALL_PAGES                0;
    #define DRM_XE_MIGRATE_ONLY_SYSTEM_PAGES        1;
                __u16 migration_policy;
                __u16 region_instance;
                __u64 reserved;
            } preferred_mem_loc;
            struct {
    #define DRM_XE_ATOMIC_UNDEFINED 0;
    #define DRM_XE_ATOMIC_DEVICE    1;
    #define DRM_XE_ATOMIC_GLOBAL    2;
    #define DRM_XE_ATOMIC_CPU       3;
                __u32 val;
                __u32 pad;
                __u64 reserved;
            } atomic;
            struct {
                __u32 val;
                __u32 pad;
                __u64 reserved;
            } pat_index;
        };
        __u64 reserved[2];
};
```

**Members**

- `extensions`: Pointer to the first extension struct, if any
- `start`: start of the virtual address range
- `range`: size of the virtual address range
- `vm_id`: vm_id of the virtual range
- `type`: type of attribute
- `{unnamed_union}`: anonymous
- `preferred_mem_loc`: preferred memory location

  Used when **type** == DRM_XE_MEM_RANGE_ATTR_PREFERRED_LOC

  - Supported values for **preferred_mem_loc.devmem_fd**:
    - DRM_XE_PREFERRED_LOC_DEFAULT_DEVICE: set vram of fault tile as preferred loc
    - DRM_XE_PREFERRED_LOC_DEFAULT_SYSTEM: set smem as preferred loc

  - Supported values for **preferred_mem_loc.migration_policy**:
    - DRM_XE_MIGRATE_ALL_PAGES
    - DRM_XE_MIGRATE_ONLY_SYSTEM_PAGES
- `preferred_mem_loc.devmem_fd`: Device file-descriptor of the device where the
  preferred memory is located, or one of the
  above special values. Please also see
  **preferred_mem_loc.region_instance** below.
- `preferred_mem_loc.migration_policy`: Page migration policy
- `preferred_mem_loc.region_instance`: Region instance.
  MBZ if **devmem_fd** \<= `DRM_XE_PREFERRED_LOC_DEFAULT_DEVICE`.
  Otherwise should point to the desired device
  VRAM instance of the device indicated by
  **preferred_mem_loc.devmem_fd**.
- `preferred_mem_loc.reserved`: Reserved
- `atomic`: Atomic access policy

  Used when **type** == DRM_XE_MEM_RANGE_ATTR_ATOMIC.

  - Supported values for **atomic.val**:
    - DRM_XE_ATOMIC_UNDEFINED: Undefined or default behaviour.
      Support both GPU and CPU atomic operations for system allocator.
      Support GPU atomic operations for normal(bo) allocator.
    - DRM_XE_ATOMIC_DEVICE: Support GPU atomic operations.
    - DRM_XE_ATOMIC_GLOBAL: Support both GPU and CPU atomic operations.
    - DRM_XE_ATOMIC_CPU: Support CPU atomic only, no GPU atomics supported.
- `atomic.val`: value of atomic operation
- `atomic.pad`: MBZ
- `atomic.reserved`: Reserved
- `pat_index`: Page attribute table index

  Used when **type** == DRM_XE_MEM_RANGE_ATTR_PAT.
- `pat_index.val`: PAT index value
- `pat_index.pad`: MBZ
- `pat_index.reserved`: Reserved
- `reserved`: Reserved

**Description**

This structure is used to set memory attributes for a virtual address range
in a VM. The type of attribute is specified by **type**, and the corresponding
union member is used to provide additional parameters for **type**.

- Supported attribute types:
  - DRM_XE_MEM_RANGE_ATTR_PREFERRED_LOC: Set preferred memory location.
  - DRM_XE_MEM_RANGE_ATTR_ATOMIC: Set atomic access policy.
  - DRM_XE_MEM_RANGE_ATTR_PAT: Set page attribute table index.

**Example**

```C
struct drm_xe_madvise madvise = {
     .vm_id = vm_id,
     .start = 0x100000,
     .range = 0x2000,
     .type = DRM_XE_MEM_RANGE_ATTR_ATOMIC,
     .atomic_val = DRM_XE_ATOMIC_DEVICE,
};

ioctl(fd, DRM_IOCTL_XE_MADVISE, &madvise);
```

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

Output of `DRM_IOCTL_XE_VM_QUERY_MEM_RANGES_ATTRS`

**Definition**

```c
struct drm_xe_mem_range_attr {
    __u64 extensions;
    __u64 start;
    __u64 end;
    struct {
        __u32 devmem_fd;
        __u32 migration_policy;
    } preferred_mem_loc;
    struct {
        __u32 val;
        __u32 reserved;
    } atomic;
    struct {
        __u32 val;
        __u32 reserved;
    } pat_index;
    __u64 reserved[2];
};
```

**Members**

- `extensions`: Pointer to the first extension struct, if any
- `start`: start of the memory range
- `end`: end of the memory range
- `preferred_mem_loc`: preferred memory location
- `preferred_mem_loc.devmem_fd`: fd for preferred loc
- `preferred_mem_loc.migration_policy`: Page migration policy
- `atomic`: Atomic access policy
- `atomic.val`: atomic attribute
- `atomic.reserved`: Reserved
- `pat_index`: Page attribute table index
- `pat_index.val`: PAT index
- `pat_index.reserved`: Reserved
- `reserved`: Reserved

**Description**

This structure is provided by userspace and filled by KMD in response to the
DRM_IOCTL_XE_VM_QUERY_MEM_RANGES_ATTRS ioctl. It describes memory attributes of
a memory ranges within a user specified address range in a VM.

The structure includes information such as atomic access policy,
page attribute table (PAT) index, and preferred memory location.
Userspace allocates an array of these structures and passes a pointer to the
ioctl to retrieve attributes for each memory ranges

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

Input of `DRM_IOCTL_XE_VM_QUERY_MEM_ATTRIBUTES`

**Definition**

```c
struct drm_xe_vm_query_mem_range_attr {
    __u64 extensions;
    __u32 vm_id;
    __u32 num_mem_ranges;
    __u64 start;
    __u64 range;
    __u64 sizeof_mem_range_attr;
    __u64 vector_of_mem_attr;
    __u64 reserved[2];
};
```

**Members**

- `extensions`: Pointer to the first extension struct, if any
- `vm_id`: vm_id of the virtual range
- `num_mem_ranges`: number of mem_ranges in range
- `start`: start of the virtual address range
- `range`: size of the virtual address range
- `sizeof_mem_range_attr`: size of struct drm_xe_mem_range_attr
- `vector_of_mem_attr`: userptr to array of struct drm_xe_mem_range_attr
- `reserved`: Reserved

**Description**

This structure is used to query memory attributes of memory regions
within a user specified address range in a VM. It provides detailed
information about each memory range, including atomic access policy,
page attribute table (PAT) index, and preferred memory location.

Userspace first calls the ioctl with **num_mem_ranges** = 0,
**sizeof_mem_ranges_attr** = 0 and **vector_of_vma_mem_attr** = NULL to retrieve
the number of memory regions and size of each memory range attribute.
Then, it allocates a buffer of that size and calls the ioctl again to fill
the buffer with memory range attributes.

If second call fails with -ENOSPC, it means memory ranges changed between
first call and now, retry IOCTL again with **num_mem_ranges** = 0,
**sizeof_mem_ranges_attr** = 0 and **vector_of_vma_mem_attr** = NULL followed by
Second ioctl call.

**Example**

```C
struct drm_xe_vm_query_mem_range_attr query = {
     .vm_id = vm_id,
     .start = 0x100000,
     .range = 0x2000,
 };

// First ioctl call to get num of mem regions and sizeof each attribute
ioctl(fd, DRM_IOCTL_XE_VM_QUERY_MEM_RANGE_ATTRS, &query);

// Allocate buffer for the memory region attributes
void *ptr = malloc(query.num_mem_ranges * query.sizeof_mem_range_attr);
void *ptr_start = ptr;

query.vector_of_mem_attr = (uintptr_t)ptr;

// Second ioctl call to actually fill the memory attributes
ioctl(fd, DRM_IOCTL_XE_VM_QUERY_MEM_RANGE_ATTRS, &query);

// Iterate over the returned memory region attributes
for (unsigned int i = 0; i < query.num_mem_ranges; ++i) {
   struct drm_xe_mem_range_attr *attr = (struct drm_xe_mem_range_attr *)ptr;

   // Do something with attr

   // Move pointer by one entry
   ptr += query.sizeof_mem_range_attr;
 }

free(ptr_start);
```

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

exec queue set property

**Definition**

```c
struct drm_xe_exec_queue_set_property {
    __u64 extensions;
    __u32 exec_queue_id;
    __u32 property;
    __u64 value;
    __u64 reserved[2];
};
```

**Members**

- `extensions`: Pointer to the first extension struct, if any
- `exec_queue_id`: Exec queue ID
- `property`: property to set
- `value`: property value
- `reserved`: Reserved

**Description**

Sets execution queue properties dynamically.
Currently only `DRM_XE_EXEC_QUEUE_SET_PROPERTY_MULTI_QUEUE_PRIORITY`
property can be dynamically set.


<a id="rst-drm-asahi-uapi"></a>

## drm/asahi uAPI


**Introduction to the Asahi UAPI**

This documentation describes the Asahi IOCTLs.

Just a few generic rules about the data passed to the Asahi IOCTLs (cribbed
from Panthor):

- Structures must be aligned on 64-bit/8-byte. If the object is not
  naturally aligned, a padding field must be added.
- Fields must be explicitly aligned to their natural type alignment with
  pad\[0..N\] fields.
- All padding fields will be checked by the driver to make sure they are
  zeroed.
- Flags can be added, but not removed/replaced.
- New fields can be added to the main structures (the structures
  directly passed to the ioctl). Those fields can be added at the end of
  the structure, or replace existing padding fields. Any new field being
  added must preserve the behavior that existed before those fields were
  added when a value of zero is passed.
- New fields can be added to indirect objects (objects pointed by the
  main structure), iff those objects are passed a size to reflect the
  size known by the userspace driver (see
  drm_asahi_cmd_header::size).
- If the kernel driver is too old to know some fields, those will be
  ignored if zero, and otherwise rejected (and so will be zero on output).
- If userspace is too old to know some fields, those will be zeroed
  (input) before the structure is parsed by the kernel driver.
- Each new flag/field addition must come with a driver version update so
  the userspace driver doesn't have to guess which flags are supported.
- Structures should not contain unions, as this would defeat the
  extensibility of such structures.
- IOCTLs can't be removed or replaced. New IOCTL IDs should be placed
  at the end of the drm_asahi_ioctl_id enum.

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

IOCTL IDs

**Constants**

- `DRM_ASAHI_GET_PARAMS`: Query device properties.
- `DRM_ASAHI_GET_TIME`: Query device time.
- `DRM_ASAHI_VM_CREATE`: Create a GPU VM address space.
- `DRM_ASAHI_VM_DESTROY`: Destroy a VM.
- `DRM_ASAHI_VM_BIND`: Bind/unbind memory to a VM.
- `DRM_ASAHI_GEM_CREATE`: Create a buffer object.
- `DRM_ASAHI_GEM_MMAP_OFFSET`: Get offset to pass to `mmap()` to map a
  given GEM handle.
- `DRM_ASAHI_GEM_BIND_OBJECT`: Bind memory as a special object
- `DRM_ASAHI_QUEUE_CREATE`: Create a scheduling queue.
- `DRM_ASAHI_QUEUE_DESTROY`: Destroy a scheduling queue.
- `DRM_ASAHI_SUBMIT`: Submit commands to a queue.

**Description**

Place new ioctls at the end, don't re-order, don't replace or remove entries.

These IDs are not meant to be used directly. Use the DRM_IOCTL_ASAHI_xxx
definitions instead.

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

Global parameters.

**Definition**

```c
struct drm_asahi_params_global {
    __u64 features;
    __u32 gpu_generation;
    __u32 gpu_variant;
    __u32 gpu_revision;
    __u32 chip_id;
    __u32 num_dies;
    __u32 num_clusters_total;
    __u32 num_cores_per_cluster;
    __u32 max_frequency_khz;
    __u64 core_masks[DRM_ASAHI_MAX_CLUSTERS];
    __u64 vm_start;
    __u64 vm_end;
    __u64 vm_kernel_min_size;
    __u32 max_commands_per_submission;
    __u32 max_attachments;
    __u64 command_timestamp_frequency_hz;
};
```

**Members**

- `features`: Feature bits from drm_asahi_feature
- `gpu_generation`: GPU generation, e.g. 13 for G13G
- `gpu_variant`: GPU variant as a character, e.g. 'C' for G13C
- `gpu_revision`: GPU revision in BCD, e.g. 0x00 for 'A0' or
  0x21 for 'C1'
- `chip_id`: Chip ID in BCD, e.g. 0x8103 for T8103
- `num_dies`: Number of dies in the SoC
- `num_clusters_total`: Number of GPU clusters (across all dies)
- `num_cores_per_cluster`: Number of logical cores per cluster
  (including inactive/nonexistent)
- `max_frequency_khz`: Maximum GPU core clock frequency
- `core_masks`: Bitmask of present/enabled cores per cluster
- `vm_start`: VM range start VMA. Together with **vm_end**, this defines
  the window of valid GPU VAs. Userspace is expected to subdivide VAs
  out of this window.

  This window contains all virtual addresses that userspace needs to
  know about. There may be kernel-internal GPU VAs outside this range,
  but that detail is not relevant here.
- `vm_end`: VM range end VMA
- `vm_kernel_min_size`: Minimum kernel VMA window size.

  When creating a VM, userspace is required to carve out a section of
  virtual addresses (within the range given by **vm_start** and
  **vm_end**). The kernel will allocate various internal structures
  within the specified VA range.

  Allowing userspace to choose the VA range for the kernel, rather than
  the kernel reserving VAs and requiring userspace to cope, can assist
  in implementing SVM.
- `max_commands_per_submission`: Maximum number of supported commands
  per submission. This mirrors firmware limits. Userspace must split up
  larger command buffers, which may require inserting additional
  synchronization.
- `max_attachments`: Maximum number of drm_asahi_attachment's per
  command
- `command_timestamp_frequency_hz`: Timebase frequency for timestamps
  written during command execution, specified via drm_asahi_timestamp
  structures. As this rate is controlled by the firmware, it is a
  queryable parameter.

  Userspace must divide by this frequency to convert timestamps to
  seconds, rather than hardcoding a particular firmware's rate.

**Description**

This struct may be queried by drm_asahi_get_params.

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

Feature bits

**Constants**

- `DRM_ASAHI_FEATURE_SOFT_FAULTS`: GPU has "soft fault" enabled. Shader
  loads of unmapped memory will return zero. Shader stores to unmapped
  memory will be silently discarded. Note that only shader load/store
  is affected. Other hardware units are not affected, notably including
  texture sampling.

  Soft fault is set when initializing the GPU and cannot be runtime
  toggled. Therefore, it is exposed as a feature bit and not a
  userspace-settable flag on the VM. When soft fault is enabled,
  userspace can speculate memory accesses more aggressively.

**Description**

This covers only features that userspace cannot infer from the architecture
version. Most features don't need to be here.

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

Arguments passed to DRM_IOCTL_ASAHI_GET_PARAMS

**Definition**

```c
struct drm_asahi_get_params {
    __u32 param_group;
    __u32 pad;
    __u64 pointer;
    __u64 size;
};
```

**Members**

- `param_group`: Parameter group to fetch (MBZ)
- `pad`: MBZ
- `pointer`: User pointer to write parameter struct
- `size`: Size of the user buffer. In case of older userspace, this may
  be less than sizeof(struct drm_asahi_params_global). The kernel will
  not write past the length specified here, allowing extensibility.

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

Arguments passed to DRM_IOCTL_ASAHI_VM_CREATE

**Definition**

```c
struct drm_asahi_vm_create {
    __u64 kernel_start;
    __u64 kernel_end;
    __u32 vm_id;
    __u32 pad;
};
```

**Members**

- `kernel_start`: Start of the kernel-reserved address range. See
  drm_asahi_params_global::vm_kernel_min_size.

  Both **kernel_start** and **kernel_end** must be within the range of
  valid VAs given by drm_asahi_params_global::vm_start and
  drm_asahi_params_global::vm_end. The size of the kernel range
  (**kernel_end** - **kernel_start**) must be at least
  drm_asahi_params_global::vm_kernel_min_size.

  Userspace must not bind any memory on this VM into this reserved
  range, it is for kernel use only.
- `kernel_end`: End of the kernel-reserved address range. See
  **kernel_start**.
- `vm_id`: Returned VM ID
- `pad`: MBZ

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

Arguments passed to DRM_IOCTL_ASAHI_VM_DESTROY

**Definition**

```c
struct drm_asahi_vm_destroy {
    __u32 vm_id;
    __u32 pad;
};
```

**Members**

- `vm_id`: VM ID to be destroyed
- `pad`: MBZ

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

Flags for GEM creation

**Constants**

- `DRM_ASAHI_GEM_WRITEBACK`: BO should be CPU-mapped as writeback.

  Map as writeback instead of write-combine. This optimizes for CPU
  reads.
- `DRM_ASAHI_GEM_VM_PRIVATE`: BO is private to this GPU VM (no exports).

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

Arguments passed to DRM_IOCTL_ASAHI_GEM_CREATE

**Definition**

```c
struct drm_asahi_gem_create {
    __u64 size;
    __u32 flags;
    __u32 vm_id;
    __u32 handle;
    __u32 pad;
};
```

**Members**

- `size`: Size of the BO
- `flags`: Combination of drm_asahi_gem_flags flags.
- `vm_id`: VM ID to assign to the BO, if DRM_ASAHI_GEM_VM_PRIVATE is set
- `handle`: Returned GEM handle for the BO
- `pad`: MBZ

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

Arguments passed to DRM_IOCTL_ASAHI_GEM_MMAP_OFFSET

**Definition**

```c
struct drm_asahi_gem_mmap_offset {
    __u32 handle;
    __u32 flags;
    __u64 offset;
};
```

**Members**

- `handle`: Handle for the object being mapped.
- `flags`: Must be zero
- `offset`: The fake offset to use for subsequent mmap call

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

Flags for GEM binding

**Constants**

- `DRM_ASAHI_BIND_UNBIND`: Instead of binding a GEM object to the range,
  simply unbind the GPU VMA range.
- `DRM_ASAHI_BIND_READ`: Map BO with GPU read permission
- `DRM_ASAHI_BIND_WRITE`: Map BO with GPU write permission
- `DRM_ASAHI_BIND_SINGLE_PAGE`: Map a single page of the BO repeatedly
  across the VA range.

  This is useful to fill a VA range with scratch pages or zero pages.
  It is intended as a mechanism to accelerate sparse.

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

Description of a single GEM bind operation.

**Definition**

```c
struct drm_asahi_gem_bind_op {
    __u32 flags;
    __u32 handle;
    __u64 offset;
    __u64 range;
    __u64 addr;
};
```

**Members**

- `flags`: Combination of drm_asahi_bind_flags flags.
- `handle`: GEM object to bind (except for UNBIND)
- `offset`: Offset into the object (except for UNBIND).

  For a regular bind, this is the beginning of the region of the GEM
  object to bind.

  For a single-page bind, this is the offset to the single page that
  will be repeatedly bound.

  Must be page-size aligned.
- `range`: Number of bytes to bind/unbind to **addr**.

  Must be page-size aligned.
- `addr`: Address to bind to.

  Must be page-size aligned.

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

Arguments passed to DRM_IOCTL_ASAHI_VM_BIND

**Definition**

```c
struct drm_asahi_vm_bind {
    __u32 vm_id;
    __u32 num_binds;
    __u32 stride;
    __u32 pad;
    __u64 userptr;
};
```

**Members**

- `vm_id`: The ID of the VM to bind to
- `num_binds`: number of binds in this IOCTL.
- `stride`: Stride in bytes between consecutive binds. This allows
  extensibility of drm_asahi_gem_bind_op.
- `pad`: MBZ
- `userptr`: User pointer to an array of **num_binds** structures of type
  **drm_asahi_gem_bind_op** and size **stride** bytes.

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

Special object bind operation

**Constants**

- `DRM_ASAHI_BIND_OBJECT_OP_BIND`: Bind a BO as a special GPU object
- `DRM_ASAHI_BIND_OBJECT_OP_UNBIND`: Unbind a special GPU object

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

Special object bind flags

**Constants**

- `DRM_ASAHI_BIND_OBJECT_USAGE_TIMESTAMPS`: Map a BO as a timestamp
  buffer.

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

Arguments passed to DRM_IOCTL_ASAHI_GEM_BIND_OBJECT

**Definition**

```c
struct drm_asahi_gem_bind_object {
    __u32 op;
    __u32 flags;
    __u32 handle;
    __u32 vm_id;
    __u64 offset;
    __u64 range;
    __u32 object_handle;
    __u32 pad;
};
```

**Members**

- `op`: Bind operation (enum drm_asahi_bind_object_op)
- `flags`: Combination of drm_asahi_bind_object_flags flags.
- `handle`: GEM object to bind/unbind (BIND)
- `vm_id`: The ID of the VM to operate on (MBZ currently)
- `offset`: Offset into the object (BIND only)
- `range`: Number of bytes to bind/unbind (BIND only)
- `object_handle`: Object handle (out for BIND, in for UNBIND)
- `pad`: MBZ

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

Command type

**Constants**

- `DRM_ASAHI_CMD_RENDER`: Render command, executing on the render
  subqueue. Combined vertex and fragment operation.

  Followed by a **drm_asahi_cmd_render** payload.
- `DRM_ASAHI_CMD_COMPUTE`: Compute command on the compute subqueue.

  Followed by a **drm_asahi_cmd_compute** payload.
- `DRM_ASAHI_SET_VERTEX_ATTACHMENTS`: Software command to set
  attachments for subsequent vertex shaders in the same submit.

  Followed by (possibly multiple) **drm_asahi_attachment** payloads.
- `DRM_ASAHI_SET_FRAGMENT_ATTACHMENTS`: Software command to set
  attachments for subsequent fragment shaders in the same submit.

  Followed by (possibly multiple) **drm_asahi_attachment** payloads.
- `DRM_ASAHI_SET_COMPUTE_ATTACHMENTS`: Software command to set
  attachments for subsequent compute shaders in the same submit.

  Followed by (possibly multiple) **drm_asahi_attachment** payloads.

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

Scheduling queue priority.

**Constants**

- `DRM_ASAHI_PRIORITY_LOW`: Low priority queue.
- `DRM_ASAHI_PRIORITY_MEDIUM`: Medium priority queue.
- `DRM_ASAHI_PRIORITY_HIGH`: High priority queue.

  Reserved for future extension.
- `DRM_ASAHI_PRIORITY_REALTIME`: Real-time priority queue.

  Reserved for future extension.

**Description**

These priorities are forwarded to the firmware to influence firmware
scheduling. The exact policy is ultimately decided by firmware, but
these enums allow userspace to communicate the intentions.

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

Arguments passed to DRM_IOCTL_ASAHI_QUEUE_CREATE

**Definition**

```c
struct drm_asahi_queue_create {
    __u32 flags;
    __u32 vm_id;
    __u32 priority;
    __u32 queue_id;
    __u64 usc_exec_base;
};
```

**Members**

- `flags`: MBZ
- `vm_id`: The ID of the VM this queue is bound to
- `priority`: One of drm_asahi_priority
- `queue_id`: The returned queue ID
- `usc_exec_base`: GPU base address for all USC binaries (shaders) on
  this queue. USC addresses are 32-bit relative to this 64-bit base.

  This sets the following registers on all queue commands:

  USC_EXEC_BASE_TA  (vertex)
  USC_EXEC_BASE_ISP (fragment)
  USC_EXEC_BASE_CP  (compute)

  While the hardware lets us configure these independently per command,
  we do not have a use case for this. Instead, we expect userspace to
  fix a 4GiB VA carveout for USC memory and pass its base address here.

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

Arguments passed to DRM_IOCTL_ASAHI_QUEUE_DESTROY

**Definition**

```c
struct drm_asahi_queue_destroy {
    __u32 queue_id;
    __u32 pad;
};
```

**Members**

- `queue_id`: The queue ID to be destroyed
- `pad`: MBZ

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

Sync item type

**Constants**

- `DRM_ASAHI_SYNC_SYNCOBJ`: Binary sync object
- `DRM_ASAHI_SYNC_TIMELINE_SYNCOBJ`: Timeline sync object

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

Sync item

**Definition**

```c
struct drm_asahi_sync {
    __u32 sync_type;
    __u32 handle;
    __u64 timeline_value;
};
```

**Members**

- `sync_type`: One of drm_asahi_sync_type
- `handle`: The sync object handle
- `timeline_value`: Timeline value for timeline sync objects

#### <a id="c-DRM_ASAHI_BARRIER_NONE"></a>`DRM_ASAHI_BARRIER_NONE`

```c
DRM_ASAHI_BARRIER_NONE
```

Command index for no barrier

**Description**

This special value may be passed in to drm_asahi_command::vdm_barrier or
drm_asahi_command::cdm_barrier to indicate that the respective subqueue
should not wait on any previous work.

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

Top level command structure

**Definition**

```c
struct drm_asahi_cmd_header {
    __u16 cmd_type;
    __u16 size;
    __u16 vdm_barrier;
    __u16 cdm_barrier;
};
```

**Members**

- `cmd_type`: One of drm_asahi_cmd_type
- `size`: Size of this command, not including this header.

  For hardware commands, this enables extensibility of commands without
  requiring extra command types. Passing a command that is shorter
  than expected is explicitly allowed for backwards-compatibility.
  Truncated fields will be zeroed.

  For the synthetic attachment setting commands, this implicitly
  encodes the number of attachments. These commands take multiple
  fixed-size **drm_asahi_attachment** structures as their payload, so size
  equals number of attachments * sizeof(struct drm_asahi_attachment).
- `vdm_barrier`: VDM (render) command index to wait on.

  Barriers are indices relative to the beginning of a given submit. A
  barrier of 0 waits on commands submitted to the respective subqueue
  in previous submit ioctls. A barrier of N waits on N previous
  commands on the subqueue within the current submit ioctl. As a
  special case, passing **DRM_ASAHI_BARRIER_NONE** avoids waiting on any
  commands in the subqueue.

  Examples:

  0: This waits on all previous work.

  NONE: This does not wait for anything on this subqueue.

  1: This waits on the first render command in the submit.
  This is valid only if there are multiple render commands in the
  same submit.

  Barriers are valid only for hardware commands. Synthetic software
  commands to set attachments must pass NONE here.
- `cdm_barrier`: CDM (compute) command index to wait on.

  See **vdm_barrier**, and replace VDM/render with CDM/compute.

**Description**

This struct is core to the command buffer definition and therefore is not
extensible.

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

Arguments passed to DRM_IOCTL_ASAHI_SUBMIT

**Definition**

```c
struct drm_asahi_submit {
    __u64 syncs;
    __u64 cmdbuf;
    __u32 flags;
    __u32 queue_id;
    __u32 in_sync_count;
    __u32 out_sync_count;
    __u32 cmdbuf_size;
    __u32 pad;
};
```

**Members**

- `syncs`: An optional pointer to an array of drm_asahi_sync. The first
  **in_sync_count** elements are in-syncs, then the remaining
  **out_sync_count** elements are out-syncs. Using a single array with
  explicit partitioning simplifies handling.
- `cmdbuf`: Pointer to the command buffer to submit.

  This is a flat command buffer. By design, it contains no CPU
  pointers, which makes it suitable for a virtgpu wire protocol without
  requiring any serializing/deserializing step.

  It consists of a series of commands. Each command begins with a
  fixed-size **drm_asahi_cmd_header** header and is followed by a
  variable-length payload according to the type and size in the header.

  The combined count of "real" hardware commands must be nonzero and at
  most drm_asahi_params_global::max_commands_per_submission.
- `flags`: Flags for command submission (MBZ)
- `queue_id`: The queue ID to be submitted to
- `in_sync_count`: Number of sync objects to wait on before starting
  this job.
- `out_sync_count`: Number of sync objects to signal upon completion of
  this job.
- `cmdbuf_size`: Command buffer size in bytes
- `pad`: MBZ

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

Describe an "attachment".

**Definition**

```c
struct drm_asahi_attachment {
    __u64 pointer;
    __u64 size;
    __u32 pad;
    __u32 flags;
};
```

**Members**

- `pointer`: Base address of the attachment
- `size`: Size of the attachment in bytes
- `pad`: MBZ
- `flags`: MBZ

**Description**

Attachments are any memory written by shaders, notably including render
target attachments written by the end-of-tile program. This is purely a hint
about the accessed memory regions. It is optional to specify, which is
fortunate as it cannot be specified precisely with bindless access anyway.
But where possible, it's probably a good idea for userspace to include these
hints, forwarded to the firmware.

This struct is implicitly sized and therefore is not extensible.

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

Describe a depth or stencil buffer.

**Definition**

```c
struct drm_asahi_zls_buffer {
    __u64 base;
    __u64 comp_base;
    __u32 stride;
    __u32 comp_stride;
};
```

**Members**

- `base`: Base address of the buffer
- `comp_base`: If the load buffer is compressed, address of the
  compression metadata section.
- `stride`: If layered rendering is enabled, the number of bytes
  between each layer of the buffer.
- `comp_stride`: If layered rendering is enabled, the number of bytes
  between each layer of the compression metadata.

**Description**

These fields correspond to hardware registers in the ZLS (Z Load/Store) unit.
There are three hardware registers for each field respectively for loads,
stores, and partial renders. In practice, it makes sense to set all to the
same values, except in exceptional cases not yet implemented in userspace, so
we do not duplicate here for simplicity/efficiency.

This struct is embedded in other structs and therefore is not extensible.

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

Describe a timestamp write.

**Definition**

```c
struct drm_asahi_timestamp {
    __u32 handle;
    __u32 offset;
};
```

**Members**

- `handle`: Handle of the timestamp buffer, or 0 to skip this
  timestamp. If nonzero, this must equal the value returned in
  drm_asahi_gem_bind_object::object_handle.
- `offset`: Offset to write into the timestamp buffer

**Description**

The firmware can optionally write the GPU timestamp at render pass
granularities, but it needs to be mapped specially via
DRM_IOCTL_ASAHI_GEM_BIND_OBJECT. This structure therefore describes where to
write as a handle-offset pair, rather than a GPU address like normal.

This struct is embedded in other structs and therefore is not extensible.

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

Describe timestamp writes.

**Definition**

```c
struct drm_asahi_timestamps {
    struct drm_asahi_timestamp start;
    struct drm_asahi_timestamp end;
};
```

**Members**

- `start`: Timestamp recorded at the start of the operation
- `end`: Timestamp recorded at the end of the operation

**Description**

Each operation that can be timestamped, can be timestamped at the start and
end. Therefore, drm_asahi_timestamp structs always come in pairs, bundled
together into drm_asahi_timestamps.

This struct is embedded in other structs and therefore is not extensible.

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

Describe helper program configuration.

**Definition**

```c
struct drm_asahi_helper_program {
    __u32 binary;
    __u32 cfg;
    __u64 data;
};
```

**Members**

- `binary`: USC address to the helper program binary. This is a tagged
  pointer with configuration in the bottom bits.
- `cfg`: Additional configuration bits for the helper program.
- `data`: Data passed to the helper program. This value is not
  interpreted by the kernel, firmware, or hardware in any way. It is
  simply a sideband for userspace, set with the submit ioctl and read
  via special registers inside the helper program.

  In practice, userspace will pass a 64-bit GPU VA here pointing to the
  actual arguments, which presumably don't fit in 64-bits.

**Description**

The helper program is a compute-like kernel required for various hardware
functionality. Its most important role is dynamically allocating
scratch/stack memory for individual subgroups, by partitioning a static
allocation shared for the whole device. It is supplied by userspace via
drm_asahi_helper_program and internally dispatched by the hardware as needed.

This struct is embedded in other structs and therefore is not extensible.

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

Describe a background or end-of-tile program.

**Definition**

```c
struct drm_asahi_bg_eot {
    __u32 usc;
    __u32 rsrc_spec;
};
```

**Members**

- `usc`: USC address of the hardware USC words binding resources
  (including images and uniforms) and the program itself. Note this is
  an additional layer of indirection compared to the helper program,
  avoiding the need for a sideband for data. This is a tagged pointer
  with additional configuration in the bottom bits.
- `rsrc_spec`: Resource specifier for the program. This is a packed
  hardware data structure describing the required number of registers,
  uniforms, bound textures, and bound samplers.

**Description**

The background and end-of-tile programs are dispatched by the hardware at the
beginning and end of rendering. As the hardware "tilebuffer" is simply local
memory, these programs are necessary to implement API-level render targets.
The fragment-like background program is responsible for loading either the
clear colour or the existing render target contents, while the compute-like
end-of-tile program stores the tilebuffer contents to memory.

This struct is embedded in other structs and therefore is not extensible.

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

Command to submit 3D

**Definition**

```c
struct drm_asahi_cmd_render {
    __u32 flags;
    __u32 isp_zls_pixels;
    __u64 vdm_ctrl_stream_base;
    struct drm_asahi_helper_program vertex_helper;
    struct drm_asahi_helper_program fragment_helper;
    __u64 isp_scissor_base;
    __u64 isp_dbias_base;
    __u64 isp_oclqry_base;
    struct drm_asahi_zls_buffer depth;
    struct drm_asahi_zls_buffer stencil;
    __u64 zls_ctrl;
    __u64 ppp_multisamplectl;
    __u64 sampler_heap;
    __u32 ppp_ctrl;
    __u16 width_px;
    __u16 height_px;
    __u16 layers;
    __u16 sampler_count;
    __u8 utile_width_px;
    __u8 utile_height_px;
    __u8 samples;
    __u8 sample_size_B;
    __u32 isp_merge_upper_x;
    __u32 isp_merge_upper_y;
    struct drm_asahi_bg_eot bg;
    struct drm_asahi_bg_eot eot;
    struct drm_asahi_bg_eot partial_bg;
    struct drm_asahi_bg_eot partial_eot;
    __u32 isp_bgobjdepth;
    __u32 isp_bgobjvals;
    struct drm_asahi_timestamps ts_vtx;
    struct drm_asahi_timestamps ts_frag;
};
```

**Members**

- `flags`: Combination of drm_asahi_render_flags flags.
- `isp_zls_pixels`: ISP_ZLS_PIXELS register value. This contains the
  depth/stencil width/height, which may differ from the framebuffer
  width/height.
- `vdm_ctrl_stream_base`: VDM_CTRL_STREAM_BASE register value. GPU
  address to the beginning of the VDM control stream.
- `vertex_helper`: Helper program used for the vertex shader
- `fragment_helper`: Helper program used for the fragment shader
- `isp_scissor_base`: ISP_SCISSOR_BASE register value. GPU address of an
  array of scissor descriptors indexed in the render pass.
- `isp_dbias_base`: ISP_DBIAS_BASE register value. GPU address of an
  array of depth bias values indexed in the render pass.
- `isp_oclqry_base`: ISP_OCLQRY_BASE register value. GPU address of an
  array of occlusion query results written by the render pass.
- `depth`: Depth buffer
- `stencil`: Stencil buffer
- `zls_ctrl`: ZLS_CTRL register value
- `ppp_multisamplectl`: PPP_MULTISAMPLECTL register value
- `sampler_heap`: Base address of the sampler heap. This heap is used
  for both vertex shaders and fragment shaders. The registers are
  per-stage, but there is no known use case for separate heaps.
- `ppp_ctrl`: PPP_CTRL register value
- `width_px`: Framebuffer width in pixels
- `height_px`: Framebuffer height in pixels
- `layers`: Number of layers in the framebuffer
- `sampler_count`: Number of samplers in the sampler heap.
- `utile_width_px`: Width of a logical tilebuffer tile in pixels
- `utile_height_px`: Height of a logical tilebuffer tile in pixels
- `samples`: \# of samples in the framebuffer. Must be 1, 2, or 4.
- `sample_size_B`: \# of bytes in the tilebuffer required per sample.
- `isp_merge_upper_x`: 32-bit float used in the hardware triangle
  merging. Calculate as: tan(60 deg) * width.

  Making these values UAPI avoids requiring floating-point calculations
  in the kernel in the hot path.
- `isp_merge_upper_y`: 32-bit float. Calculate as: tan(60 deg) * height.
  See **isp_merge_upper_x**.
- `bg`: Background program run for each tile at the start
- `eot`: End-of-tile program ran for each tile at the end
- `partial_bg`: Background program ran at the start of each tile when
  resuming the render pass during a partial render.
- `partial_eot`: End-of-tile program ran at the end of each tile when
  pausing the render pass during a partial render.
- `isp_bgobjdepth`: ISP_BGOBJDEPTH register value. This is the depth
  buffer clear value, encoded in the depth buffer's format: either a
  32-bit float or a 16-bit unorm (with upper bits zeroed).
- `isp_bgobjvals`: ISP_BGOBJVALS register value. The bottom 8-bits
  contain the stencil buffer clear value.
- `ts_vtx`: Timestamps for the vertex portion of the render
- `ts_frag`: Timestamps for the fragment portion of the render

**Description**

This command submits a single render pass. The hardware control stream may
include many draws and subpasses, but within the command, the framebuffer
dimensions and attachments are fixed.

The hardware requires the firmware to set a large number of Control Registers
setting up state at render pass granularity before each command rendering 3D.
The firmware bundles this state into data structures. Unfortunately, we
cannot expose either any of that directly to userspace, because the
kernel-firmware ABI is not stable. Although we can guarantee the firmware
updates in tandem with the kernel, we cannot break old userspace when
upgrading the firmware and kernel. Therefore, we need to abstract well the
data structures to avoid tying our hands with future firmwares.

The bulk of drm_asahi_cmd_render therefore consists of values of hardware
control registers, marshalled via the firmware interface.

The framebuffer/tilebuffer dimensions are also specified here. In addition to
being passed to the firmware/hardware, the kernel requires these dimensions
to calculate various essential tiling-related data structures. It is
unfortunate that our submits are heavier than on vendors with saner
hardware-software interfaces. The upshot is all of this information is
readily available to userspace with all current APIs.

It looks odd - but it's not overly burdensome and it ensures we can remain
compatible with old userspace.

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

Command to submit compute

**Definition**

```c
struct drm_asahi_cmd_compute {
    __u32 flags;
    __u32 sampler_count;
    __u64 cdm_ctrl_stream_base;
    __u64 cdm_ctrl_stream_end;
    __u64 sampler_heap;
    struct drm_asahi_helper_program helper;
    struct drm_asahi_timestamps ts;
};
```

**Members**

- `flags`: MBZ
- `sampler_count`: Number of samplers in the sampler heap.
- `cdm_ctrl_stream_base`: CDM_CTRL_STREAM_BASE register value. GPU
  address to the beginning of the CDM control stream.
- `cdm_ctrl_stream_end`: GPU base address to the end of the hardware
  control stream. Note this only considers the first contiguous segment
  of the control stream, as the stream might jump elsewhere.
- `sampler_heap`: Base address of the sampler heap.
- `helper`: Helper program used for this compute command
- `ts`: Timestamps for the compute command

**Description**

This command submits a control stream consisting of compute dispatches. There
is essentially no limit on how many compute dispatches may be included in a
single compute command, although timestamps are at command granularity.

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

Arguments passed to DRM_IOCTL_ASAHI_GET_TIME

**Definition**

```c
struct drm_asahi_get_time {
    __u64 flags;
    __u64 gpu_timestamp;
};
```

**Members**

- `flags`: MBZ.
- `gpu_timestamp`: On return, the GPU timestamp in nanoseconds.

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

```c
DRM_IOCTL_ASAHI(__access, __id, __type)
```

Build an Asahi IOCTL number

**Parameters**

- `__access`: Access type. Must be R, W or RW.
- `__id`: One of the DRM_ASAHI_xxx id.
- `__type`: Suffix of the type being passed to the IOCTL.

**Description**

Don't use this macro directly, use the DRM_IOCTL_ASAHI_xxx
values instead.

**Return**

An IOCTL number to be passed to `ioctl()` from userspace.

---

# GPU Driver Documentation

_Peios Kernel / Hardware and drivers / Graphics_

> Reference for GPU Driver Documentation.

<a id="rst-gpu-driver-documentation"></a>

- [drm/amdgpu AMDgpu driver](</kernel/hardware/gpu/amdgpu/index.md>)
- [drm/i915 Intel GFX Driver](</kernel/hardware/gpu/i915.md>)
- [drm/imagination PowerVR Graphics Driver](</kernel/hardware/gpu/imagination/index.md>)
- [drm/mcde ST-Ericsson MCDE Multi-channel display engine](</kernel/hardware/gpu/mcde.md>)
- [drm/meson AmLogic Meson Video Processing Unit](</kernel/hardware/gpu/meson.md>)
- [drm/nouveau NVIDIA GPU Driver](</kernel/hardware/gpu/nouveau.md>)
- [drm/pl111 ARM PrimeCell PL110 and PL111 CLCD Driver](</kernel/hardware/gpu/pl111.md>)
- [drm/tegra NVIDIA Tegra GPU and display driver](</kernel/hardware/gpu/tegra.md>)
- [drm/tve200 Faraday TV Encoder 200](</kernel/hardware/gpu/tve200.md>)
- [drm/v3d Broadcom V3D Graphics Driver](</kernel/hardware/gpu/v3d.md>)
- [drm/vc4 Broadcom VC4 Graphics Driver](</kernel/hardware/gpu/vc4.md>)
- [drm/vkms Virtual Kernel Modesetting](</kernel/hardware/gpu/vkms.md>)
- [drm/bridge/dw-hdmi Synopsys DesignWare HDMI Controller](</kernel/hardware/gpu/bridge/dw-hdmi.md>)
- [drm/xen-front Xen para-virtualized frontend driver](</kernel/hardware/gpu/xen-front.md>)
- [drm/xe Intel GFX Driver](</kernel/hardware/gpu/xe/index.md>)
- [Arm Framebuffer Compression (AFBC)](</kernel/hardware/gpu/afbc.md>)
- [drm/komeda Arm display driver](</kernel/hardware/gpu/komeda-kms.md>)
- [drm/Panfrost Mali Driver](</kernel/hardware/gpu/panfrost.md>)
- [drm/Panthor CSF driver](</kernel/hardware/gpu/panthor.md>)
- [Xilinx ZynqMP Ultrascale+ DisplayPort Subsystem](</kernel/hardware/gpu/zynqmp.md>)
- [nova NVIDIA GPU drivers](</kernel/hardware/gpu/nova/index.md>)

---

# Kernel clients

_Peios Kernel / Hardware and drivers / Graphics_

> Reference for Kernel clients.

<a id="rst-kernel-clients"></a>


This library provides support for clients running in the kernel like fbdev and bootsplash.

GEM drivers which provide a GEM based dumb buffer with a virtual address are supported.



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

DRM client callbacks

**Definition**

```c
struct drm_client_funcs {
    struct module *owner;
    void (*free)(struct drm_client_dev *client);
    void (*unregister)(struct drm_client_dev *client);
    int (*restore)(struct drm_client_dev *client, bool force);
    int (*hotplug)(struct drm_client_dev *client);
    int (*suspend)(struct drm_client_dev *client);
    int (*resume)(struct drm_client_dev *client);
};
```

**Members**

- `owner`: The module owner
- `free`: Called when the client gets unregistered. Implementations should
  release all client-specific data and free the memory.

  This callback is optional.
- `unregister`: Called when [`drm_device`](/kernel/hardware/gpu/drm-internals.md#c-struct-drm_device) is unregistered. The client should respond by
  releasing its resources using [`drm_client_release()`](#c-drm_client_release).

  This callback is optional.
- `restore`: Called on `drm_lastclose()`. The first client instance in the list that
  returns zero gets the privilege to restore and no more clients are
  called. This callback is not called after **unregister** has been called.

  Note that the core does not guarantee exclusion against concurrent
  [`drm_open()`](/kernel/hardware/gpu/drm-internals.md#c-drm_open). Clients need to ensure this themselves, for example by
  using `drm_master_internal_acquire()` and `drm_master_internal_release()`.

  If the caller passes force, the client should ignore any present DRM
  master and restore the display anyway.

  This callback is optional.
- `hotplug`: Called on [`drm_kms_helper_hotplug_event()`](/kernel/hardware/gpu/drm-kms-helpers.md#c-drm_kms_helper_hotplug_event).
  This callback is not called after **unregister** has been called.

  This callback is optional.
- `suspend`: Called when suspending the device.

  This callback is optional.
- `resume`: Called when resuming the device from suspend.

  This callback is optional.

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

DRM client instance

**Definition**

```c
struct drm_client_dev {
    struct drm_device *dev;
    const char *name;
    struct list_head list;
    const struct drm_client_funcs *funcs;
    struct drm_file *file;
    struct mutex modeset_mutex;
    struct drm_mode_set *modesets;
    bool suspended;
    bool hotplug_pending;
    bool hotplug_failed;
};
```

**Members**

- `dev`: DRM device
- `name`: Name of the client.
- `list`: List of all clients of a DRM device, linked into
  [`drm_device.clientlist`](/kernel/hardware/gpu/drm-internals.md#c-struct-drm_device). Protected by [`drm_device.clientlist_mutex`](/kernel/hardware/gpu/drm-internals.md#c-struct-drm_device).
- `funcs`: DRM client functions (optional)
- `file`: DRM file
- `modeset_mutex`: Protects **modesets**.
- `modesets`: CRTC configurations
- `suspended`: The client has been suspended.
- `hotplug_pending`: A hotplug event has been received while the client was suspended.
  Try again on resume.
- `hotplug_failed`: Set by client hotplug helpers if the hotplugging failed
  before. It is usually not tried again.

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

DRM client buffer

**Definition**

```c
struct drm_client_buffer {
    struct drm_client_dev *client;
    struct drm_gem_object *gem;
    struct iosys_map map;
    struct drm_framebuffer *fb;
};
```

**Members**

- `client`: DRM client
- `gem`: GEM object backing this buffer

  FIXME: The DRM framebuffer holds a reference on its GEM
  buffer objects. Do not use this field in new code and
  update existing users.
- `map`: Virtual address for the buffer
- `fb`: DRM framebuffer

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

```c
drm_client_for_each_modeset(modeset, client)
```

Iterate over client modesets

**Parameters**

- `modeset`: [`drm_mode_set`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_mode_set) loop cursor
- `client`: DRM client

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

```c
drm_client_for_each_connector_iter(connector, iter)
```

connector_list iterator macro

**Parameters**

- `connector`: [`struct drm_connector`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_connector) pointer used as cursor
- `iter`: [`struct drm_connector_list_iter`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_connector_list_iter)

**Description**

This iterates the connectors that are useable for internal clients (excludes
writeback connectors).

For more info see [`drm_for_each_connector_iter()`](/kernel/hardware/gpu/drm-kms.md#c-drm_for_each_connector_iter).



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

```c
int drm_client_init(struct drm_device *dev, struct drm_client_dev *client, const char *name, const struct drm_client_funcs *funcs)
```

Initialise a DRM client

**Parameters**

- `struct drm_device *dev`: DRM device
- `struct drm_client_dev *client`: DRM client
- `const char *name`: Client name
- `const struct drm_client_funcs *funcs`: DRM client functions (optional)

**Description**

This initialises the client and opens a [`drm_file`](/kernel/hardware/gpu/drm-internals.md#c-struct-drm_file).
Use [`drm_client_register()`](#c-drm_client_register) to complete the process.
The caller needs to hold a reference on **dev** before calling this function.
The client is freed when the [`drm_device`](/kernel/hardware/gpu/drm-internals.md#c-struct-drm_device) is unregistered. See [`drm_client_release()`](#c-drm_client_release).

**Return**

Zero on success or negative error code on failure.

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

```c
void drm_client_register(struct drm_client_dev *client)
```

Register client

**Parameters**

- `struct drm_client_dev *client`: DRM client

**Description**

Add the client to the [`drm_device`](/kernel/hardware/gpu/drm-internals.md#c-struct-drm_device) client list to activate its callbacks.
**client** must be initialized by a call to [`drm_client_init()`](#c-drm_client_init). After
[`drm_client_register()`](#c-drm_client_register) it is no longer permissible to call [`drm_client_release()`](#c-drm_client_release)
directly (outside the unregister callback), instead cleanup will happen
automatically on driver unload.

Registering a client generates a hotplug event that allows the client
to set up its display from pre-existing outputs. The client must have
initialized its state to able to handle the hotplug event successfully.

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

```c
void drm_client_release(struct drm_client_dev *client)
```

Release DRM client resources

**Parameters**

- `struct drm_client_dev *client`: DRM client

**Description**

Releases resources by closing the [`drm_file`](/kernel/hardware/gpu/drm-internals.md#c-struct-drm_file) that was opened by [`drm_client_init()`](#c-drm_client_init).
It is called automatically if the [`drm_client_funcs.unregister`](#c-struct-drm_client_funcs) callback is _not_ set.

This function should only be called from the unregister callback. An exception
is fbdev which cannot free the buffer if userspace has open file descriptors.

**Note**

Clients cannot initiate a release by themselves. This is done to keep the code simple.
The driver has to be unloaded before the client can be unloaded.

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

```c
void drm_client_buffer_delete(struct drm_client_buffer *buffer)
```

Delete a client buffer

**Parameters**

- `struct drm_client_buffer *buffer`: DRM client buffer

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

```c
int drm_client_buffer_vmap_local(struct drm_client_buffer *buffer, struct iosys_map *map_copy)
```

Map DRM client buffer into address space

**Parameters**

- `struct drm_client_buffer *buffer`: DRM client buffer
- `struct iosys_map *map_copy`: Returns the mapped memory's address

**Description**

This function maps a client buffer into kernel address space. If the
buffer is already mapped, it returns the existing mapping's address.

Client buffer mappings are not ref'counted. Each call to
[`drm_client_buffer_vmap_local()`](#c-drm_client_buffer_vmap_local) should be closely followed by a call to
[`drm_client_buffer_vunmap_local()`](#c-drm_client_buffer_vunmap_local). See [`drm_client_buffer_vmap()`](#c-drm_client_buffer_vmap) for
long-term mappings.

The returned address is a copy of the internal value. In contrast to
other vmap interfaces, you don't need it for the client's vunmap
function. So you can modify it at will during blit and draw operations.

**Return**

0 on success, or a negative errno code otherwise.

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

```c
void drm_client_buffer_vunmap_local(struct drm_client_buffer *buffer)
```

Unmap DRM client buffer

**Parameters**

- `struct drm_client_buffer *buffer`: DRM client buffer

**Description**

This function removes a client buffer's memory mapping established
with [`drm_client_buffer_vunmap_local()`](#c-drm_client_buffer_vunmap_local). Calling this function is only
required by clients that manage their buffer mappings by themselves.

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

```c
int drm_client_buffer_vmap(struct drm_client_buffer *buffer, struct iosys_map *map_copy)
```

Map DRM client buffer into address space

**Parameters**

- `struct drm_client_buffer *buffer`: DRM client buffer
- `struct iosys_map *map_copy`: Returns the mapped memory's address

**Description**

This function maps a client buffer into kernel address space. If the
buffer is already mapped, it returns the existing mapping's address.

Client buffer mappings are not ref'counted. Each call to
[`drm_client_buffer_vmap()`](#c-drm_client_buffer_vmap) should be followed by a call to
[`drm_client_buffer_vunmap()`](#c-drm_client_buffer_vunmap); or the client buffer should be mapped
throughout its lifetime.

The returned address is a copy of the internal value. In contrast to
other vmap interfaces, you don't need it for the client's vunmap
function. So you can modify it at will during blit and draw operations.

**Return**

0 on success, or a negative errno code otherwise.

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

```c
void drm_client_buffer_vunmap(struct drm_client_buffer *buffer)
```

Unmap DRM client buffer

**Parameters**

- `struct drm_client_buffer *buffer`: DRM client buffer

**Description**

This function removes a client buffer's memory mapping. Calling this
function is only required by clients that manage their buffer mappings
by themselves.

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

```c
struct drm_client_buffer * drm_client_buffer_create_dumb(struct drm_client_dev *client, u32 width, u32 height, u32 format)
```

Create a client buffer backed by a dumb buffer

**Parameters**

- `struct drm_client_dev *client`: DRM client
- `u32 width`: Framebuffer width
- `u32 height`: Framebuffer height
- `u32 format`: Buffer format

**Description**

This function creates a [`drm_client_buffer`](#c-struct-drm_client_buffer) which consists of a
[`drm_framebuffer`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_framebuffer) backed by a dumb buffer.
Call [`drm_client_buffer_delete()`](#c-drm_client_buffer_delete) to free the buffer.

**Return**

Pointer to a client buffer or an error pointer on failure.

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

```c
int drm_client_buffer_flush(struct drm_client_buffer *buffer, struct drm_rect *rect)
```

Manually flush client buffer

**Parameters**

- `struct drm_client_buffer *buffer`: DRM client buffer
- `struct drm_rect *rect`: Damage rectangle (if NULL flushes all)

**Description**

This calls [`drm_framebuffer_funcs->dirty`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_framebuffer_funcs) (if present) to flush buffer changes
for drivers that need it.

**Return**

Zero on success or negative error code on failure.



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

```c
int drm_client_modeset_probe(struct drm_client_dev *client, unsigned int width, unsigned int height)
```

Probe for displays

**Parameters**

- `struct drm_client_dev *client`: DRM client
- `unsigned int width`: Maximum display mode width (optional)
- `unsigned int height`: Maximum display mode height (optional)

**Description**

This function sets up display pipelines for enabled connectors and stores the
config in the client's modeset array.

**Return**

Zero on success or negative error code on failure.

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

```c
bool drm_client_rotation(struct drm_mode_set *modeset, unsigned int *rotation)
```

Check the initial rotation value

**Parameters**

- `struct drm_mode_set *modeset`: DRM modeset
- `unsigned int *rotation`: Returned rotation value

**Description**

This function checks if the primary plane in **modeset** can hw rotate
to match the rotation needed on its connector.

**Note**

Currently only 0 and 180 degrees are supported.

**Return**

True if the plane can do the rotation, false otherwise.

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

```c
int drm_client_modeset_check(struct drm_client_dev *client)
```

Check modeset configuration

**Parameters**

- `struct drm_client_dev *client`: DRM client

**Description**

Check modeset configuration.

**Return**

Zero on success or negative error code on failure.

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

```c
int drm_client_modeset_commit_locked(struct drm_client_dev *client)
```

Force commit CRTC configuration

**Parameters**

- `struct drm_client_dev *client`: DRM client

**Description**

Commit modeset configuration to crtcs without checking if there is a DRM
master. The assumption is that the caller already holds an internal DRM
master reference acquired with `drm_master_internal_acquire()`.

**Return**

Zero on success or negative error code on failure.

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

```c
int drm_client_modeset_commit(struct drm_client_dev *client)
```

Commit CRTC configuration

**Parameters**

- `struct drm_client_dev *client`: DRM client

**Description**

Commit modeset configuration to crtcs.

**Return**

Zero on success or negative error code on failure.

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

```c
int drm_client_modeset_dpms(struct drm_client_dev *client, int mode)
```

Set DPMS mode

**Parameters**

- `struct drm_client_dev *client`: DRM client
- `int mode`: DPMS mode

**Note**

For atomic drivers **mode** is reduced to on/off.

**Return**

Zero on success or negative error code on failure.

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

```c
int drm_client_modeset_wait_for_vblank(struct drm_client_dev *client, unsigned int crtc_index)
```

Wait for the next VBLANK to occur

**Parameters**

- `struct drm_client_dev *client`: DRM client
- `unsigned int crtc_index`: The ndex of the CRTC to wait on

**Description**

Block the caller until the given CRTC has seen a VBLANK. Do nothing
if the CRTC is disabled. If there's another DRM master present, fail
with -EBUSY.

**Return**

0 on success, or negative error code otherwise.



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

```c
void drm_client_dev_unregister(struct drm_device *dev)
```

Unregister clients

**Parameters**

- `struct drm_device *dev`: DRM device

**Description**

This function releases all clients by calling each client's
[`drm_client_funcs.unregister`](#c-struct-drm_client_funcs) callback. The callback function
is responsibe for releaseing all resources including the client
itself.

The helper [`drm_dev_unregister()`](/kernel/hardware/gpu/drm-internals.md#c-drm_dev_unregister) calls this function. Drivers
that use it don't need to call this function themselves.

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

```c
void drm_client_dev_hotplug(struct drm_device *dev)
```

Send hotplug event to clients

**Parameters**

- `struct drm_device *dev`: DRM device

**Description**

This function calls the [`drm_client_funcs.hotplug`](#c-struct-drm_client_funcs) callback on the attached clients.

[`drm_kms_helper_hotplug_event()`](/kernel/hardware/gpu/drm-kms-helpers.md#c-drm_kms_helper_hotplug_event) calls this function, so drivers that use it
don't need to call this function themselves.

---

# Long running workloads and compute

_Peios Kernel / Hardware and drivers / Graphics_

> Long running workloads (compute) are workloads that will not complete in 10 seconds. (The time let the user wait before he reaches for the power button). This means that other techniques need to be used to manage those workloads, that…

<a id="rst-long-running-workloads-and-compute"></a>

Long running workloads (compute) are workloads that will not complete in 10 seconds. (The time let the user wait before he reaches for the power button). This means that other techniques need to be used to manage those workloads, that cannot use fences.

Some hardware may schedule compute jobs, and have no way to pre-empt them, or have their memory swapped out from them. Or they simply want their workload not to be preempted or swapped out at all.

This means that it differs from what is described in driver-api/dma-buf.rst.

As with normal compute jobs, dma-fence may not be used at all. In this case, not even to force preemption. The driver with is simply forced to unmap a BO from the long compute job's address space on unbind immediately, not even waiting for the workload to complete. Effectively this terminates the workload when there is no hardware support to recover.

Since this is undesirable, there need to be mitigations to prevent a workload from being terminated. There are several possible approach, all with their advantages and drawbacks.

The first approach you will likely try is to pin all buffers used by compute. This guarantees that the job will run uninterrupted, but also allows a very denial of service attack by pinning as much memory as possible, hogging the all GPU memory, and possibly a huge chunk of CPU memory.

A second approach that will work slightly better on its own is adding an option not to evict when creating a new job (any kind). If all of userspace opts in to this flag, it would prevent cooperating userspace from forced terminating older compute jobs to start a new one.

If job preemption and recoverable pagefaults are not available, those are the only approaches possible. So even with those, you want a separate way of controlling resources. The standard kernel way of doing so is cgroups.

This creates a third option, using cgroups to prevent eviction. Both GPU and driver-allocated CPU memory would be accounted to the correct cgroup, and eviction would be made cgroup aware. This allows the GPU to be partitioned into cgroups, that will allow jobs to run next to each other without interference.

The interface to the cgroup would be similar to the current CPU memory interface, with similar semantics for min/low/high/max, if eviction can be made cgroup aware.

What should be noted is that each memory region (tiled memory for example) should have its own accounting.

The key is set to the regionid set by the driver, for example "tile0". For the value of $card, we use drmGetUnique().

---

# DRM Internals

_Peios Kernel / Hardware and drivers / Graphics_

> This chapter documents DRM internals relevant to driver authors and developers working to add support for the latest features to existing drivers.

<a id="rst-drm-internals"></a>

This chapter documents DRM internals relevant to driver authors and developers working to add support for the latest features to existing drivers.

First, we go over some typical driver initialization requirements, like setting up command buffers, creating an initial output configuration, and initializing core services. Subsequent sections cover core internals in more detail, providing implementation notes and examples.

The DRM layer provides several services to graphics drivers, many of them driven by the application interfaces it provides through libdrm, the library that wraps most of the DRM ioctls. These include vblank event handling, memory management, output management, framebuffer management, command submission &amp; fencing, suspend/resume support, and DMA services.

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

## Driver Initialization

At the core of every DRM driver is a `struct drm_driver <drm_driver>` structure. Drivers typically statically initialize a drm_driver structure, and then pass it to drm_dev_alloc() to allocate a device instance. After the device instance is fully initialized it can be registered (which makes it accessible from userspace) using drm_dev_register().

The `struct drm_driver <drm_driver>` structure contains static information that describes the driver and features it supports, and pointers to methods that the DRM core will call to implement the DRM API. We will first go through the `struct drm_driver <drm_driver>` static information fields, and will then describe individual operations in details as they get used in later sections.

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

### Driver Information

<a id="rst-major-minor-and-patchlevel"></a>

#### Major, Minor and Patchlevel

int major; int minor; int patchlevel; The DRM core identifies driver versions by a major, minor and patch level triplet. The information is printed to the kernel log at initialization time and passed to userspace through the DRM_IOCTL_VERSION ioctl.

The major and minor numbers are also used to verify the requested driver API version passed to DRM_IOCTL_SET_VERSION. When the driver API changes between minor versions, applications can call DRM_IOCTL_SET_VERSION to select a specific version of the API. If the requested major isn't equal to the driver major, or the requested minor is larger than the driver minor, the DRM_IOCTL_SET_VERSION call will return an error. Otherwise the driver's set_version() method will be called with the requested version.

<a id="rst-name-and-description"></a>

#### Name and Description

char \*name; char \*desc; char \*date; The driver name is printed to the kernel log at initialization time, used for IRQ registration and passed to userspace through DRM_IOCTL_VERSION.

The driver description is a purely informative string passed to userspace through the DRM_IOCTL_VERSION ioctl and otherwise unused by the kernel.

<a id="rst-module-initialization"></a>

### Module Initialization


This library provides helpers registering DRM drivers during module
initialization and shutdown. The provided helpers act like bus-specific
module helpers, such as `module_pci_driver()`, but respect additional
parameters that control DRM driver registration.

Below is an example of initializing a DRM driver for a device on the
PCI bus.

```c
struct pci_driver my_pci_drv = {
};

drm_module_pci_driver(my_pci_drv);
```

The generated code will test if DRM drivers are enabled and register
the PCI driver my_pci_drv. For more complex module initialization, you
can still use [`module_init()`](/kernel/hardware/driver-api/fundamentals/basics.md#c-module_init) and [`module_exit()`](/kernel/hardware/driver-api/fundamentals/basics.md#c-module_exit) in your driver.


<a id="rst-device-instance-and-driver-handling"></a>

### Device Instance and Driver Handling


A device instance for a drm driver is represented by [`struct drm_device`](#c-struct-drm_device). This
is allocated and initialized with [`devm_drm_dev_alloc()`](#c-devm_drm_dev_alloc), usually from
bus-specific ->`probe()` callbacks implemented by the driver. The driver then
needs to initialize all the various subsystems for the drm device like memory
management, vblank handling, modesetting support and initial output
configuration plus obviously initialize all the corresponding hardware bits.
Finally when everything is up and running and ready for userspace the device
instance can be published using [`drm_dev_register()`](#c-drm_dev_register).

There is also deprecated support for initializing device instances using
bus-specific helpers and the [`drm_driver.load`](#c-struct-drm_driver) callback. But due to
backwards-compatibility needs the device instance have to be published too
early, which requires unpretty global locking to make safe and is therefore
only support for existing drivers not yet converted to the new scheme.

When cleaning up a device instance everything needs to be done in reverse:
First unpublish the device instance with [`drm_dev_unregister()`](#c-drm_dev_unregister). Then clean up
any other resources allocated at device initialization and drop the driver's
reference to [`drm_device`](#c-struct-drm_device) using [`drm_dev_put()`](#c-drm_dev_put).

Note that any allocation or resource which is visible to userspace must be
released only when the final [`drm_dev_put()`](#c-drm_dev_put) is called, and not when the
driver is unbound from the underlying physical struct [`device`](/kernel/hardware/driver-api/fundamentals/infrastructure.md#c-struct-device). Best to use
[`drm_device`](#c-struct-drm_device) managed resources with [`drmm_add_action()`](#c-drmm_add_action), [`drmm_kmalloc()`](#c-drmm_kmalloc) and
related functions.

devres managed resources like [`devm_kmalloc()`](/kernel/hardware/driver-api/fundamentals/basics.md#c-devm_kmalloc) can only be used for resources
directly related to the underlying hardware device, and only used in code
paths fully protected by [`drm_dev_enter()`](#c-drm_dev_enter) and [`drm_dev_exit()`](#c-drm_dev_exit).

**Display driver example**

The following example shows a typical structure of a DRM display driver.
The example focus on the `probe()` function and the other functions that is
almost always present and serves as a demonstration of [`devm_drm_dev_alloc()`](#c-devm_drm_dev_alloc).

```c
struct driver_device {
        struct drm_device drm;
        void *userspace_facing;
        struct clk *pclk;
};

static const struct drm_driver driver_drm_driver = {
        [...]
};

static int driver_probe(struct platform_device *pdev)
{
        struct driver_device *priv;
        struct drm_device *drm;
        int ret;

        priv = devm_drm_dev_alloc(&pdev->dev, &driver_drm_driver,
                                  struct driver_device, drm);
        if (IS_ERR(priv))
                return PTR_ERR(priv);
        drm = &priv->drm;

        ret = drmm_mode_config_init(drm);
        if (ret)
                return ret;

        priv->userspace_facing = drmm_kzalloc(..., GFP_KERNEL);
        if (!priv->userspace_facing)
                return -ENOMEM;

        priv->pclk = devm_clk_get(dev, "PCLK");
        if (IS_ERR(priv->pclk))
                return PTR_ERR(priv->pclk);

        // Further setup, display pipeline etc

        platform_set_drvdata(pdev, drm);

        drm_mode_config_reset(drm);

        ret = drm_dev_register(drm);
        if (ret)
                return ret;

        drm_fbdev_{...}_setup(drm, 32);

        return 0;
}

// This function is called before the devm_ resources are released
static int driver_remove(struct platform_device *pdev)
{
        struct drm_device *drm = platform_get_drvdata(pdev);

        drm_dev_unregister(drm);
        drm_atomic_helper_shutdown(drm)

        return 0;
}

// This function is called on kernel restart and shutdown
static void driver_shutdown(struct platform_device *pdev)
{
        drm_atomic_helper_shutdown(platform_get_drvdata(pdev));
}

static int __maybe_unused driver_pm_suspend(struct device *dev)
{
        return drm_mode_config_helper_suspend(dev_get_drvdata(dev));
}

static int __maybe_unused driver_pm_resume(struct device *dev)
{
        drm_mode_config_helper_resume(dev_get_drvdata(dev));

        return 0;
}

static const struct dev_pm_ops driver_pm_ops = {
        SET_SYSTEM_SLEEP_PM_OPS(driver_pm_suspend, driver_pm_resume)
};

static struct platform_driver driver_driver = {
        .driver = {
                [...]
                .pm = &driver_pm_ops,
        },
        .probe = driver_probe,
        .remove = driver_remove,
        .shutdown = driver_shutdown,
};
module_platform_driver(driver_driver);
```

Drivers that want to support device unplugging (USB, DT overlay unload) should
use [`drm_dev_unplug()`](#c-drm_dev_unplug) instead of [`drm_dev_unregister()`](#c-drm_dev_unregister). The driver must protect
regions that is accessing device resources to prevent use after they're
released. This is done using [`drm_dev_enter()`](#c-drm_dev_enter) and [`drm_dev_exit()`](#c-drm_dev_exit). There is one
shortcoming however, [`drm_dev_unplug()`](#c-drm_dev_unplug) marks the drm_device as unplugged before
[`drm_atomic_helper_shutdown()`](/kernel/hardware/gpu/drm-kms-helpers.md#c-drm_atomic_helper_shutdown) is called. This means that if the disable code
paths are protected, they will not run on regular driver module unload,
possibly leaving the hardware enabled.



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

information about the guilty task of a wedge dev

**Definition**

```c
struct drm_wedge_task_info {
    pid_t pid;
    char comm[TASK_COMM_LEN];
};
```

**Members**

- `pid`: pid of the task
- `comm`: command name of the task

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

power state of drm device

**Constants**

- `DRM_SWITCH_POWER_ON`: Power state is ON
- `DRM_SWITCH_POWER_OFF`: Power state is OFF
- `DRM_SWITCH_POWER_CHANGING`: Power state is changing
- `DRM_SWITCH_POWER_DYNAMIC_OFF`: Suspended

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

DRM device structure

**Definition**

```c
struct drm_device {
        int if_version;
        struct kref ref;
        struct device *dev;
        struct device *dma_dev;
        struct {
            struct list_head resources;
            void *final_kfree;
            spinlock_t lock;
        } managed;
        const struct drm_driver *driver;
        void *dev_private;
        struct drm_minor *primary;
        struct drm_minor *render;
        struct drm_minor *accel;
        bool registered;
        struct drm_master *master;
    #ifdef CONFIG_TRANSPARENT_HUGEPAGE;
        struct vfsmount *huge_mnt;
    #endif;
        u32 driver_features;
        bool unplugged;
        struct inode *anon_inode;
        char *unique;
        struct mutex master_mutex;
        atomic_t open_count;
        struct mutex filelist_mutex;
        struct list_head filelist;
        struct list_head filelist_internal;
        struct mutex clientlist_mutex;
        struct list_head clientlist;
        struct list_head client_sysrq_list;
        bool vblank_disable_immediate;
        struct drm_vblank_crtc *vblank;
        spinlock_t vblank_time_lock;
        spinlock_t vbl_lock;
        u32 max_vblank_count;
        struct list_head vblank_event_list;
        spinlock_t event_lock;
        unsigned int num_crtcs;
        struct drm_mode_config mode_config;
        struct mutex object_name_lock;
        struct idr object_name_idr;
        struct drm_vma_offset_manager *vma_offset_manager;
        struct drm_vram_mm *vram_mm;
        enum switch_power_state switch_power_state;
        struct drm_fb_helper *fb_helper;
        struct dentry *debugfs_root;
};
```

**Members**

- `if_version`: Highest interface version set
- `ref`: Object ref-count
- `dev`: Device structure of bus-device
- `dma_dev`: Device for DMA operations. Only required if the device **dev**
  cannot perform DMA by itself. Should be NULL otherwise. Call
  [`drm_dev_dma_dev()`](#c-drm_dev_dma_dev) to get the DMA device instead of using this
  field directly. Call [`drm_dev_set_dma_dev()`](#c-drm_dev_set_dma_dev) to set this field.

  DRM devices are sometimes bound to virtual devices that cannot
  perform DMA by themselves. Drivers should set this field to the
  respective DMA controller.

  Devices on USB and other peripheral busses also cannot perform
  DMA by themselves. The **dma_dev** field should point the bus
  controller that does DMA on behalve of such a device. Required
  for importing buffers via dma-buf.

  If set, the DRM core automatically releases the reference on the
  device.
- `managed`: Managed resources linked to the lifetime of this [`drm_device`](#c-struct-drm_device) as
  tracked by **ref**.
- `managed.resources`: managed resources list
- `managed.final_kfree`: pointer for final [`kfree()`](/kernel/internals/core-api/mm-api.md#c-kfree) call
- `managed.lock`: protects **managed.resources**
- `driver`: DRM driver managing the device
- `dev_private`: DRM driver private data. This is deprecated and should be left set to
  NULL.

  Instead of using this pointer it is recommended that drivers use
  [`devm_drm_dev_alloc()`](#c-devm_drm_dev_alloc) and embed struct [`drm_device`](#c-struct-drm_device) in their larger
  per-device structure.
- `primary`: Primary node. Drivers should not interact with this
  directly. debugfs interfaces can be registered with
  [`drm_debugfs_add_file()`](/kernel/hardware/gpu/drm-uapi.md#c-drm_debugfs_add_file), and sysfs should be directly added on the
  hardware (and not character device node) struct device **dev**.
- `render`: Render node. Drivers should not interact with this directly ever.
  Drivers should not expose any additional interfaces in debugfs or
  sysfs on this node.
- `accel`: Compute Acceleration node
- `registered`: Internally used by [`drm_dev_register()`](#c-drm_dev_register) and [`drm_connector_register()`](/kernel/hardware/gpu/drm-kms.md#c-drm_connector_register).
- `master`: Currently active master for this device.
  Protected by `master_mutex`
- `huge_mnt`: Huge tmpfs mountpoint used at GEM object initialization
  [`drm_gem_object_init()`](/kernel/hardware/gpu/drm-mm.md#c-drm_gem_object_init). Drivers can call [`drm_gem_huge_mnt_create()`](/kernel/hardware/gpu/drm-mm.md#c-drm_gem_huge_mnt_create) to
  create, mount and use it. The default tmpfs mountpoint (`shm_mnt`) is
  used if NULL.
- `driver_features`: per-device driver features

  Drivers can clear specific flags here to disallow
  certain features on a per-device basis while still
  sharing a single [`struct drm_driver`](#c-struct-drm_driver) instance across
  all devices.
- `unplugged`: Flag to tell if the device has been unplugged.
  See [`drm_dev_enter()`](#c-drm_dev_enter) and [`drm_dev_is_unplugged()`](#c-drm_dev_is_unplugged).
- `anon_inode`: inode for private address-space
- `unique`: Unique name of the device
- `master_mutex`: Lock for [`drm_minor.master`](#c-struct-drm_minor) and [`drm_file.is_master`](#c-struct-drm_file)
- `open_count`: Usage counter for outstanding files open,
  protected by drm_global_mutex
- `filelist_mutex`: Protects **filelist**.
- `filelist`: List of userspace clients, linked through [`drm_file.lhead`](#c-struct-drm_file).
- `filelist_internal`: List of open DRM files for in-kernel clients.
  Protected by `filelist_mutex`.
- `clientlist_mutex`: Protects `clientlist` access.
- `clientlist`: List of in-kernel clients. Protected by `clientlist_mutex`.
- `client_sysrq_list`: Entry into list of devices registered for sysrq. Allows in-kernel
  clients on this device to handle sysrq keys.
- `vblank_disable_immediate`: If true, vblank interrupt will be disabled immediately when the
  refcount drops to zero, as opposed to via the vblank disable
  timer.

  This can be set to true it the hardware has a working vblank counter
  with high-precision timestamping (otherwise there are races) and the
  driver uses [`drm_crtc_vblank_on()`](/kernel/hardware/gpu/drm-kms.md#c-drm_crtc_vblank_on) and [`drm_crtc_vblank_off()`](/kernel/hardware/gpu/drm-kms.md#c-drm_crtc_vblank_off)
  appropriately. Also, see **max_vblank_count**,
  [`drm_crtc_funcs.get_vblank_counter`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_crtc_funcs) and
  [`drm_vblank_crtc_config.disable_immediate`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_vblank_crtc_config).
- `vblank`: Array of vblank tracking structures, one per [`struct drm_crtc`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_crtc). For
  historical reasons (vblank support predates kernel modesetting) this
  is free-standing and not part of [`struct drm_crtc`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_crtc) itself. It must be
  initialized explicitly by calling [`drm_vblank_init()`](/kernel/hardware/gpu/drm-kms.md#c-drm_vblank_init).
- `vblank_time_lock`: Protects vblank count and time updates during vblank enable/disable
- `vbl_lock`: Top-level vblank references lock, wraps the low-level
  **vblank_time_lock**.
- `max_vblank_count`: Maximum value of the vblank registers. This value +1 will result in a
  wrap-around of the vblank register. It is used by the vblank core to
  handle wrap-arounds.

  If set to zero the vblank core will try to guess the elapsed vblanks
  between times when the vblank interrupt is disabled through
  high-precision timestamps. That approach is suffering from small
  races and imprecision over longer time periods, hence exposing a
  hardware vblank counter is always recommended.

  This is the statically configured device wide maximum. The driver
  can instead choose to use a runtime configurable per-crtc value
  [`drm_vblank_crtc.max_vblank_count`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_vblank_crtc), in which case **max_vblank_count**
  must be left at zero. See [`drm_crtc_set_max_vblank_count()`](/kernel/hardware/gpu/drm-kms.md#c-drm_crtc_set_max_vblank_count) on how
  to use the per-crtc value.

  If non-zero, [`drm_crtc_funcs.get_vblank_counter`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_crtc_funcs) must be set.
- `vblank_event_list`: List of vblank events
- `event_lock`: Protects **vblank_event_list** and event delivery in
  general. See [`drm_send_event()`](#c-drm_send_event) and [`drm_send_event_locked()`](#c-drm_send_event_locked).
- `num_crtcs`: Number of CRTCs on this device
- `mode_config`: Current mode config
- `object_name_lock`: GEM information
- `object_name_idr`: GEM information
- `vma_offset_manager`: GEM information
- `vram_mm`: VRAM MM memory manager
- `switch_power_state`: Power state of the client.
  Used by drivers supporting the switcheroo driver.
  The state is maintained in the
  [`vga_switcheroo_client_ops.set_gpu_state`](/kernel/hardware/gpu/vga-switcheroo.md#c-struct-vga_switcheroo_client_ops) callback
- `fb_helper`: Pointer to the fbdev emulation structure.
  Set by [`drm_fb_helper_init()`](/kernel/hardware/gpu/drm-kms-helpers.md#c-drm_fb_helper_init) and cleared by [`drm_fb_helper_fini()`](/kernel/hardware/gpu/drm-kms-helpers.md#c-drm_fb_helper_fini).
- `debugfs_root`: Root directory for debugfs files.

**Description**

This structure represent a complete card that
may contain multiple heads.

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

```c
struct device * drm_dev_dma_dev(struct drm_device *dev)
```

returns the DMA device for a DRM device

**Parameters**

- `struct drm_device *dev`: DRM device

**Description**

Returns the DMA device of the given DRM device. By default, this
the DRM device's parent. See [`drm_dev_set_dma_dev()`](#c-drm_dev_set_dma_dev).

**Return**

A DMA-capable device for the DRM device.



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

feature flags

**Constants**

- `DRIVER_GEM`: Driver use the GEM memory manager. This should be set for all modern
  drivers.
- `DRIVER_MODESET`: Driver supports mode setting interfaces (KMS).
- `DRIVER_RENDER`: Driver supports dedicated render nodes. See also the section on
  render nodes for details.
- `DRIVER_ATOMIC`: Driver supports the full atomic modesetting userspace API. Drivers
  which only use atomic internally, but do not support the full
  userspace API (e.g. not all properties converted to atomic, or
  multi-plane updates are not guaranteed to be tear-free) should not
  set this flag.
- `DRIVER_SYNCOBJ`: Driver supports [`drm_syncobj`](/kernel/hardware/gpu/drm-mm.md#c-struct-drm_syncobj) for explicit synchronization of command
  submission.
- `DRIVER_SYNCOBJ_TIMELINE`: Driver supports the timeline flavor of [`drm_syncobj`](/kernel/hardware/gpu/drm-mm.md#c-struct-drm_syncobj) for explicit
  synchronization of command submission.
- `DRIVER_COMPUTE_ACCEL`: Driver supports compute acceleration devices. This flag is mutually exclusive with
  **DRIVER_RENDER** and **DRIVER_MODESET**. Devices that support both graphics and compute
  acceleration should be handled by two drivers that are connected using auxiliary bus.
- `DRIVER_GEM_GPUVA`: Driver supports user defined GPU VA bindings for GEM objects.
- `DRIVER_CURSOR_HOTSPOT`: Driver supports and requires cursor hotspot information in the
  cursor plane (e.g. cursor plane has to actually track the mouse
  cursor and the clients are required to set hotspot in order for
  the cursor planes to work correctly).
- `DRIVER_USE_AGP`: Set up DRM AGP support, see `drm_agp_init()`, the DRM core will manage
  AGP resources. New drivers don't need this.
- `DRIVER_LEGACY`: Denote a legacy driver using shadow attach. Do not use.
- `DRIVER_PCI_DMA`: Driver is capable of PCI DMA, mapping of PCI DMA buffers to userspace
  will be enabled. Only for legacy drivers. Do not use.
- `DRIVER_SG`: Driver can perform scatter/gather DMA, allocation and mapping of
  scatter/gather buffers will be enabled. Only for legacy drivers. Do
  not use.
- `DRIVER_HAVE_DMA`: Driver supports DMA, the userspace DMA API will be supported. Only
  for legacy drivers. Do not use.
- `DRIVER_HAVE_IRQ`: Legacy irq support. Only for legacy drivers. Do not use.

**Description**

See [`drm_driver.driver_features`](#c-struct-drm_driver), drm_device.driver_features and
[`drm_core_check_feature()`](#c-drm_core_check_feature).

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

DRM driver structure

**Definition**

```c
struct drm_driver {
    int (*load) (struct drm_device *, unsigned long flags);
    int (*open) (struct drm_device *, struct drm_file *);
    void (*postclose) (struct drm_device *, struct drm_file *);
    void (*unload) (struct drm_device *);
    void (*release) (struct drm_device *);
    void (*master_set)(struct drm_device *dev, struct drm_file *file_priv, bool from_open);
    void (*master_drop)(struct drm_device *dev, struct drm_file *file_priv);
    void (*debugfs_init)(struct drm_minor *minor);
    struct drm_gem_object *(*gem_create_object)(struct drm_device *dev, size_t size);
    int (*prime_handle_to_fd)(struct drm_device *dev, struct drm_file *file_priv, uint32_t handle, uint32_t flags, int *prime_fd);
    int (*prime_fd_to_handle)(struct drm_device *dev, struct drm_file *file_priv, int prime_fd, uint32_t *handle);
    struct drm_gem_object * (*gem_prime_import)(struct drm_device *dev, struct dma_buf *dma_buf);
    struct drm_gem_object *(*gem_prime_import_sg_table)( struct drm_device *dev, struct dma_buf_attachment *attach, struct sg_table *sgt);
    int (*dumb_create)(struct drm_file *file_priv, struct drm_device *dev, struct drm_mode_create_dumb *args);
    int (*dumb_map_offset)(struct drm_file *file_priv, struct drm_device *dev, uint32_t handle, uint64_t *offset);
    int (*fbdev_probe)(struct drm_fb_helper *fbdev_helper, struct drm_fb_helper_surface_size *sizes);
    void (*show_fdinfo)(struct drm_printer *p, struct drm_file *f);
    int major;
    int minor;
    int patchlevel;
    char *name;
    char *desc;
    u32 driver_features;
    const struct drm_ioctl_desc *ioctls;
    int num_ioctls;
    const struct file_operations *fops;
};
```

**Members**

- `load`: Backward-compatible driver callback to complete initialization steps
  after the driver is registered.  For this reason, may suffer from
  race conditions and its use is deprecated for new drivers.  It is
  therefore only supported for existing drivers not yet converted to
  the new scheme.  See [`devm_drm_dev_alloc()`](#c-devm_drm_dev_alloc) and [`drm_dev_register()`](#c-drm_dev_register) for
  proper and race-free way to set up a [`struct drm_device`](#c-struct-drm_device).

  This is deprecated, do not use!

  Returns:

  Zero on success, non-zero value on failure.
- `open`: Driver callback when a new [`struct drm_file`](#c-struct-drm_file) is opened. Useful for
  setting up driver-private data structures like buffer allocators,
  execution contexts or similar things. Such driver-private resources
  must be released again in **postclose**.

  Since the display/modeset side of DRM can only be owned by exactly
  one [`struct drm_file`](#c-struct-drm_file) (see [`drm_file.is_master`](#c-struct-drm_file) and [`drm_device.master`](#c-struct-drm_device))
  there should never be a need to set up any modeset related resources
  in this callback. Doing so would be a driver design bug.

  Returns:

  0 on success, a negative error code on failure, which will be
  promoted to userspace as the result of the `open()` system call.
- `postclose`: One of the driver callbacks when a new [`struct drm_file`](#c-struct-drm_file) is closed.
  Useful for tearing down driver-private data structures allocated in
  **open** like buffer allocators, execution contexts or similar things.

  Since the display/modeset side of DRM can only be owned by exactly
  one [`struct drm_file`](#c-struct-drm_file) (see [`drm_file.is_master`](#c-struct-drm_file) and [`drm_device.master`](#c-struct-drm_device))
  there should never be a need to tear down any modeset related
  resources in this callback. Doing so would be a driver design bug.
- `unload`: Reverse the effects of the driver load callback.  Ideally,
  the clean up performed by the driver should happen in the
  reverse order of the initialization.  Similarly to the load
  hook, this handler is deprecated and its usage should be
  dropped in favor of an open-coded teardown function at the
  driver layer.  See [`drm_dev_unregister()`](#c-drm_dev_unregister) and [`drm_dev_put()`](#c-drm_dev_put)
  for the proper way to remove a [`struct drm_device`](#c-struct-drm_device).

  The `unload()` hook is called right after unregistering
  the device.
- `release`: Optional callback for destroying device data after the final
  reference is released, i.e. the device is being destroyed.

  This is deprecated, clean up all memory allocations associated with a
  [`drm_device`](#c-struct-drm_device) using [`drmm_add_action()`](#c-drmm_add_action), [`drmm_kmalloc()`](#c-drmm_kmalloc) and related
  managed resources functions.
- `master_set`: Called whenever the minor master is set. Only used by vmwgfx.
- `master_drop`: Called whenever the minor master is dropped. Only used by vmwgfx.
- `debugfs_init`: Allows drivers to create driver-specific debugfs files.
- `gem_create_object`: constructor for gem objects

  Hook for allocating the GEM object struct, for use by the CMA
  and SHMEM GEM helpers. Returns a GEM object on success, or an
  [`ERR_PTR()`](/kernel/internals/core-api/kernel-api.md#c-ERR_PTR)-encoded error code otherwise.
- `prime_handle_to_fd`: PRIME export function. Only used by vmwgfx.
- `prime_fd_to_handle`: PRIME import function. Only used by vmwgfx.
- `gem_prime_import`: Import hook for GEM drivers.

  This defaults to [`drm_gem_prime_import()`](/kernel/hardware/gpu/drm-mm.md#c-drm_gem_prime_import) if not set.
- `gem_prime_import_sg_table`: Optional hook used by the PRIME helper functions
  [`drm_gem_prime_import()`](/kernel/hardware/gpu/drm-mm.md#c-drm_gem_prime_import) respectively [`drm_gem_prime_import_dev()`](/kernel/hardware/gpu/drm-mm.md#c-drm_gem_prime_import_dev).
- `dumb_create`: This creates a new dumb buffer in the driver's backing storage manager (GEM,
  TTM or something else entirely) and returns the resulting buffer handle. This
  handle can then be wrapped up into a framebuffer modeset object.

  Note that userspace is not allowed to use such objects for render
  acceleration - drivers must create their own private ioctls for such a use
  case.

  Width, height and depth are specified in the [`drm_mode_create_dumb`](/kernel/hardware/gpu/drm-uapi.md#c-struct-drm_mode_create_dumb)
  argument. The callback needs to fill the handle, pitch and size for
  the created buffer.

  Called by the user via ioctl.

  Returns:

  Zero on success, negative errno on failure.
- `dumb_map_offset`: Allocate an offset in the drm device node's address space to be able to
  memory map a dumb buffer.

  The default implementation is [`drm_gem_create_mmap_offset()`](/kernel/hardware/gpu/drm-mm.md#c-drm_gem_create_mmap_offset). GEM based
  drivers must not overwrite this.

  Called by the user via ioctl.

  Returns:

  Zero on success, negative errno on failure.
- `fbdev_probe`: Allocates and initialize the fb_info structure for fbdev emulation.
  Furthermore it also needs to allocate the DRM framebuffer used to
  back the fbdev.

  This callback is mandatory for fbdev support.

  Returns:

  0 on success ot a negative error code otherwise.
- `show_fdinfo`: Print device specific fdinfo.  See Documentation/gpu/drm-usage-stats.rst.
- `major`: driver major number
- `minor`: driver minor number
- `patchlevel`: driver patch level
- `name`: driver name
- `desc`: driver description
- `driver_features`: Driver features, see [`enum drm_driver_feature`](#c-enum-drm_driver_feature). Drivers can disable
  some features on a per-instance basis using
  [`drm_device.driver_features`](#c-struct-drm_device).
- `ioctls`: Array of driver-private IOCTL description entries. See the chapter on
  IOCTL support in the userland interfaces
  chapter for the full details.
- `num_ioctls`: Number of entries in **ioctls**.
- `fops`: File operations for the DRM device node. See the discussion in
  file operations for in-depth coverage and
  some examples.

**Description**

This structure represent the common code for a family of cards. There will be
one [`struct drm_device`](#c-struct-drm_device) for each card present in this family. It contains lots
of vfunc entries, and a pile of those probably should be moved to more
appropriate places like [`drm_mode_config_funcs`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_mode_config_funcs) or into a new operations
structure for GEM drivers.

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

```c
devm_drm_dev_alloc(parent, driver, type, member)
```

Resource managed allocation of a [`drm_device`](#c-struct-drm_device) instance

**Parameters**

- `parent`: Parent device object
- `driver`: DRM driver
- `type`: the type of the struct which contains struct [`drm_device`](#c-struct-drm_device)
- `member`: the name of the [`drm_device`](#c-struct-drm_device) within **type**.

**Description**

This allocates and initialize a new DRM device. No device registration is done.
Call [`drm_dev_register()`](#c-drm_dev_register) to advertice the device to user space and register it
with other core subsystems. This should be done last in the device
initialization sequence to make sure userspace can't access an inconsistent
state.

The initial ref-count of the object is 1. Use [`drm_dev_get()`](#c-drm_dev_get) and
[`drm_dev_put()`](#c-drm_dev_put) to take and drop further ref-counts.

It is recommended that drivers embed [`struct drm_device`](#c-struct-drm_device) into their own device
structure.

Note that this manages the lifetime of the resulting [`drm_device`](#c-struct-drm_device)
automatically using devres. The DRM device initialized with this function is
automatically put on driver detach using [`drm_dev_put()`](#c-drm_dev_put).

**Return**

Pointer to new DRM device, or ERR_PTR on failure.

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

```c
bool drm_dev_is_unplugged(struct drm_device *dev)
```

is a DRM device unplugged

**Parameters**

- `struct drm_device *dev`: DRM device

**Description**

This function can be called to check whether a hotpluggable is unplugged.
Unplugging itself is singalled through [`drm_dev_unplug()`](#c-drm_dev_unplug). If a device is
unplugged, these two functions guarantee that any store before calling
[`drm_dev_unplug()`](#c-drm_dev_unplug) is visible to callers of this function after it completes

WARNING: This function fundamentally races against [`drm_dev_unplug()`](#c-drm_dev_unplug). It is
recommended that drivers instead use the underlying [`drm_dev_enter()`](#c-drm_dev_enter) and
[`drm_dev_exit()`](#c-drm_dev_exit) function pairs.

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

```c
bool drm_core_check_all_features(const struct drm_device *dev, u32 features)
```

check driver feature flags mask

**Parameters**

- `const struct drm_device *dev`: DRM device to check
- `u32 features`: feature flag(s) mask

**Description**

This checks **dev** for driver features, see [`drm_driver.driver_features`](#c-struct-drm_driver),
[`drm_device.driver_features`](#c-struct-drm_device), and the various [`enum drm_driver_feature`](#c-enum-drm_driver_feature) flags.

Returns true if all features in the **features** mask are supported, false
otherwise.

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

```c
bool drm_core_check_feature(const struct drm_device *dev, enum drm_driver_feature feature)
```

check driver feature flags

**Parameters**

- `const struct drm_device *dev`: DRM device to check
- `enum drm_driver_feature feature`: feature flag

**Description**

This checks **dev** for driver features, see [`drm_driver.driver_features`](#c-struct-drm_driver),
[`drm_device.driver_features`](#c-struct-drm_device), and the various [`enum drm_driver_feature`](#c-enum-drm_driver_feature) flags.

Returns true if the **feature** is supported, false otherwise.

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

```c
bool drm_drv_uses_atomic_modeset(struct drm_device *dev)
```

check if the driver implements `atomic_commit()`

**Parameters**

- `struct drm_device *dev`: DRM device

**Description**

This check is useful if drivers do not have DRIVER_ATOMIC set but
have atomic modesetting internally implemented.



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

```c
void drm_put_dev(struct drm_device *dev)
```

Unregister and release a DRM device

**Parameters**

- `struct drm_device *dev`: DRM device

**Description**

Called at module unload time or when a PCI device is unplugged.

Cleans up all DRM device, calling `drm_lastclose()`.

**Note**

Use of this function is deprecated. It will eventually go away
completely.  Please use [`drm_dev_unregister()`](#c-drm_dev_unregister) and [`drm_dev_put()`](#c-drm_dev_put) explicitly
instead to make sure that the device isn't userspace accessible any more
while teardown is in progress, ensuring that userspace can't access an
inconsistent state.

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

```c
bool drm_dev_enter(struct drm_device *dev, int *idx)
```

Enter device critical section

**Parameters**

- `struct drm_device *dev`: DRM device
- `int *idx`: Pointer to index that will be passed to the matching [`drm_dev_exit()`](#c-drm_dev_exit)

**Description**

This function marks and protects the beginning of a section that should not
be entered after the device has been unplugged. The section end is marked
with [`drm_dev_exit()`](#c-drm_dev_exit). Calls to this function can be nested.

**Return**

True if it is OK to enter the section, false otherwise.

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

```c
void drm_dev_exit(int idx)
```

Exit device critical section

**Parameters**

- `int idx`: index returned from [`drm_dev_enter()`](#c-drm_dev_enter)

**Description**

This function marks the end of a section that should not be entered after
the device has been unplugged.

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

```c
void drm_dev_unplug(struct drm_device *dev)
```

unplug a DRM device

**Parameters**

- `struct drm_device *dev`: DRM device

**Description**

This unplugs a hotpluggable DRM device, which makes it inaccessible to
userspace operations. Entry-points can use [`drm_dev_enter()`](#c-drm_dev_enter) and
[`drm_dev_exit()`](#c-drm_dev_exit) to protect device resources in a race free manner. This
essentially unregisters the device like [`drm_dev_unregister()`](#c-drm_dev_unregister), but can be
called while there are still open users of **dev**.

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

```c
void drm_dev_set_dma_dev(struct drm_device *dev, struct device *dma_dev)
```

set the DMA device for a DRM device

**Parameters**

- `struct drm_device *dev`: DRM device
- `struct device *dma_dev`: DMA device or NULL

**Description**

Sets the DMA device of the given DRM device. Only required if
the DMA device is different from the DRM device's parent. After
calling this function, the DRM device holds a reference on
**dma_dev**. Pass NULL to clear the DMA device.

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

```c
int drm_dev_wedged_event(struct drm_device *dev, unsigned long method, struct drm_wedge_task_info *info)
```

generate a device wedged uevent

**Parameters**

- `struct drm_device *dev`: DRM device
- `unsigned long method`: method(s) to be used for recovery
- `struct drm_wedge_task_info *info`: optional information about the guilty task

**Description**

This generates a device wedged uevent for the DRM device specified by **dev**.
Recovery **method**\(s) of choice will be sent in the uevent environment as
`WEDGED=<method1>[,..,<methodN>]` in order of less to more side-effects.
If caller is unsure about recovery or **method** is unknown (0),
`WEDGED=unknown` will be sent instead.

Refer to "Device Wedging" chapter in Documentation/gpu/drm-uapi.rst for more
details.

**Return**

0 on success, negative error code otherwise.

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

```c
void * __drm_dev_alloc(struct device *parent, const struct drm_driver *driver, size_t size, size_t offset)
```

Allocation of a [`drm_device`](#c-struct-drm_device) instance

**Parameters**

- `struct device *parent`: Parent device object
- `const struct drm_driver *driver`: DRM driver
- `size_t size`: the size of the struct which contains struct drm_device
- `size_t offset`: the offset of the [`drm_device`](#c-struct-drm_device) within the container.

**Description**

This should *NOT* be by any drivers, but is a dedicated interface for the
corresponding Rust abstraction.

This is the same as [`devm_drm_dev_alloc()`](#c-devm_drm_dev_alloc), but without the corresponding
resource management through the parent device, but not the same as
[`drm_dev_alloc()`](#c-drm_dev_alloc), since the latter is the deprecated version, which does not
support subclassing.

**Return**

A pointer to new DRM device, or an ERR_PTR on failure.

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

```c
struct drm_device * drm_dev_alloc(const struct drm_driver *driver, struct device *parent)
```

Allocate new DRM device

**Parameters**

- `const struct drm_driver *driver`: DRM driver to allocate device for
- `struct device *parent`: Parent device object

**Description**

This is the deprecated version of [`devm_drm_dev_alloc()`](#c-devm_drm_dev_alloc), which does not support
subclassing through embedding the struct [`drm_device`](#c-struct-drm_device) in a driver private
structure, and which does not support automatic cleanup through devres.

**Return**

Pointer to new DRM device, or ERR_PTR on failure.

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

```c
void drm_dev_get(struct drm_device *dev)
```

Take reference of a DRM device

**Parameters**

- `struct drm_device *dev`: device to take reference of or NULL

**Description**

This increases the ref-count of **dev** by one. You *must* already own a
reference when calling this. Use [`drm_dev_put()`](#c-drm_dev_put) to drop this reference
again.

This function never fails. However, this function does not provide *any*
guarantee whether the device is alive or running. It only provides a
reference to the object and the memory associated with it.

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

```c
void drm_dev_put(struct drm_device *dev)
```

Drop reference of a DRM device

**Parameters**

- `struct drm_device *dev`: device to drop reference of or NULL

**Description**

This decreases the ref-count of **dev** by one. The device is destroyed if the
ref-count drops to zero.

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

```c
struct dmem_cgroup_region * drmm_cgroup_register_region(struct drm_device *dev, const char *region_name, u64 size)
```

Register a region of a DRM device to cgroups

**Parameters**

- `struct drm_device *dev`: device for region
- `const char *region_name`: Region name for registering
- `u64 size`: Size of region in bytes

**Description**

This decreases the ref-count of **dev** by one. The device is destroyed if the
ref-count drops to zero.

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

```c
int drm_dev_register(struct drm_device *dev, unsigned long flags)
```

Register DRM device

**Parameters**

- `struct drm_device *dev`: Device to register
- `unsigned long flags`: Flags passed to the driver's .`load()` function

**Description**

Register the DRM device **dev** with the system, advertise device to user-space
and start normal device operation. **dev** must be initialized via `drm_dev_init()`
previously.

Never call this twice on any device!

**NOTE**

To ensure backward compatibility with existing drivers method this
function calls the [`drm_driver.load`](#c-struct-drm_driver) method after registering the device
nodes, creating race conditions. Usage of the [`drm_driver.load`](#c-struct-drm_driver) methods is
therefore deprecated, drivers must perform all initialization before calling
[`drm_dev_register()`](#c-drm_dev_register).

**Return**

0 on success, negative error code on failure.

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

```c
void drm_dev_unregister(struct drm_device *dev)
```

Unregister DRM device

**Parameters**

- `struct drm_device *dev`: Device to unregister

**Description**

Unregister the DRM device from the system. This does the reverse of
[`drm_dev_register()`](#c-drm_dev_register) but does not deallocate the device. The caller must call
[`drm_dev_put()`](#c-drm_dev_put) to drop their final reference, unless it is managed with devres
(as devices allocated with [`devm_drm_dev_alloc()`](#c-devm_drm_dev_alloc) are), in which case there is
already an unwind action registered.

A special form of unregistering for hotpluggable devices is [`drm_dev_unplug()`](#c-drm_dev_unplug),
which can be called while there are still open users of **dev**.

This should be called first in the device teardown code to make sure
userspace can't access the device instance any more.


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

### Driver Load

<a id="rst-component-helper-usage"></a>

#### Component Helper Usage


DRM drivers that drive hardware where a logical device consists of a pile of
independent hardware blocks are recommended to use the component helper
library. For consistency and better options for code reuse the
following guidelines apply:

- The entire device initialization procedure should be run from the
  [`component_master_ops.master_bind`](/kernel/hardware/driver-api/fundamentals/component.md#c-struct-component_master_ops) callback, starting with
  [`devm_drm_dev_alloc()`](#c-devm_drm_dev_alloc), then binding all components with
  [`component_bind_all()`](/kernel/hardware/driver-api/fundamentals/component.md#c-component_bind_all) and finishing with [`drm_dev_register()`](#c-drm_dev_register).

- The opaque pointer passed to all components through [`component_bind_all()`](/kernel/hardware/driver-api/fundamentals/component.md#c-component_bind_all)
  should point at [`struct drm_device`](#c-struct-drm_device) of the device instance, not some driver
  specific private structure.

- The component helper fills the niche where further standardization of
  interfaces is not practical. When there already is, or will be, a
  standardized interface like [`drm_bridge`](/kernel/hardware/gpu/drm-kms-helpers.md#c-struct-drm_bridge) or [`drm_panel`](/kernel/hardware/gpu/drm-kms-helpers.md#c-struct-drm_panel), providing its own
  functions to find such components at driver load time, like
  [`drm_of_find_panel_or_bridge()`](/kernel/hardware/gpu/drm-kms-helpers.md#c-drm_of_find_panel_or_bridge), then the component helper should not be
  used.


<a id="rst-memory-manager-initialization"></a>

#### Memory Manager Initialization

Every DRM driver requires a memory manager which must be initialized at load time. DRM currently contains two memory managers, the Translation Table Manager (TTM) and the Graphics Execution Manager (GEM). This document describes the use of the GEM memory manager only. See ? for details.

<a id="rst-miscellaneous-device-configuration"></a>

#### Miscellaneous Device Configuration

Another task that may be necessary for PCI devices during configuration is mapping the video BIOS. On many devices, the VBIOS describes device configuration, LCD panel timings (if any), and contains flags indicating device state. Mapping the BIOS can be done using the pci_map_rom() call, a convenience function that takes care of mapping the actual ROM, whether it has been shadowed into memory (typically at address 0xc0000) or exists on the PCI device in the ROM BAR. Note that after the ROM has been mapped and any necessary information has been extracted, it should be unmapped; on many devices, the ROM address decoder is shared with other BARs, so leaving it mapped could cause undesired behaviour like hangs or memory corruption.

<a id="rst-managed-resources"></a>

### Managed Resources


Inspired by struct [`device`](/kernel/hardware/driver-api/fundamentals/infrastructure.md#c-struct-device) managed resources, but tied to the lifetime of
struct [`drm_device`](#c-struct-drm_device), which can outlive the underlying physical device, usually
when userspace has some open files and other handles to resources still open.

Release actions can be added with [`drmm_add_action()`](#c-drmm_add_action), memory allocations can
be done directly with [`drmm_kmalloc()`](#c-drmm_kmalloc) and the related functions. Everything
will be released on the final [`drm_dev_put()`](#c-drm_dev_put) in reverse order of how the
release actions have been added and memory has been allocated since driver
loading started with [`devm_drm_dev_alloc()`](#c-devm_drm_dev_alloc).

Note that release actions and managed memory can also be added and removed
during the lifetime of the driver, all the functions are fully concurrent
safe. But it is recommended to use managed resources only for resources that
change rarely, if ever, during the lifetime of the [`drm_device`](#c-struct-drm_device) instance.



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

```c
void drmm_release_action(struct drm_device *dev, drmres_release_t action, void *data)
```

release a managed action from a [`drm_device`](#c-struct-drm_device)

**Parameters**

- `struct drm_device *dev`: DRM device
- `drmres_release_t action`: function which would be called when **dev** is released
- `void *data`: opaque pointer, passed to **action**

**Description**

This function calls the **action** previously added by [`drmm_add_action()`](#c-drmm_add_action)
immediately.
The **action** is removed from the list of cleanup actions for **dev**,
which means that it won't be called in the final [`drm_dev_put()`](#c-drm_dev_put).

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

```c
void * drmm_kmalloc(struct drm_device *dev, size_t size, gfp_t gfp)
```

[`drm_device`](#c-struct-drm_device) managed [`kmalloc()`](/kernel/internals/core-api/mm-api.md#c-kmalloc)

**Parameters**

- `struct drm_device *dev`: DRM device
- `size_t size`: size of the memory allocation
- `gfp_t gfp`: GFP allocation flags

**Description**

This is a [`drm_device`](#c-struct-drm_device) managed version of [`kmalloc()`](/kernel/internals/core-api/mm-api.md#c-kmalloc). The allocated memory is
automatically freed on the final [`drm_dev_put()`](#c-drm_dev_put). Memory can also be freed
before the final [`drm_dev_put()`](#c-drm_dev_put) by calling [`drmm_kfree()`](#c-drmm_kfree).

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

```c
char * drmm_kstrdup(struct drm_device *dev, const char *s, gfp_t gfp)
```

[`drm_device`](#c-struct-drm_device) managed [`kstrdup()`](/kernel/internals/core-api/kernel-api.md#c-kstrdup)

**Parameters**

- `struct drm_device *dev`: DRM device
- `const char *s`: 0-terminated string to be duplicated
- `gfp_t gfp`: GFP allocation flags

**Description**

This is a [`drm_device`](#c-struct-drm_device) managed version of [`kstrdup()`](/kernel/internals/core-api/kernel-api.md#c-kstrdup). The allocated memory is
automatically freed on the final [`drm_dev_put()`](#c-drm_dev_put) and works exactly like a
memory allocation obtained by [`drmm_kmalloc()`](#c-drmm_kmalloc).

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

```c
void drmm_kfree(struct drm_device *dev, void *data)
```

[`drm_device`](#c-struct-drm_device) managed [`kfree()`](/kernel/internals/core-api/mm-api.md#c-kfree)

**Parameters**

- `struct drm_device *dev`: DRM device
- `void *data`: memory allocation to be freed

**Description**

This is a [`drm_device`](#c-struct-drm_device) managed version of [`kfree()`](/kernel/internals/core-api/mm-api.md#c-kfree) which can be used to
release memory allocated through [`drmm_kmalloc()`](#c-drmm_kmalloc) or any of its related
functions before the final [`drm_dev_put()`](#c-drm_dev_put) of **dev**.



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

```c
drmm_add_action(dev, action, data)
```

add a managed release action to a [`drm_device`](#c-struct-drm_device)

**Parameters**

- `dev`: DRM device
- `action`: function which should be called when **dev** is released
- `data`: opaque pointer, passed to **action**

**Description**

This function adds the **release** action with optional parameter **data** to the
list of cleanup actions for **dev**. The cleanup actions will be run in reverse
order in the final [`drm_dev_put()`](#c-drm_dev_put) call for **dev**.

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

```c
drmm_add_action_or_reset(dev, action, data)
```

add a managed release action to a [`drm_device`](#c-struct-drm_device)

**Parameters**

- `dev`: DRM device
- `action`: function which should be called when **dev** is released
- `data`: opaque pointer, passed to **action**

**Description**

Similar to [`drmm_add_action()`](#c-drmm_add_action), with the only difference that upon failure
**action** is directly called for any cleanup work necessary on failures.

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

```c
void * drmm_kzalloc(struct drm_device *dev, size_t size, gfp_t gfp)
```

[`drm_device`](#c-struct-drm_device) managed [`kzalloc()`](/kernel/internals/core-api/mm-api.md#c-kzalloc)

**Parameters**

- `struct drm_device *dev`: DRM device
- `size_t size`: size of the memory allocation
- `gfp_t gfp`: GFP allocation flags

**Description**

This is a [`drm_device`](#c-struct-drm_device) managed version of [`kzalloc()`](/kernel/internals/core-api/mm-api.md#c-kzalloc). The allocated memory is
automatically freed on the final [`drm_dev_put()`](#c-drm_dev_put). Memory can also be freed
before the final [`drm_dev_put()`](#c-drm_dev_put) by calling [`drmm_kfree()`](#c-drmm_kfree).

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

```c
void * drmm_kmalloc_array(struct drm_device *dev, size_t n, size_t size, gfp_t flags)
```

[`drm_device`](#c-struct-drm_device) managed [`kmalloc_array()`](/kernel/internals/core-api/mm-api.md#c-kmalloc_array)

**Parameters**

- `struct drm_device *dev`: DRM device
- `size_t n`: number of array elements to allocate
- `size_t size`: size of array member
- `gfp_t flags`: GFP allocation flags

**Description**

This is a [`drm_device`](#c-struct-drm_device) managed version of [`kmalloc_array()`](/kernel/internals/core-api/mm-api.md#c-kmalloc_array). The allocated
memory is automatically freed on the final [`drm_dev_put()`](#c-drm_dev_put) and works exactly
like a memory allocation obtained by [`drmm_kmalloc()`](#c-drmm_kmalloc).

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

```c
void * drmm_kcalloc(struct drm_device *dev, size_t n, size_t size, gfp_t flags)
```

[`drm_device`](#c-struct-drm_device) managed [`kcalloc()`](/kernel/internals/core-api/mm-api.md#c-kcalloc)

**Parameters**

- `struct drm_device *dev`: DRM device
- `size_t n`: number of array elements to allocate
- `size_t size`: size of array member
- `gfp_t flags`: GFP allocation flags

**Description**

This is a [`drm_device`](#c-struct-drm_device) managed version of [`kcalloc()`](/kernel/internals/core-api/mm-api.md#c-kcalloc). The allocated memory is
automatically freed on the final [`drm_dev_put()`](#c-drm_dev_put) and works exactly like a
memory allocation obtained by [`drmm_kmalloc()`](#c-drmm_kmalloc).

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

```c
drmm_mutex_init(dev, lock)
```

[`drm_device`](#c-struct-drm_device)-managed [`mutex_init()`](/kernel/development/kernel-hacking/locking.md#c-mutex_init)

**Parameters**

- `dev`: DRM device
- `lock`: lock to be initialized

**Return**

0 on success, or a negative errno code otherwise.

**Description**

This is a [`drm_device`](#c-struct-drm_device)-managed version of [`mutex_init()`](/kernel/development/kernel-hacking/locking.md#c-mutex_init). The initialized
lock is automatically destroyed on the final [`drm_dev_put()`](#c-drm_dev_put).

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

```c
drmm_alloc_ordered_workqueue(dev, fmt, flags, args...)
```

[`drm_device`](#c-struct-drm_device) managed [`alloc_ordered_workqueue()`](/kernel/internals/core-api/workqueue.md#c-alloc_ordered_workqueue)

**Parameters**

- `dev`: DRM device
- `fmt`: printf format for the name of the workqueue
- `flags`: WQ_* flags (only WQ_FREEZABLE and WQ_MEM_RECLAIM are meaningful)
- `args...`: args for **fmt**

**Description**

This is a [`drm_device`](#c-struct-drm_device)-managed version of [`alloc_ordered_workqueue()`](/kernel/internals/core-api/workqueue.md#c-alloc_ordered_workqueue). The
allocated workqueue is automatically destroyed on the final [`drm_dev_put()`](#c-drm_dev_put).

**Return**

workqueue on success, negative ERR_PTR otherwise.


<a id="rst-open-close-file-operations-and-ioctls"></a>

## Open/Close, File Operations and IOCTLs

<a id="rst-file-operations"></a>
<a id="rst-drm-driver-fops"></a>

### File Operations


Drivers must define the file operations structure that forms the DRM
userspace API entry point, even though most of those operations are
implemented in the DRM core. The resulting `struct file_operations` must be
stored in the [`drm_driver.fops`](#c-struct-drm_driver) field. The mandatory functions are [`drm_open()`](#c-drm_open),
[`drm_read()`](#c-drm_read), [`drm_ioctl()`](/kernel/hardware/gpu/drm-uapi.md#c-drm_ioctl) and [`drm_compat_ioctl()`](/kernel/hardware/gpu/drm-uapi.md#c-drm_compat_ioctl) if CONFIG_COMPAT is enabled
Note that drm_compat_ioctl will be NULL if CONFIG_COMPAT=n, so there's no
need to sprinkle #ifdef into the code. Drivers which implement private ioctls
that require 32/64 bit compatibility support must provide their own
`file_operations.compat_ioctl` handler that processes private ioctls and calls
[`drm_compat_ioctl()`](/kernel/hardware/gpu/drm-uapi.md#c-drm_compat_ioctl) for core ioctls.

In addition [`drm_read()`](#c-drm_read) and [`drm_poll()`](#c-drm_poll) provide support for DRM events. DRM
events are a generic and extensible means to send asynchronous events to
userspace through the file descriptor. They are used to send vblank event and
page flip completions by the KMS API. But drivers can also use it for their
own needs, e.g. to signal completion of rendering.

For the driver-side event interface see [`drm_event_reserve_init()`](#c-drm_event_reserve_init) and
[`drm_send_event()`](#c-drm_send_event) as the main starting points.

The memory mapping implementation will vary depending on how the driver
manages memory. For GEM-based drivers this is [`drm_gem_mmap()`](/kernel/hardware/gpu/drm-mm.md#c-drm_gem_mmap).

No other file operations are supported by the DRM userspace API. Overall the
following is an example `file_operations` structure:

```text
static const example_drm_fops = {
        .owner = THIS_MODULE,
        .open = drm_open,
        .release = drm_release,
        .unlocked_ioctl = drm_ioctl,
        .compat_ioctl = drm_compat_ioctl, // NULL if CONFIG_COMPAT=n
        .poll = drm_poll,
        .read = drm_read,
        .mmap = drm_gem_mmap,
};
```

For plain GEM based drivers there is the [`DEFINE_DRM_GEM_FOPS()`](/kernel/hardware/gpu/drm-mm.md#c-DEFINE_DRM_GEM_FOPS) macro, and for
DMA based drivers there is the [`DEFINE_DRM_GEM_DMA_FOPS()`](/kernel/hardware/gpu/drm-mm.md#c-DEFINE_DRM_GEM_DMA_FOPS) macro to make this
simpler.

The driver's `file_operations` must be stored in [`drm_driver.fops`](#c-struct-drm_driver).

For driver-private IOCTL handling see the more detailed discussion in
IOCTL support in the userland interfaces chapter.



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

DRM device minor structure

**Definition**

```c
struct drm_minor {
};
```

**Description**

This structure represents a DRM minor number for device nodes in /dev.
Entirely opaque to drivers and should never be inspected directly by drivers.
Drivers instead should only interact with [`struct drm_file`](#c-struct-drm_file) and of course
[`struct drm_device`](#c-struct-drm_device), which is also where driver-private data and resources can
be attached to.

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

Event queued up for userspace to read

**Definition**

```c
struct drm_pending_event {
    struct completion *completion;
    void (*completion_release)(struct completion *completion);
    struct drm_event *event;
    struct dma_fence *fence;
    struct drm_file *file_priv;
    struct list_head link;
    struct list_head pending_link;
};
```

**Members**

- `completion`: Optional pointer to a kernel internal completion signalled when
  [`drm_send_event()`](#c-drm_send_event) is called, useful to internally synchronize with
  nonblocking operations.
- `completion_release`: Optional callback currently only used by the atomic modeset helpers
  to clean up the reference count for the structure **completion** is
  stored in.
- `event`: Pointer to the actual event that should be sent to userspace to be
  read using [`drm_read()`](#c-drm_read). Can be optional, since nowadays events are
  also used to signal kernel internal threads with **completion** or DMA
  transactions using **fence**.
- `fence`: Optional DMA fence to unblock other hardware transactions which
  depend upon the nonblocking DRM operation this event represents.
- `file_priv`: [`struct drm_file`](#c-struct-drm_file) where **event** should be delivered to. Only set when
  **event** is set.
- `link`: Double-linked list to keep track of this event. Can be used by the
  driver up to the point when it calls [`drm_send_event()`](#c-drm_send_event), after that
  this list entry is owned by the core for its own book-keeping.
- `pending_link`: Entry on [`drm_file.pending_event_list`](#c-struct-drm_file), to keep track of all pending
  events for **file_priv**, to allow correct unwinding of them when
  userspace closes the file before the event is delivered.

**Description**

This represents a DRM event. Drivers can use this as a generic completion
mechanism, which supports kernel-internal `struct completion`, [`struct dma_fence`](/kernel/hardware/driver-api/io-and-dma/dma-buf.md#c-struct-dma_fence)
and also the DRM-specific [`struct drm_event`](/kernel/hardware/gpu/drm-uapi.md#c-struct-drm_event) delivery mechanism.

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

DRM file private data

**Definition**

```c
struct drm_file {
    bool authenticated;
    bool stereo_allowed;
    bool universal_planes;
    bool atomic;
    bool aspect_ratio_allowed;
    bool writeback_connectors;
    bool plane_color_pipeline;
    bool was_master;
    bool is_master;
    bool supports_virtualized_cursor_plane;
    struct drm_master *master;
    spinlock_t master_lookup_lock;
    struct pid  *pid;
    u64 client_id;
    drm_magic_t magic;
    struct list_head lhead;
    struct drm_minor *minor;
    struct idr object_idr;
    spinlock_t table_lock;
    struct xarray syncobj_xa;
    struct file *filp;
    void *driver_priv;
    struct list_head fbs;
    struct mutex fbs_lock;
    struct list_head blobs;
    wait_queue_head_t event_wait;
    struct list_head pending_event_list;
    struct list_head event_list;
    int event_space;
    struct mutex event_read_lock;
    struct drm_prime_file_private prime;
    const char *client_name;
    struct mutex client_name_lock;
    struct dentry *debugfs_client;
};
```

**Members**

- `authenticated`: Whether the client is allowed to submit rendering, which for legacy
  nodes means it must be authenticated.

  See also the section on primary nodes and authentication.
- `stereo_allowed`: True when the client has asked us to expose stereo 3D mode flags.
- `universal_planes`: True if client understands CRTC primary planes and cursor planes
  in the plane list. Automatically set when **atomic** is set.
- `atomic`: True if client understands atomic properties.
- `aspect_ratio_allowed`: True, if client can handle picture aspect ratios, and has requested
  to pass this information along with the mode.
- `writeback_connectors`: True if client understands writeback connectors
- `plane_color_pipeline`: True if client understands plane color pipelines
- `was_master`: This client has or had, master capability. Protected by struct
  [`drm_device.master_mutex`](#c-struct-drm_device).

  This is used to ensure that CAP_SYS_ADMIN is not enforced, if the
  client is or was master in the past.
- `is_master`: This client is the creator of **master**. Protected by struct
  [`drm_device.master_mutex`](#c-struct-drm_device).

  See also the section on primary nodes and authentication.
- `supports_virtualized_cursor_plane`: This client is capable of handling the cursor plane with the
  restrictions imposed on it by the virtualized drivers.

  This implies that the cursor plane has to behave like a cursor
  i.e. track cursor movement. It also requires setting of the
  hotspot properties by the client on the cursor plane.
- `master`: Master this node is currently associated with. Protected by struct
  [`drm_device.master_mutex`](#c-struct-drm_device), and serialized by **master_lookup_lock**.

  Only relevant if [`drm_is_primary_client()`](#c-drm_is_primary_client) returns true. Note that
  this only matches [`drm_device.master`](#c-struct-drm_device) if the master is the currently
  active one.

  To update **master**, both [`drm_device.master_mutex`](#c-struct-drm_device) and
  **master_lookup_lock** need to be held, therefore holding either of
  them is safe and enough for the read side.

  When dereferencing this pointer, either hold struct
  [`drm_device.master_mutex`](#c-struct-drm_device) for the duration of the pointer's use, or
  use [`drm_file_get_master()`](/kernel/hardware/gpu/drm-uapi.md#c-drm_file_get_master) if struct [`drm_device.master_mutex`](#c-struct-drm_device) is not
  currently held and there is no other need to hold it. This prevents
  **master** from being freed during use.

  See also **authentication** and **is_master** and the section on
  primary nodes and authentication.
- `master_lookup_lock`: Serializes **master**.
- `pid`: Process that is using this file.

  Must only be dereferenced under a rcu_read_lock or equivalent.

  Updates are guarded with dev->filelist_mutex and reference must be
  dropped after a RCU grace period to accommodate lockless readers.
- `client_id`: A unique id for fdinfo
- `magic`: Authentication magic, see **authenticated**.
- `lhead`: List of all open files of a DRM device, linked into
  [`drm_device.filelist`](#c-struct-drm_device). Protected by [`drm_device.filelist_mutex`](#c-struct-drm_device).
- `minor`: [`struct drm_minor`](#c-struct-drm_minor) for this file.
- `object_idr`: Mapping of mm object handles to object pointers. Used by the GEM
  subsystem. Protected by **table_lock**.

  Note that allocated entries might be NULL as a transient state when
  creating or deleting a handle.
- `table_lock`: Protects **object_idr**.
- `syncobj_xa`: Mapping of sync object handles to object pointers.
- `filp`: Pointer to the core file structure.
- `driver_priv`: Optional pointer for driver private data. Can be allocated in
  [`drm_driver.open`](#c-struct-drm_driver) and should be freed in [`drm_driver.postclose`](#c-struct-drm_driver).
- `fbs`: List of [`struct drm_framebuffer`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_framebuffer) associated with this file, using the
  [`drm_framebuffer.filp_head`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_framebuffer) entry.

  Protected by **fbs_lock**. Note that the **fbs** list holds a reference on
  the framebuffer object to prevent it from untimely disappearing.
- `fbs_lock`: Protects **fbs**.
- `blobs`: User-created blob properties; this retains a reference on the
  property.

  Protected by **drm_mode_config.blob_lock**;
- `event_wait`: Waitqueue for new events added to **event_list**.
- `pending_event_list`: List of pending [`struct drm_pending_event`](#c-struct-drm_pending_event), used to clean up pending
  events in case this file gets closed before the event is signalled.
  Uses the [`drm_pending_event.pending_link`](#c-struct-drm_pending_event) entry.

  Protect by [`drm_device.event_lock`](#c-struct-drm_device).
- `event_list`: List of [`struct drm_pending_event`](#c-struct-drm_pending_event), ready for delivery to userspace
  through [`drm_read()`](#c-drm_read). Uses the [`drm_pending_event.link`](#c-struct-drm_pending_event) entry.

  Protect by [`drm_device.event_lock`](#c-struct-drm_device).
- `event_space`: Available event space to prevent userspace from
  exhausting kernel memory. Currently limited to the fairly arbitrary
  value of 4KB.
- `event_read_lock`: Serializes [`drm_read()`](#c-drm_read).
- `prime`: Per-file buffer caches used by the PRIME buffer sharing code.
- `client_name`: Userspace-provided name; useful for accounting and debugging.
- `client_name_lock`: Protects **client_name**.
- `debugfs_client`: debugfs directory for each client under a drm node.

**Description**

This structure tracks DRM state per open file descriptor.

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

```c
bool drm_is_primary_client(const struct drm_file *file_priv)
```

is this an open file of the primary node

**Parameters**

- `const struct drm_file *file_priv`: DRM file

**Description**

Returns true if this is an open file of the primary node, i.e.
[`drm_file.minor`](#c-struct-drm_file) of **file_priv** is a primary minor.

See also the section on primary nodes and authentication.

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

```c
bool drm_is_render_client(const struct drm_file *file_priv)
```

is this an open file of the render node

**Parameters**

- `const struct drm_file *file_priv`: DRM file

**Description**

Returns true if this is an open file of the render node, i.e.
[`drm_file.minor`](#c-struct-drm_file) of **file_priv** is a render minor.

See also the section on render nodes.

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

```c
bool drm_is_accel_client(const struct drm_file *file_priv)
```

is this an open file of the compute acceleration node

**Parameters**

- `const struct drm_file *file_priv`: DRM file

**Description**

Returns true if this is an open file of the compute acceleration node, i.e.
[`drm_file.minor`](#c-struct-drm_file) of **file_priv** is a accel minor.

See also Introduction to compute accelerators subsystem.

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

GEM object stats associated

**Definition**

```c
struct drm_memory_stats {
    u64 shared;
    u64 private;
    u64 resident;
    u64 purgeable;
    u64 active;
};
```

**Members**

- `shared`: Total size of GEM objects shared between processes
- `private`: Total size of GEM objects
- `resident`: Total size of GEM objects backing pages
- `purgeable`: Total size of GEM objects that can be purged (resident and not active)
- `active`: Total size of GEM objects active on one or more engines

**Description**

Used by [`drm_print_memory_stats()`](#c-drm_print_memory_stats)



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

```c
int drm_open(struct inode *inode, struct file *filp)
```

open method for DRM file

**Parameters**

- `struct inode *inode`: device inode
- `struct file *filp`: file pointer.

**Description**

This function must be used by drivers as their `file_operations.open` method.
It looks up the correct DRM device and instantiates all the per-file
resources for it. It also calls the [`drm_driver.open`](#c-struct-drm_driver) driver callback.

**Return**

0 on success or negative errno value on failure.

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

```c
int drm_release(struct inode *inode, struct file *filp)
```

release method for DRM file

**Parameters**

- `struct inode *inode`: device inode
- `struct file *filp`: file pointer.

**Description**

This function must be used by drivers as their `file_operations.release`
method. It frees any resources associated with the open file. If this
is the last open file for the DRM device, it also restores the active
in-kernel DRM client.

**Return**

Always succeeds and returns 0.

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

```c
int drm_release_noglobal(struct inode *inode, struct file *filp)
```

release method for DRM file

**Parameters**

- `struct inode *inode`: device inode
- `struct file *filp`: file pointer.

**Description**

This function may be used by drivers as their `file_operations.release`
method. It frees any resources associated with the open file prior to taking
the drm_global_mutex. If this is the last open file for the DRM device, it
then restores the active in-kernel DRM client.

**Return**

Always succeeds and returns 0.

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

```c
ssize_t drm_read(struct file *filp, char __user *buffer, size_t count, loff_t *offset)
```

read method for DRM file

**Parameters**

- `struct file *filp`: file pointer
- `char __user *buffer`: userspace destination pointer for the read
- `size_t count`: count in bytes to read
- `loff_t *offset`: offset to read

**Description**

This function must be used by drivers as their `file_operations.read`
method if they use DRM events for asynchronous signalling to userspace.
Since events are used by the KMS API for vblank and page flip completion this
means all modern display drivers must use it.

**offset** is ignored, DRM events are read like a pipe. Polling support is
provided by [`drm_poll()`](#c-drm_poll).

This function will only ever read a full event. Therefore userspace must
supply a big enough buffer to fit any event to ensure forward progress. Since
the maximum event space is currently 4K it's recommended to just use that for
safety.

**Return**

Number of bytes read (always aligned to full events, and can be 0) or a
negative error code on failure.

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

```c
__poll_t drm_poll(struct file *filp, struct poll_table_struct *wait)
```

poll method for DRM file

**Parameters**

- `struct file *filp`: file pointer
- `struct poll_table_struct *wait`: poll waiter table

**Description**

This function must be used by drivers as their `file_operations.read` method
if they use DRM events for asynchronous signalling to userspace.  Since
events are used by the KMS API for vblank and page flip completion this means
all modern display drivers must use it.

See also [`drm_read()`](#c-drm_read).

**Return**

Mask of POLL flags indicating the current status of the file.

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

```c
int drm_event_reserve_init_locked(struct drm_device *dev, struct drm_file *file_priv, struct drm_pending_event *p, struct drm_event *e)
```

init a DRM event and reserve space for it

**Parameters**

- `struct drm_device *dev`: DRM device
- `struct drm_file *file_priv`: DRM file private data
- `struct drm_pending_event *p`: tracking structure for the pending event
- `struct drm_event *e`: actual event data to deliver to userspace

**Description**

This function prepares the passed in event for eventual delivery. If the event
doesn't get delivered (because the IOCTL fails later on, before queuing up
anything) then the even must be cancelled and freed using
[`drm_event_cancel_free()`](#c-drm_event_cancel_free). Successfully initialized events should be sent out
using [`drm_send_event()`](#c-drm_send_event) or [`drm_send_event_locked()`](#c-drm_send_event_locked) to signal completion of the
asynchronous event to userspace.

If callers embedded **p** into a larger structure it must be allocated with
kmalloc and **p** must be the first member element.

This is the locked version of [`drm_event_reserve_init()`](#c-drm_event_reserve_init) for callers which
already hold [`drm_device.event_lock`](#c-struct-drm_device).

**Return**

0 on success or a negative error code on failure.

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

```c
int drm_event_reserve_init(struct drm_device *dev, struct drm_file *file_priv, struct drm_pending_event *p, struct drm_event *e)
```

init a DRM event and reserve space for it

**Parameters**

- `struct drm_device *dev`: DRM device
- `struct drm_file *file_priv`: DRM file private data
- `struct drm_pending_event *p`: tracking structure for the pending event
- `struct drm_event *e`: actual event data to deliver to userspace

**Description**

This function prepares the passed in event for eventual delivery. If the event
doesn't get delivered (because the IOCTL fails later on, before queuing up
anything) then the even must be cancelled and freed using
[`drm_event_cancel_free()`](#c-drm_event_cancel_free). Successfully initialized events should be sent out
using [`drm_send_event()`](#c-drm_send_event) or [`drm_send_event_locked()`](#c-drm_send_event_locked) to signal completion of the
asynchronous event to userspace.

If callers embedded **p** into a larger structure it must be allocated with
kmalloc and **p** must be the first member element.

Callers which already hold [`drm_device.event_lock`](#c-struct-drm_device) should use
[`drm_event_reserve_init_locked()`](#c-drm_event_reserve_init_locked) instead.

**Return**

0 on success or a negative error code on failure.

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

```c
void drm_event_cancel_free(struct drm_device *dev, struct drm_pending_event *p)
```

free a DRM event and release its space

**Parameters**

- `struct drm_device *dev`: DRM device
- `struct drm_pending_event *p`: tracking structure for the pending event

**Description**

This function frees the event **p** initialized with [`drm_event_reserve_init()`](#c-drm_event_reserve_init)
and releases any allocated space. It is used to cancel an event when the
nonblocking operation could not be submitted and needed to be aborted.

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

```c
void drm_send_event_timestamp_locked(struct drm_device *dev, struct drm_pending_event *e, ktime_t timestamp)
```

send DRM event to file descriptor

**Parameters**

- `struct drm_device *dev`: DRM device
- `struct drm_pending_event *e`: DRM event to deliver
- `ktime_t timestamp`: timestamp to set for the fence event in kernel's CLOCK_MONOTONIC
  time domain

**Description**

This function sends the event **e**, initialized with [`drm_event_reserve_init()`](#c-drm_event_reserve_init),
to its associated userspace DRM file. Callers must already hold
[`drm_device.event_lock`](#c-struct-drm_device).

Note that the core will take care of unlinking and disarming events when the
corresponding DRM file is closed. Drivers need not worry about whether the
DRM file for this event still exists and can call this function upon
completion of the asynchronous work unconditionally.

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

```c
void drm_send_event_locked(struct drm_device *dev, struct drm_pending_event *e)
```

send DRM event to file descriptor

**Parameters**

- `struct drm_device *dev`: DRM device
- `struct drm_pending_event *e`: DRM event to deliver

**Description**

This function sends the event **e**, initialized with [`drm_event_reserve_init()`](#c-drm_event_reserve_init),
to its associated userspace DRM file. Callers must already hold
[`drm_device.event_lock`](#c-struct-drm_device), see [`drm_send_event()`](#c-drm_send_event) for the unlocked version.

Note that the core will take care of unlinking and disarming events when the
corresponding DRM file is closed. Drivers need not worry about whether the
DRM file for this event still exists and can call this function upon
completion of the asynchronous work unconditionally.

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

```c
void drm_send_event(struct drm_device *dev, struct drm_pending_event *e)
```

send DRM event to file descriptor

**Parameters**

- `struct drm_device *dev`: DRM device
- `struct drm_pending_event *e`: DRM event to deliver

**Description**

This function sends the event **e**, initialized with [`drm_event_reserve_init()`](#c-drm_event_reserve_init),
to its associated userspace DRM file. This function acquires
[`drm_device.event_lock`](#c-struct-drm_device), see [`drm_send_event_locked()`](#c-drm_send_event_locked) for callers which already
hold this lock.

Note that the core will take care of unlinking and disarming events when the
corresponding DRM file is closed. Drivers need not worry about whether the
DRM file for this event still exists and can call this function upon
completion of the asynchronous work unconditionally.

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

```c
void drm_print_memory_stats(struct drm_printer *p, const struct drm_memory_stats *stats, enum drm_gem_object_status supported_status, const char *region)
```

A helper to print memory stats

**Parameters**

- `struct drm_printer *p`: The printer to print output to
- `const struct drm_memory_stats *stats`: The collected memory stats
- `enum drm_gem_object_status supported_status`: Bitmask of optional stats which are available
- `const char *region`: The memory region

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

```c
void drm_show_memory_stats(struct drm_printer *p, struct drm_file *file)
```

Helper to collect and show standard fdinfo memory stats

**Parameters**

- `struct drm_printer *p`: the printer to print output to
- `struct drm_file *file`: the DRM file

**Description**

Helper to iterate over GEM objects with a handle allocated in the specified
file.

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

```c
void drm_show_fdinfo(struct seq_file *m, struct file *f)
```

helper for drm file fops

**Parameters**

- `struct seq_file *m`: output stream
- `struct file *f`: the device file instance

**Description**

Helper to implement fdinfo, for userspace to query usage stats, etc, of a
process using the GPU.  See also [`drm_driver.show_fdinfo`](#c-struct-drm_driver).

For text output format description please see Documentation/gpu/drm-usage-stats.rst

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

```c
void drm_file_err(struct drm_file *file_priv, const char *fmt, ...)
```

log process name, pid and client_name associated with a drm_file

**Parameters**

- `struct drm_file *file_priv`: context of interest for process name and pid
- `const char *fmt`: `printf()` like format string
- `...`: variable arguments

**Description**

Helper function for clients which needs to log process details such
as name and pid etc along with user logs.


<a id="rst-misc-utilities"></a>

## Misc Utilities

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

### Printer


A simple wrapper for `dev_printk()`, `seq_printf()`, etc.  Allows same
debug code to be used for both debugfs and printk logging.

For example:

```text
void log_some_info(struct drm_printer *p)
{
        drm_printf(p, "foo=%d\n", foo);
        drm_printf(p, "bar=%d\n", bar);
}

#ifdef CONFIG_DEBUG_FS
void debugfs_show(struct seq_file *f)
{
        struct drm_printer p = drm_seq_file_printer(f);
        log_some_info(&p);
}
#endif

void some_other_function(...)
{
        struct drm_printer p = drm_info_printer(drm->dev);
        log_some_info(&p);
}
```



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

The DRM debug categories

**Constants**

- `DRM_UT_CORE`: Used in the generic drm code: drm_ioctl.c, drm_mm.c,
  drm_memory.c, ...
- `DRM_UT_DRIVER`: Used in the vendor specific part of the driver: i915,
  radeon, ... macro.
- `DRM_UT_KMS`: Used in the modesetting code.
- `DRM_UT_PRIME`: Used in the prime code.
- `DRM_UT_ATOMIC`: Used in the atomic code.
- `DRM_UT_VBL`: Used for verbose debug message in the vblank code.
- `DRM_UT_STATE`: Used for verbose atomic state debugging.
- `DRM_UT_LEASE`: Used in the lease code.
- `DRM_UT_DP`: Used in the DP code.
- `DRM_UT_DRMRES`: Used in the drm managed resources code.

**Description**

Each of the DRM debug logging macros use a specific category, and the logging
is filtered by the drm.debug module parameter. This enum specifies the values
for the interface.

Each DRM_DEBUG_\<CATEGORY> macro logs to DRM_UT_\<CATEGORY> category, except
`DRM_DEBUG()` logs to DRM_UT_CORE.

Enabling verbose debug messages is done through the drm.debug parameter, each
category being enabled by a bit:

- drm.debug=0x1 will enable CORE messages
- drm.debug=0x2 will enable DRIVER messages
- drm.debug=0x3 will enable CORE and DRIVER messages
- ...
- drm.debug=0x1ff will enable all messages

An interesting feature is that it's possible to enable verbose logging at
run-time by echoing the debug value in its sysfs node:

```text
# echo 0xf > /sys/module/drm/parameters/debug
```

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

drm output "stream"

**Definition**

```c
struct drm_printer {
};
```

**Description**

Do not use struct members directly.  Use `drm_printer_seq_file()`,
`drm_printer_info()`, etc to initialize.  And [`drm_printf()`](#c-drm_printf) for output.

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

```c
void drm_vprintf(struct drm_printer *p, const char *fmt, va_list *va)
```

print to a [`drm_printer`](#c-struct-drm_printer) stream

**Parameters**

- `struct drm_printer *p`: the [`drm_printer`](#c-struct-drm_printer)
- `const char *fmt`: format string
- `va_list *va`: the va_list

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

```c
drm_printf_indent(printer, indent, fmt, ...)
```

Print to a [`drm_printer`](#c-struct-drm_printer) stream with indentation

**Parameters**

- `printer`: DRM printer
- `indent`: Tab indentation level (max 5)
- `fmt`: Format string
- `...`: variable arguments

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

local struct used with drm_printer_coredump

**Definition**

```c
struct drm_print_iterator {
    void *data;
    ssize_t start;
    ssize_t remain;
};
```

**Members**

- `data`: Pointer to the devcoredump output buffer, can be NULL if using
  drm_printer_coredump to determine size of devcoredump
- `start`: The offset within the buffer to start writing
- `remain`: The number of bytes to write for this iteration

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

```c
struct drm_printer drm_coredump_printer(struct drm_print_iterator *iter)
```

construct a [`drm_printer`](#c-struct-drm_printer) that can output to a buffer from the read function for devcoredump

**Parameters**

- `struct drm_print_iterator *iter`: A pointer to a struct drm_print_iterator for the read instance

**Description**

This wrapper extends [`drm_printf()`](#c-drm_printf) to work with a [`dev_coredumpm()`](/kernel/development/process/debugging/driver-development-debugging-guide.md#c-dev_coredumpm) callback
function. The passed in drm_print_iterator struct contains the buffer
pointer, size and offset as passed in from devcoredump.

For example:

```text
void coredump_read(char *buffer, loff_t offset, size_t count,
        void *data, size_t datalen)
{
        struct drm_print_iterator iter;
        struct drm_printer p;

        iter.data = buffer;
        iter.start = offset;
        iter.remain = count;

        p = drm_coredump_printer(&iter);

        drm_printf(p, "foo=%d\n", foo);
}

void makecoredump(...)
{
        ...
        dev_coredumpm(dev, THIS_MODULE, data, 0, GFP_KERNEL,
                coredump_read, ...)
}
```

The above example has a time complexity of O(N^2), where N is the size of the
devcoredump. This is acceptable for small devcoredumps but scales poorly for
larger ones.

Another use case for drm_coredump_printer is to capture the devcoredump into
a saved buffer before the `dev_coredump()` callback. This involves two passes:
one to determine the size of the devcoredump and another to print it to a
buffer. Then, in `dev_coredump()`, copy from the saved buffer into the
devcoredump read buffer.

For example:

```text
char *devcoredump_saved_buffer;

ssize_t __coredump_print(char *buffer, ssize_t count, ...)
{
        struct drm_print_iterator iter;
        struct drm_printer p;

        iter.data = buffer;
        iter.start = 0;
        iter.remain = count;

        p = drm_coredump_printer(&iter);

        drm_printf(p, "foo=%d\n", foo);
        ...
        return count - iter.remain;
}

void coredump_print(...)
{
        ssize_t count;

        count = __coredump_print(NULL, INT_MAX, ...);
        devcoredump_saved_buffer = kvmalloc(count, GFP_KERNEL);
        __coredump_print(devcoredump_saved_buffer, count, ...);
}

void coredump_read(char *buffer, loff_t offset, size_t count,
                   void *data, size_t datalen)
{
        ...
        memcpy(buffer, devcoredump_saved_buffer + offset, count);
        ...
}
```

The above example has a time complexity of O(N*2), where N is the size of the
devcoredump. This scales better than the previous example for larger
devcoredumps.

**Return**

The [`drm_printer`](#c-struct-drm_printer) object

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

```c
bool drm_coredump_printer_is_full(struct drm_printer *p)
```

DRM coredump printer output is full

**Parameters**

- `struct drm_printer *p`: DRM coredump printer

**Description**

DRM printer output is full, useful to short circuit coredump printing once
printer is full.

**Return**

True if DRM coredump printer output buffer is full, False otherwise

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

```c
struct drm_printer drm_seq_file_printer(struct seq_file *f)
```

construct a [`drm_printer`](#c-struct-drm_printer) that outputs to `seq_file`

**Parameters**

- `struct seq_file *f`: the `struct seq_file` to output to

**Return**

The [`drm_printer`](#c-struct-drm_printer) object

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

```c
struct drm_printer drm_info_printer(struct device *dev)
```

construct a [`drm_printer`](#c-struct-drm_printer) that outputs to `dev_printk()`

**Parameters**

- `struct device *dev`: the [`struct device`](/kernel/hardware/driver-api/fundamentals/infrastructure.md#c-struct-device) pointer

**Return**

The [`drm_printer`](#c-struct-drm_printer) object

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

```c
struct drm_printer drm_dbg_printer(struct drm_device *drm, enum drm_debug_category category, const char *prefix)
```

construct a [`drm_printer`](#c-struct-drm_printer) for drm device specific output

**Parameters**

- `struct drm_device *drm`: the [`struct drm_device`](#c-struct-drm_device) pointer, or NULL
- `enum drm_debug_category category`: the debug category to use
- `const char *prefix`: debug output prefix, or NULL for no prefix

**Return**

The [`drm_printer`](#c-struct-drm_printer) object

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

```c
struct drm_printer drm_err_printer(struct drm_device *drm, const char *prefix)
```

construct a [`drm_printer`](#c-struct-drm_printer) that outputs to `drm_err()`

**Parameters**

- `struct drm_device *drm`: the [`struct drm_device`](#c-struct-drm_device) pointer
- `const char *prefix`: debug output prefix, or NULL for no prefix

**Return**

The [`drm_printer`](#c-struct-drm_printer) object

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

```c
struct drm_printer drm_line_printer(struct drm_printer *p, const char *prefix, unsigned int series)
```

construct a [`drm_printer`](#c-struct-drm_printer) that prefixes outputs with line numbers

**Parameters**

- `struct drm_printer *p`: the [`struct drm_printer`](#c-struct-drm_printer) which actually generates the output
- `const char *prefix`: optional output prefix, or NULL for no prefix
- `unsigned int series`: optional unique series identifier, or 0 to omit identifier in the output

**Description**

This printer can be used to increase the robustness of the captured output
to make sure we didn't lost any intermediate lines of the output. Helpful
while capturing some crash data.

Example 1:

```text
void crash_dump(struct drm_device *drm)
{
        static unsigned int id;
        struct drm_printer p = drm_err_printer(drm, "crash");
        struct drm_printer lp = drm_line_printer(&p, "dump", ++id);

        drm_printf(&lp, "foo");
        drm_printf(&lp, "bar");
}
```

Above code will print into the dmesg something like:

```text
[ ] 0000:00:00.0: [drm] *ERROR* crash dump 1.1: foo
[ ] 0000:00:00.0: [drm] *ERROR* crash dump 1.2: bar
```

Example 2:

```text
void line_dump(struct device *dev)
{
        struct drm_printer p = drm_info_printer(dev);
        struct drm_printer lp = drm_line_printer(&p, NULL, 0);

        drm_printf(&lp, "foo");
        drm_printf(&lp, "bar");
}
```

Above code will print:

```text
[ ] 0000:00:00.0: [drm] 1: foo
[ ] 0000:00:00.0: [drm] 2: bar
```

**Return**

The [`drm_printer`](#c-struct-drm_printer) object

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

```c
DRM_DEV_ERROR(dev, fmt, ...)
```

Error output.

**Parameters**

- `dev`: device pointer
- `fmt`: `printf()` like format string.
- `...`: variable arguments

**NOTE**

this is deprecated in favor of `drm_err()` or `dev_err()`.

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

```c
DRM_DEV_ERROR_RATELIMITED(dev, fmt, ...)
```

Rate limited error output.

**Parameters**

- `dev`: device pointer
- `fmt`: `printf()` like format string.
- `...`: variable arguments

**NOTE**

this is deprecated in favor of `drm_err_ratelimited()` or
`dev_err_ratelimited()`.

**Description**

Like `DRM_ERROR()` but won't flood the log.

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

```c
DRM_DEV_DEBUG(dev, fmt, ...)
```

Debug output for generic drm code

**Parameters**

- `dev`: device pointer
- `fmt`: `printf()` like format string.
- `...`: variable arguments

**NOTE**

this is deprecated in favor of `drm_dbg_core()`.

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

```c
DRM_DEV_DEBUG_DRIVER(dev, fmt, ...)
```

Debug output for vendor specific part of the driver

**Parameters**

- `dev`: device pointer
- `fmt`: `printf()` like format string.
- `...`: variable arguments

**NOTE**

this is deprecated in favor of `drm_dbg()` or `dev_dbg()`.

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

```c
DRM_DEV_DEBUG_KMS(dev, fmt, ...)
```

Debug output for modesetting code

**Parameters**

- `dev`: device pointer
- `fmt`: `printf()` like format string.
- `...`: variable arguments

**NOTE**

this is deprecated in favor of `drm_dbg_kms()`.



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

```c
void drm_puts(struct drm_printer *p, const char *str)
```

print a const string to a [`drm_printer`](#c-struct-drm_printer) stream

**Parameters**

- `struct drm_printer *p`: the `drm` printer
- `const char *str`: const string

**Description**

Allow [`drm_printer`](#c-struct-drm_printer) types that have a constant string
option to use it.

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

```c
void drm_printf(struct drm_printer *p, const char *f, ...)
```

print to a [`drm_printer`](#c-struct-drm_printer) stream

**Parameters**

- `struct drm_printer *p`: the [`drm_printer`](#c-struct-drm_printer)
- `const char *f`: format string
- `...`: variable arguments

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

```c
void drm_print_bits(struct drm_printer *p, unsigned long value, const char * const bits[], unsigned int nbits)
```

print bits to a [`drm_printer`](#c-struct-drm_printer) stream

**Parameters**

- `struct drm_printer *p`: the [`drm_printer`](#c-struct-drm_printer)
- `unsigned long value`: field value.
- `const char * const bits[]`: Array with bit names.
- `unsigned int nbits`: Size of bit names array.

**Description**

Print bits (in flag fields for example) in human readable form.

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

```c
void drm_print_regset32(struct drm_printer *p, struct debugfs_regset32 *regset)
```

print the contents of registers to a [`drm_printer`](#c-struct-drm_printer) stream.

**Parameters**

- `struct drm_printer *p`: the `drm` printer
- `struct debugfs_regset32 *regset`: the list of registers to print.

**Description**

Often in driver debug, it's useful to be able to either capture the
contents of registers in the steady state using debugfs or at
specific points during operation.  This lets the driver have a
single list of registers for both.

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

```c
void drm_print_hex_dump(struct drm_printer *p, const char *prefix, const u8 *buf, size_t len)
```

print a hex dump to a [`drm_printer`](#c-struct-drm_printer) stream

**Parameters**

- `struct drm_printer *p`: The [`drm_printer`](#c-struct-drm_printer)
- `const char *prefix`: Prefix for each line, may be NULL for no prefix
- `const u8 *buf`: Buffer to dump
- `size_t len`: Length of buffer

**Description**

Print hex dump to [`drm_printer`](#c-struct-drm_printer), with 16 space-separated hex bytes per line,
optionally with a prefix on each line. No separator is added after prefix.


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

### Utilities


Macros and inline functions that does not naturally belong in other places



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

```c
bool drm_can_sleep(void)
```

returns true if currently okay to sleep

**Parameters**

- `void`: no arguments

**Description**

This function shall not be used in new code.
The check for running in atomic context may not work - see linux/preempt.h.

FIXME: All users of drm_can_sleep should be removed (see todo.rst)

**Return**

False if kgdb is active, we are in atomic context or irqs are disabled.


<a id="rst-unit-testing"></a>

## Unit testing

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

### KUnit

KUnit (Kernel unit testing framework) provides a common framework for unit tests within the Linux kernel.

This section covers the specifics for the DRM subsystem. For general information about KUnit, please refer to [Documentation/dev-tools/kunit/start.rst](/kernel/development/dev-tools/kunit/start.md).

<a id="rst-how-to-run-the-tests"></a>

#### How to run the tests?

In order to facilitate running the test suite, a configuration file is present in `drivers/gpu/drm/tests/.kunitconfig`. It can be used by `kunit.py` as follows:



```bash
$ ./tools/testing/kunit/kunit.py run --kunitconfig=drivers/gpu/drm/tests \
        --kconfig_add CONFIG_VIRTIO_UML=y \
        --kconfig_add CONFIG_UML_PCI_OVER_VIRTIO=y
```

> [!NOTE]
>
> The configuration included in `.kunitconfig` should be as generic as possible. `CONFIG_VIRTIO_UML` and `CONFIG_UML_PCI_OVER_VIRTIO` are not included in it because they are only required for User Mode Linux.

<a id="rst-kunit-coverage-rules"></a>

#### KUnit Coverage Rules

KUnit support is gradually added to the DRM framework and helpers. There's no general requirement for the framework and helpers to have KUnit tests at the moment. However, patches that are affecting a function or helper already covered by KUnit tests must provide tests if the change calls for one.

<a id="rst-legacy-support-code"></a>

## Legacy Support Code

The section very briefly covers some of the old legacy support code which is only used by old DRM drivers which have done a so-called shadow-attach to the underlying device instead of registering as a real driver. This also includes some of the old generic buffer management and command submission code. Do not use any of this in new and modern drivers.

<a id="rst-legacy-suspend-resume"></a>

### Legacy Suspend/Resume

The DRM core provides some suspend/resume code, but drivers wanting full suspend/resume support should provide save() and restore() functions. These are called at suspend, hibernate, or resume time, and should perform any state save or restore required by your device across suspend or hibernate states.

int (\*suspend) (struct drm_device \*, pm_message_t state); int (\*resume) (struct drm_device \*); Those are legacy suspend and resume methods which *only* work with the legacy shadow-attach driver registration functions. New driver should use the power management interface provided by their bus type (usually through the `struct device_driver <device_driver>` dev_pm_ops) and set these methods to NULL.

<a id="rst-legacy-dma-services"></a>

### Legacy DMA Services

This should cover how DMA mapping etc. is supported by the core. These functions are deprecated and should not be used.

---

# Mode Setting Helper Functions

_Peios Kernel / Hardware and drivers / Graphics_

> The DRM subsystem aims for a strong separation between core code and helper libraries. Core code takes care of general setup and teardown and decoding userspace requests to kernel internal objects. Everything else is handled by a large set…

<a id="rst-mode-setting-helper-functions"></a>

The DRM subsystem aims for a strong separation between core code and helper libraries. Core code takes care of general setup and teardown and decoding userspace requests to kernel internal objects. Everything else is handled by a large set of helper libraries, which can be combined freely to pick and choose for each driver what fits, and avoid shared code where special behaviour is needed.

This distinction between core code and helpers is especially strong in the modesetting code, where there's a shared userspace ABI for all drivers. This is in contrast to the render side, where pretty much everything (with very few exceptions) can be considered optional helper code.

There are a few areas these helpers can grouped into:

- Helpers to implement modesetting. The important ones here are the atomic helpers. Old drivers still often use the legacy CRTC helpers. They both share the same set of common helper vtables. For really simple drivers (anything that would have been a great fit in the deprecated fbdev subsystem) there's also the simple display pipe helpers.

- There's a big pile of helpers for handling outputs. First the generic bridge helpers for handling encoder and transcoder IP blocks. Second the panel helpers for handling panel-related information and logic. Plus then a big set of helpers for the various sink standards (DisplayPort, HDMI, MIPI DSI). Finally there's also generic helpers for handling output probing, and for dealing with EDIDs.

- The last group of helpers concerns itself with the frontend side of a display pipeline: Planes, handling rectangles for visibility checking and scissoring, flip queues and assorted bits.

<a id="rst-modeset-helper-reference-for-common-vtables"></a>

## Modeset Helper Reference for Common Vtables


The DRM mode setting helper functions are common code for drivers to use if
they wish.  Drivers are not forced to use this code in their
implementations but it would be useful if the code they do use at least
provides a consistent interface and operation to userspace. Therefore it is
highly recommended to use the provided helpers as much as possible.

Because there is only one pointer per modeset object to hold a vfunc table
for helper libraries they are by necessity shared among the different
helpers.

To make this clear all the helper vtables are pulled together in this location here.



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

helper operations for CRTCs

**Definition**

```c
struct drm_crtc_helper_funcs {
    void (*dpms)(struct drm_crtc *crtc, int mode);
    void (*prepare)(struct drm_crtc *crtc);
    void (*commit)(struct drm_crtc *crtc);
    enum drm_mode_status (*mode_valid)(struct drm_crtc *crtc, const struct drm_display_mode *mode);
    bool (*mode_fixup)(struct drm_crtc *crtc, const struct drm_display_mode *mode, struct drm_display_mode *adjusted_mode);
    int (*mode_set)(struct drm_crtc *crtc, struct drm_display_mode *mode, struct drm_display_mode *adjusted_mode, int x, int y, struct drm_framebuffer *old_fb);
    void (*mode_set_nofb)(struct drm_crtc *crtc);
    int (*mode_set_base)(struct drm_crtc *crtc, int x, int y, struct drm_framebuffer *old_fb);
    void (*disable)(struct drm_crtc *crtc);
    int (*atomic_check)(struct drm_crtc *crtc, struct drm_atomic_state *state);
    void (*atomic_begin)(struct drm_crtc *crtc, struct drm_atomic_state *state);
    void (*atomic_flush)(struct drm_crtc *crtc, struct drm_atomic_state *state);
    void (*atomic_enable)(struct drm_crtc *crtc, struct drm_atomic_state *state);
    void (*atomic_disable)(struct drm_crtc *crtc, struct drm_atomic_state *state);
    bool (*get_scanout_position)(struct drm_crtc *crtc, bool in_vblank_irq, int *vpos, int *hpos, ktime_t *stime, ktime_t *etime, const struct drm_display_mode *mode);
    bool (*handle_vblank_timeout)(struct drm_crtc *crtc);
};
```

**Members**

- `dpms`: Callback to control power levels on the CRTC.  If the mode passed in
  is unsupported, the provider must use the next lowest power level.
  This is used by the legacy CRTC helpers to implement DPMS
  functionality in [`drm_helper_connector_dpms()`](#c-drm_helper_connector_dpms).

  This callback is also used to disable a CRTC by calling it with
  DRM_MODE_DPMS_OFF if the **disable** hook isn't used.

  This callback is used by the legacy CRTC helpers.  Atomic helpers
  also support using this hook for enabling and disabling a CRTC to
  facilitate transitions to atomic, but it is deprecated. Instead
  **atomic_enable** and **atomic_disable** should be used.
- `prepare`: This callback should prepare the CRTC for a subsequent modeset, which
  in practice means the driver should disable the CRTC if it is
  running. Most drivers ended up implementing this by calling their
  **dpms** hook with DRM_MODE_DPMS_OFF.

  This callback is used by the legacy CRTC helpers.  Atomic helpers
  also support using this hook for disabling a CRTC to facilitate
  transitions to atomic, but it is deprecated. Instead **atomic_disable**
  should be used.
- `commit`: This callback should commit the new mode on the CRTC after a modeset,
  which in practice means the driver should enable the CRTC.  Most
  drivers ended up implementing this by calling their **dpms** hook with
  DRM_MODE_DPMS_ON.

  This callback is used by the legacy CRTC helpers.  Atomic helpers
  also support using this hook for enabling a CRTC to facilitate
  transitions to atomic, but it is deprecated. Instead **atomic_enable**
  should be used.
- `mode_valid`: This callback is used to check if a specific mode is valid in this
  crtc. This should be implemented if the crtc has some sort of
  restriction in the modes it can display. For example, a given crtc
  may be responsible to set a clock value. If the clock can not
  produce all the values for the available modes then this callback
  can be used to restrict the number of modes to only the ones that
  can be displayed.

  This hook is used by the probe helpers to filter the mode list in
  [`drm_helper_probe_single_connector_modes()`](#c-drm_helper_probe_single_connector_modes), and it is used by the
  atomic helpers to validate modes supplied by userspace in
  [`drm_atomic_helper_check_modeset()`](#c-drm_atomic_helper_check_modeset).

  This function is optional.

  NOTE:

  Since this function is both called from the check phase of an atomic
  commit, and the mode validation in the probe paths it is not allowed
  to look at anything else but the passed-in mode, and validate it
  against configuration-invariant hardware constraints. Any further
  limits which depend upon the configuration can only be checked in
  **mode_fixup** or **atomic_check**.

  RETURNS:

  drm_mode_status Enum
- `mode_fixup`: This callback is used to validate a mode. The parameter mode is the
  display mode that userspace requested, adjusted_mode is the mode the
  encoders need to be fed with. Note that this is the inverse semantics
  of the meaning for the [`drm_encoder`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_encoder) and [`drm_bridge_funcs.mode_fixup`](#c-struct-drm_bridge_funcs)
  vfunc. If the CRTC cannot support the requested conversion from mode
  to adjusted_mode it should reject the modeset. See also
  [`drm_crtc_state.adjusted_mode`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_crtc_state) for more details.

  This function is used by both legacy CRTC helpers and atomic helpers.
  With atomic helpers it is optional.

  NOTE:

  This function is called in the check phase of atomic modesets, which
  can be aborted for any reason (including on userspace's request to
  just check whether a configuration would be possible). Atomic drivers
  MUST NOT touch any persistent state (hardware or software) or data
  structures except the passed in adjusted_mode parameter.

  This is in contrast to the legacy CRTC helpers where this was
  allowed.

  Atomic drivers which need to inspect and adjust more state should
  instead use the **atomic_check** callback, but note that they're not
  perfectly equivalent: **mode_valid** is called from
  [`drm_atomic_helper_check_modeset()`](#c-drm_atomic_helper_check_modeset), but **atomic_check** is called from
  [`drm_atomic_helper_check_planes()`](#c-drm_atomic_helper_check_planes), because originally it was meant for
  plane update checks only.

  Also beware that userspace can request its own custom modes, neither
  core nor helpers filter modes to the list of probe modes reported by
  the GETCONNECTOR IOCTL and stored in [`drm_connector.modes`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_connector). To ensure
  that modes are filtered consistently put any CRTC constraints and
  limits checks into **mode_valid**.

  RETURNS:

  True if an acceptable configuration is possible, false if the modeset
  operation should be rejected.
- `mode_set`: This callback is used by the legacy CRTC helpers to set a new mode,
  position and framebuffer. Since it ties the primary plane to every
  mode change it is incompatible with universal plane support. And
  since it can't update other planes it's incompatible with atomic
  modeset support.

  This callback is only used by CRTC helpers and deprecated.

  RETURNS:

  0 on success or a negative error code on failure.
- `mode_set_nofb`: This callback is used to update the display mode of a CRTC without
  changing anything of the primary plane configuration. This fits the
  requirement of atomic and hence is used by the atomic helpers.

  Note that the display pipe is completely off when this function is
  called. Atomic drivers which need hardware to be running before they
  program the new display mode (e.g. because they implement runtime PM)
  should not use this hook. This is because the helper library calls
  this hook only once per mode change and not every time the display
  pipeline is suspended using either DPMS or the new "ACTIVE" property.
  Which means register values set in this callback might get reset when
  the CRTC is suspended, but not restored.  Such drivers should instead
  move all their CRTC setup into the **atomic_enable** callback.

  This callback is optional.
- `mode_set_base`: This callback is used by the legacy CRTC helpers to set a new
  framebuffer and scanout position. It is optional and used as an
  optimized fast-path instead of a full mode set operation with all the
  resulting flickering. If it is not present
  [`drm_crtc_helper_set_config()`](#c-drm_crtc_helper_set_config) will fall back to a full modeset, using
  the **mode_set** callback. Since it can't update other planes it's
  incompatible with atomic modeset support.

  This callback is only used by the CRTC helpers and deprecated.

  RETURNS:

  0 on success or a negative error code on failure.
- `disable`: This callback should be used to disable the CRTC. With the atomic
  drivers it is called after all encoders connected to this CRTC have
  been shut off already using their own
  [`drm_encoder_helper_funcs.disable`](#c-struct-drm_encoder_helper_funcs) hook. If that sequence is too
  simple drivers can just add their own hooks and call it from this
  CRTC callback here by looping over all encoders connected to it using
  `for_each_encoder_on_crtc()`.

  This hook is used both by legacy CRTC helpers and atomic helpers.
  Atomic drivers don't need to implement it if there's no need to
  disable anything at the CRTC level. To ensure that runtime PM
  handling (using either DPMS or the new "ACTIVE" property) works
  **disable** must be the inverse of **atomic_enable** for atomic drivers.
  Atomic drivers should consider to use **atomic_disable** instead of
  this one.

  NOTE:

  With legacy CRTC helpers there's a big semantic difference between
  **disable** and other hooks (like **prepare** or **dpms**) used to shut down a
  CRTC: **disable** is only called when also logically disabling the
  display pipeline and needs to release any resources acquired in
  **mode_set** (like shared PLLs, or again release pinned framebuffers).

  Therefore **disable** must be the inverse of **mode_set** plus **commit** for
  drivers still using legacy CRTC helpers, which is different from the
  rules under atomic.
- `atomic_check`: Drivers should check plane-update related CRTC constraints in this
  hook. They can also check mode related limitations but need to be
  aware of the calling order, since this hook is used by
  [`drm_atomic_helper_check_planes()`](#c-drm_atomic_helper_check_planes) whereas the preparations needed to
  check output routing and the display mode is done in
  [`drm_atomic_helper_check_modeset()`](#c-drm_atomic_helper_check_modeset). Therefore drivers that want to
  check output routing and display mode constraints in this callback
  must ensure that [`drm_atomic_helper_check_modeset()`](#c-drm_atomic_helper_check_modeset) has been called
  beforehand. This is calling order used by the default helper
  implementation in [`drm_atomic_helper_check()`](#c-drm_atomic_helper_check).

  When using [`drm_atomic_helper_check_planes()`](#c-drm_atomic_helper_check_planes) this hook is called
  after the [`drm_plane_helper_funcs.atomic_check`](#c-struct-drm_plane_helper_funcs) hook for planes, which
  allows drivers to assign shared resources requested by planes in this
  callback here. For more complicated dependencies the driver can call
  the provided check helpers multiple times until the computed state
  has a final configuration and everything has been checked.

  This function is also allowed to inspect any other object's state and
  can add more state objects to the atomic commit if needed. Care must
  be taken though to ensure that state check and compute functions for
  these added states are all called, and derived state in other objects
  all updated. Again the recommendation is to just call check helpers
  until a maximal configuration is reached.

  This callback is used by the atomic modeset helpers, but it is
  optional.

  NOTE:

  This function is called in the check phase of an atomic update. The
  driver is not allowed to change anything outside of the free-standing
  state object passed-in.

  Also beware that userspace can request its own custom modes, neither
  core nor helpers filter modes to the list of probe modes reported by
  the GETCONNECTOR IOCTL and stored in [`drm_connector.modes`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_connector). To ensure
  that modes are filtered consistently put any CRTC constraints and
  limits checks into **mode_valid**.

  RETURNS:

  0 on success, -EINVAL if the state or the transition can't be
  supported, -ENOMEM on memory allocation failure and -EDEADLK if an
  attempt to obtain another state object ran into a [`drm_modeset_lock`](/kernel/hardware/gpu/drm-kms.md#c-drm_modeset_lock)
  deadlock.
- `atomic_begin`: Drivers should prepare for an atomic update of multiple planes on
  a CRTC in this hook. Depending upon hardware this might be vblank
  evasion, blocking updates by setting bits or doing preparatory work
  for e.g. manual update display.

  This hook is called before any plane commit functions are called.

  Note that the power state of the display pipe when this function is
  called depends upon the exact helpers and calling sequence the driver
  has picked. See [`drm_atomic_helper_commit_planes()`](#c-drm_atomic_helper_commit_planes) for a discussion of
  the tradeoffs and variants of plane commit helpers.

  This callback is used by the atomic modeset helpers, but it is
  optional.
- `atomic_flush`: Drivers should finalize an atomic update of multiple planes on
  a CRTC in this hook. Depending upon hardware this might include
  checking that vblank evasion was successful, unblocking updates by
  setting bits or setting the GO bit to flush out all updates.

  Simple hardware or hardware with special requirements can commit and
  flush out all updates for all planes from this hook and forgo all the
  other commit hooks for plane updates.

  This hook is called after any plane commit functions are called.

  Note that the power state of the display pipe when this function is
  called depends upon the exact helpers and calling sequence the driver
  has picked. See [`drm_atomic_helper_commit_planes()`](#c-drm_atomic_helper_commit_planes) for a discussion of
  the tradeoffs and variants of plane commit helpers.

  This callback is used by the atomic modeset helpers, but it is
  optional.
- `atomic_enable`: This callback should be used to enable the CRTC. With the atomic
  drivers it is called before all encoders connected to this CRTC are
  enabled through the encoder's own [`drm_encoder_helper_funcs.enable`](#c-struct-drm_encoder_helper_funcs)
  hook.  If that sequence is too simple drivers can just add their own
  hooks and call it from this CRTC callback here by looping over all
  encoders connected to it using `for_each_encoder_on_crtc()`.

  This hook is used only by atomic helpers, for symmetry with
  **atomic_disable**. Atomic drivers don't need to implement it if there's
  no need to enable anything at the CRTC level. To ensure that runtime
  PM handling (using either DPMS or the new "ACTIVE" property) works
  **atomic_enable** must be the inverse of **atomic_disable** for atomic
  drivers.

  This function is optional.
- `atomic_disable`: This callback should be used to disable the CRTC. With the atomic
  drivers it is called after all encoders connected to this CRTC have
  been shut off already using their own
  [`drm_encoder_helper_funcs.disable`](#c-struct-drm_encoder_helper_funcs) hook. If that sequence is too
  simple drivers can just add their own hooks and call it from this
  CRTC callback here by looping over all encoders connected to it using
  `for_each_encoder_on_crtc()`.

  This hook is used only by atomic helpers. Atomic drivers don't
  need to implement it if there's no need to disable anything at the
  CRTC level.

  This function is optional.
- `get_scanout_position`: Called by vblank timestamping code.

  Returns the current display scanout position from a CRTC and an
  optional accurate `ktime_get()` timestamp of when the position was
  measured. Note that this is a helper callback which is only used
  if a driver uses [`drm_crtc_vblank_helper_get_vblank_timestamp()`](/kernel/hardware/gpu/drm-kms.md#c-drm_crtc_vblank_helper_get_vblank_timestamp)
  for the **drm_crtc_funcs.get_vblank_timestamp** callback.

  Parameters:

  - crtc:
    The CRTC.
  - in_vblank_irq:
    True when called from [`drm_crtc_handle_vblank()`](/kernel/hardware/gpu/drm-kms.md#c-drm_crtc_handle_vblank). Some drivers
    need to apply some workarounds for gpu-specific vblank irq
    quirks if the flag is set.
  - vpos:
    Target location for current vertical scanout position.
  - hpos:
    Target location for current horizontal scanout position.
  - stime:
    Target location for timestamp taken immediately before
    scanout position query. Can be NULL to skip timestamp.
  - etime:
    Target location for timestamp taken immediately after
    scanout position query. Can be NULL to skip timestamp.
  - mode:
    Current display timings.

  Returns vpos as a positive number while in active scanout area.
  Returns vpos as a negative number inside vblank, counting the number
  of scanlines to go until end of vblank, e.g., -1 means "one scanline
  until start of active scanout / end of vblank."

  Returns:

  True on success, false if a reliable scanout position counter could
  not be read out.
- `handle_vblank_timeout`: Handles timeouts of the vblank timer.

  Called by CRTC's the vblank timer on each timeout. Semantics is
  equivalient to [`drm_crtc_handle_vblank()`](/kernel/hardware/gpu/drm-kms.md#c-drm_crtc_handle_vblank). Implementations should
  invoke [`drm_crtc_handle_vblank()`](/kernel/hardware/gpu/drm-kms.md#c-drm_crtc_handle_vblank) as part of processing the timeout.

  This callback is optional. If unset, the vblank timer invokes
  [`drm_crtc_handle_vblank()`](/kernel/hardware/gpu/drm-kms.md#c-drm_crtc_handle_vblank) directly.

**Description**

These hooks are used by the legacy CRTC helpers and the new atomic
modesetting helpers.

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

```c
void drm_crtc_helper_add(struct drm_crtc *crtc, const struct drm_crtc_helper_funcs *funcs)
```

sets the helper vtable for a crtc

**Parameters**

- `struct drm_crtc *crtc`: DRM CRTC
- `const struct drm_crtc_helper_funcs *funcs`: helper vtable to set for **crtc**

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

helper operations for encoders

**Definition**

```c
struct drm_encoder_helper_funcs {
    void (*dpms)(struct drm_encoder *encoder, int mode);
    enum drm_mode_status (*mode_valid)(struct drm_encoder *crtc, const struct drm_display_mode *mode);
    bool (*mode_fixup)(struct drm_encoder *encoder, const struct drm_display_mode *mode, struct drm_display_mode *adjusted_mode);
    void (*prepare)(struct drm_encoder *encoder);
    void (*commit)(struct drm_encoder *encoder);
    void (*mode_set)(struct drm_encoder *encoder, struct drm_display_mode *mode, struct drm_display_mode *adjusted_mode);
    void (*atomic_mode_set)(struct drm_encoder *encoder, struct drm_crtc_state *crtc_state, struct drm_connector_state *conn_state);
    enum drm_connector_status (*detect)(struct drm_encoder *encoder, struct drm_connector *connector);
    void (*atomic_disable)(struct drm_encoder *encoder, struct drm_atomic_state *state);
    void (*atomic_enable)(struct drm_encoder *encoder, struct drm_atomic_state *state);
    void (*disable)(struct drm_encoder *encoder);
    void (*enable)(struct drm_encoder *encoder);
    int (*atomic_check)(struct drm_encoder *encoder, struct drm_crtc_state *crtc_state, struct drm_connector_state *conn_state);
};
```

**Members**

- `dpms`: Callback to control power levels on the encoder.  If the mode passed in
  is unsupported, the provider must use the next lowest power level.
  This is used by the legacy encoder helpers to implement DPMS
  functionality in [`drm_helper_connector_dpms()`](#c-drm_helper_connector_dpms).

  This callback is also used to disable an encoder by calling it with
  DRM_MODE_DPMS_OFF if the **disable** hook isn't used.

  This callback is used by the legacy CRTC helpers.  Atomic helpers
  also support using this hook for enabling and disabling an encoder to
  facilitate transitions to atomic, but it is deprecated. Instead
  **enable** and **disable** should be used.
- `mode_valid`: This callback is used to check if a specific mode is valid in this
  encoder. This should be implemented if the encoder has some sort
  of restriction in the modes it can display. For example, a given
  encoder may be responsible to set a clock value. If the clock can
  not produce all the values for the available modes then this callback
  can be used to restrict the number of modes to only the ones that
  can be displayed.

  This hook is used by the probe helpers to filter the mode list in
  [`drm_helper_probe_single_connector_modes()`](#c-drm_helper_probe_single_connector_modes), and it is used by the
  atomic helpers to validate modes supplied by userspace in
  [`drm_atomic_helper_check_modeset()`](#c-drm_atomic_helper_check_modeset).

  This function is optional.

  NOTE:

  Since this function is both called from the check phase of an atomic
  commit, and the mode validation in the probe paths it is not allowed
  to look at anything else but the passed-in mode, and validate it
  against configuration-invariant hardware constraints. Any further
  limits which depend upon the configuration can only be checked in
  **mode_fixup** or **atomic_check**.

  RETURNS:

  drm_mode_status Enum
- `mode_fixup`: This callback is used to validate and adjust a mode. The parameter
  mode is the display mode that should be fed to the next element in
  the display chain, either the final [`drm_connector`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_connector) or a [`drm_bridge`](#c-struct-drm_bridge).
  The parameter adjusted_mode is the input mode the encoder requires. It
  can be modified by this callback and does not need to match mode. See
  also [`drm_crtc_state.adjusted_mode`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_crtc_state) for more details.

  This function is used by both legacy CRTC helpers and atomic helpers.
  This hook is optional.

  NOTE:

  This function is called in the check phase of atomic modesets, which
  can be aborted for any reason (including on userspace's request to
  just check whether a configuration would be possible). Atomic drivers
  MUST NOT touch any persistent state (hardware or software) or data
  structures except the passed in adjusted_mode parameter.

  This is in contrast to the legacy CRTC helpers where this was
  allowed.

  Atomic drivers which need to inspect and adjust more state should
  instead use the **atomic_check** callback. If **atomic_check** is used,
  this hook isn't called since **atomic_check** allows a strict superset
  of the functionality of **mode_fixup**.

  Also beware that userspace can request its own custom modes, neither
  core nor helpers filter modes to the list of probe modes reported by
  the GETCONNECTOR IOCTL and stored in [`drm_connector.modes`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_connector). To ensure
  that modes are filtered consistently put any encoder constraints and
  limits checks into **mode_valid**.

  RETURNS:

  True if an acceptable configuration is possible, false if the modeset
  operation should be rejected.
- `prepare`: This callback should prepare the encoder for a subsequent modeset,
  which in practice means the driver should disable the encoder if it
  is running. Most drivers ended up implementing this by calling their
  **dpms** hook with DRM_MODE_DPMS_OFF.

  This callback is used by the legacy CRTC helpers.  Atomic helpers
  also support using this hook for disabling an encoder to facilitate
  transitions to atomic, but it is deprecated. Instead **disable** should
  be used.
- `commit`: This callback should commit the new mode on the encoder after a modeset,
  which in practice means the driver should enable the encoder.  Most
  drivers ended up implementing this by calling their **dpms** hook with
  DRM_MODE_DPMS_ON.

  This callback is used by the legacy CRTC helpers.  Atomic helpers
  also support using this hook for enabling an encoder to facilitate
  transitions to atomic, but it is deprecated. Instead **enable** should
  be used.
- `mode_set`: This callback is used to update the display mode of an encoder.

  Note that the display pipe is completely off when this function is
  called. Drivers which need hardware to be running before they program
  the new display mode (because they implement runtime PM) should not
  use this hook, because the helper library calls it only once and not
  every time the display pipeline is suspend using either DPMS or the
  new "ACTIVE" property. Such drivers should instead move all their
  encoder setup into the **enable** callback.

  This callback is used both by the legacy CRTC helpers and the atomic
  modeset helpers. It is optional in the atomic helpers.

  NOTE:

  If the driver uses the atomic modeset helpers and needs to inspect
  the connector state or connector display info during mode setting,
  **atomic_mode_set** can be used instead.
- `atomic_mode_set`: This callback is used to update the display mode of an encoder.

  Note that the display pipe is completely off when this function is
  called. Drivers which need hardware to be running before they program
  the new display mode (because they implement runtime PM) should not
  use this hook, because the helper library calls it only once and not
  every time the display pipeline is suspended using either DPMS or the
  new "ACTIVE" property. Such drivers should instead move all their
  encoder setup into the **enable** callback.

  This callback is used by the atomic modeset helpers in place of the
  **mode_set** callback, if set by the driver. It is optional and should
  be used instead of **mode_set** if the driver needs to inspect the
  connector state or display info, since there is no direct way to
  go from the encoder to the current connector.
- `detect`: This callback can be used by drivers who want to do detection on the
  encoder object instead of in connector functions.

  It is not used by any helper and therefore has purely driver-specific
  semantics. New drivers shouldn't use this and instead just implement
  their own private callbacks.

  FIXME:

  This should just be converted into a pile of driver vfuncs.
  Currently radeon, amdgpu and nouveau are using it.
- `atomic_disable`: This callback should be used to disable the encoder. With the atomic
  drivers it is called before this encoder's CRTC has been shut off
  using their own [`drm_crtc_helper_funcs.atomic_disable`](#c-struct-drm_crtc_helper_funcs) hook. If that
  sequence is too simple drivers can just add their own driver private
  encoder hooks and call them from CRTC's callback by looping over all
  encoders connected to it using `for_each_encoder_on_crtc()`.

  This callback is a variant of **disable** that provides the atomic state
  to the driver. If **atomic_disable** is implemented, **disable** is not
  called by the helpers.

  This hook is only used by atomic helpers. Atomic drivers don't need
  to implement it if there's no need to disable anything at the encoder
  level. To ensure that runtime PM handling (using either DPMS or the
  new "ACTIVE" property) works **atomic_disable** must be the inverse of
  **atomic_enable**.
- `atomic_enable`: This callback should be used to enable the encoder. It is called
  after this encoder's CRTC has been enabled using their own
  [`drm_crtc_helper_funcs.atomic_enable`](#c-struct-drm_crtc_helper_funcs) hook. If that sequence is
  too simple drivers can just add their own driver private encoder
  hooks and call them from CRTC's callback by looping over all encoders
  connected to it using `for_each_encoder_on_crtc()`.

  This callback is a variant of **enable** that provides the atomic state
  to the driver. If **atomic_enable** is implemented, **enable** is not
  called by the helpers.

  This hook is only used by atomic helpers, it is the opposite of
  **atomic_disable**. Atomic drivers don't need to implement it if there's
  no need to enable anything at the encoder level. To ensure that
  runtime PM handling works **atomic_enable** must be the inverse of
  **atomic_disable**.
- `disable`: This callback should be used to disable the encoder. With the atomic
  drivers it is called before this encoder's CRTC has been shut off
  using their own [`drm_crtc_helper_funcs.disable`](#c-struct-drm_crtc_helper_funcs) hook.  If that
  sequence is too simple drivers can just add their own driver private
  encoder hooks and call them from CRTC's callback by looping over all
  encoders connected to it using `for_each_encoder_on_crtc()`.

  This hook is used both by legacy CRTC helpers and atomic helpers.
  Atomic drivers don't need to implement it if there's no need to
  disable anything at the encoder level. To ensure that runtime PM
  handling (using either DPMS or the new "ACTIVE" property) works
  **disable** must be the inverse of **enable** for atomic drivers.

  For atomic drivers also consider **atomic_disable** and save yourself
  from having to read the NOTE below!

  NOTE:

  With legacy CRTC helpers there's a big semantic difference between
  **disable** and other hooks (like **prepare** or **dpms**) used to shut down a
  encoder: **disable** is only called when also logically disabling the
  display pipeline and needs to release any resources acquired in
  **mode_set** (like shared PLLs, or again release pinned framebuffers).

  Therefore **disable** must be the inverse of **mode_set** plus **commit** for
  drivers still using legacy CRTC helpers, which is different from the
  rules under atomic.
- `enable`: This callback should be used to enable the encoder. With the atomic
  drivers it is called after this encoder's CRTC has been enabled using
  their own [`drm_crtc_helper_funcs.enable`](#c-struct-drm_crtc_helper_funcs) hook.  If that sequence is
  too simple drivers can just add their own driver private encoder
  hooks and call them from CRTC's callback by looping over all encoders
  connected to it using `for_each_encoder_on_crtc()`.

  This hook is only used by atomic helpers, it is the opposite of
  **disable**. Atomic drivers don't need to implement it if there's no
  need to enable anything at the encoder level. To ensure that
  runtime PM handling (using either DPMS or the new "ACTIVE" property)
  works **enable** must be the inverse of **disable** for atomic drivers.
- `atomic_check`: This callback is used to validate encoder state for atomic drivers.
  Since the encoder is the object connecting the CRTC and connector it
  gets passed both states, to be able to validate interactions and
  update the CRTC to match what the encoder needs for the requested
  connector.

  Since this provides a strict superset of the functionality of
  **mode_fixup** (the requested and adjusted modes are both available
  through the passed in [`struct drm_crtc_state`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_crtc_state)) **mode_fixup** is not
  called when **atomic_check** is implemented.

  This function is used by the atomic helpers, but it is optional.

  NOTE:

  This function is called in the check phase of an atomic update. The
  driver is not allowed to change anything outside of the free-standing
  state objects passed-in or assembled in the overall [`drm_atomic_state`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_atomic_state)
  update tracking structure.

  Also beware that userspace can request its own custom modes, neither
  core nor helpers filter modes to the list of probe modes reported by
  the GETCONNECTOR IOCTL and stored in [`drm_connector.modes`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_connector). To ensure
  that modes are filtered consistently put any encoder constraints and
  limits checks into **mode_valid**.

  RETURNS:

  0 on success, -EINVAL if the state or the transition can't be
  supported, -ENOMEM on memory allocation failure and -EDEADLK if an
  attempt to obtain another state object ran into a [`drm_modeset_lock`](/kernel/hardware/gpu/drm-kms.md#c-drm_modeset_lock)
  deadlock.

**Description**

These hooks are used by the legacy CRTC helpers and the new atomic
modesetting helpers.

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

```c
void drm_encoder_helper_add(struct drm_encoder *encoder, const struct drm_encoder_helper_funcs *funcs)
```

sets the helper vtable for an encoder

**Parameters**

- `struct drm_encoder *encoder`: DRM encoder
- `const struct drm_encoder_helper_funcs *funcs`: helper vtable to set for **encoder**

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

helper operations for connectors

**Definition**

```c
struct drm_connector_helper_funcs {
    int (*get_modes)(struct drm_connector *connector);
    int (*detect_ctx)(struct drm_connector *connector, struct drm_modeset_acquire_ctx *ctx, bool force);
    enum drm_mode_status (*mode_valid)(struct drm_connector *connector, const struct drm_display_mode *mode);
    int (*mode_valid_ctx)(struct drm_connector *connector, const struct drm_display_mode *mode, struct drm_modeset_acquire_ctx *ctx, enum drm_mode_status *status);
    struct drm_encoder *(*best_encoder)(struct drm_connector *connector);
    struct drm_encoder *(*atomic_best_encoder)(struct drm_connector *connector, struct drm_atomic_state *state);
    int (*atomic_check)(struct drm_connector *connector, struct drm_atomic_state *state);
    void (*atomic_commit)(struct drm_connector *connector, struct drm_atomic_state *state);
    int (*prepare_writeback_job)(struct drm_writeback_connector *connector, struct drm_writeback_job *job);
    void (*cleanup_writeback_job)(struct drm_writeback_connector *connector, struct drm_writeback_job *job);
    void (*enable_hpd)(struct drm_connector *connector);
    void (*disable_hpd)(struct drm_connector *connector);
};
```

**Members**

- `get_modes`: This function should fill in all modes currently valid for the sink
  into the [`drm_connector.probed_modes`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_connector) list. It should also update the
  EDID property by calling [`drm_connector_update_edid_property()`](#c-drm_connector_update_edid_property).

  The usual way to implement this is to cache the EDID retrieved in the
  probe callback somewhere in the driver-private connector structure.
  In this function drivers then parse the modes in the EDID and add
  them by calling [`drm_add_edid_modes()`](#c-drm_add_edid_modes). But connectors that drive a
  fixed panel can also manually add specific modes using
  [`drm_mode_probed_add()`](/kernel/hardware/gpu/drm-kms.md#c-drm_mode_probed_add). Drivers which manually add modes should also
  make sure that the [`drm_connector.display_info`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_connector),
  [`drm_connector.width_mm`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_connector) and [`drm_connector.height_mm`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_connector) fields are
  filled in.

  Note that the caller function will automatically add standard VESA
  DMT modes up to 1024x768 if the .`get_modes()` helper operation returns
  no mode and if the connector status is connector_status_connected or
  connector_status_unknown. There is no need to call
  [`drm_add_modes_noedid()`](#c-drm_add_modes_noedid) manually in that case.

  Virtual drivers that just want some standard VESA mode with a given
  resolution can call [`drm_add_modes_noedid()`](#c-drm_add_modes_noedid), and mark the preferred
  one using [`drm_set_preferred_mode()`](/kernel/hardware/gpu/drm-kms.md#c-drm_set_preferred_mode).

  This function is only called after the **detect** hook has indicated
  that a sink is connected and when the EDID isn't overridden through
  sysfs or the kernel commandline.

  This callback is used by the probe helpers in e.g.
  [`drm_helper_probe_single_connector_modes()`](#c-drm_helper_probe_single_connector_modes).

  To avoid races with concurrent connector state updates, the helper
  libraries always call this with the [`drm_mode_config.connection_mutex`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_mode_config)
  held. Because of this it's safe to inspect [`drm_connector->state`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_connector).

  RETURNS:

  The number of modes added by calling [`drm_mode_probed_add()`](/kernel/hardware/gpu/drm-kms.md#c-drm_mode_probed_add). Return 0
  on failures (no modes) instead of negative error codes.
- `detect_ctx`: Check to see if anything is attached to the connector. The parameter
  force is set to false whilst polling, true when checking the
  connector due to a user request. force can be used by the driver to
  avoid expensive, destructive operations during automated probing.

  This callback is optional, if not implemented the connector will be
  considered as always being attached.

  This is the atomic version of [`drm_connector_funcs.detect`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_connector_funcs).

  To avoid races against concurrent connector state updates, the
  helper libraries always call this with ctx set to a valid context,
  and [`drm_mode_config.connection_mutex`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_mode_config) will always be locked with
  the ctx parameter set to this ctx. This allows taking additional
  locks as required.

  RETURNS:

  [`drm_connector_status`](/kernel/hardware/gpu/drm-kms.md#c-enum-drm_connector_status) indicating the connector's status,
  or the error code returned by [`drm_modeset_lock()`](/kernel/hardware/gpu/drm-kms.md#c-drm_modeset_lock), -EDEADLK.
- `mode_valid`: Callback to validate a mode for a connector, irrespective of the
  specific display configuration.

  This callback is used by the probe helpers to filter the mode list
  (which is usually derived from the EDID data block from the sink).
  See e.g. [`drm_helper_probe_single_connector_modes()`](#c-drm_helper_probe_single_connector_modes).

  This function is optional.

  NOTE:

  This only filters the mode list supplied to userspace in the
  GETCONNECTOR IOCTL. Compared to [`drm_encoder_helper_funcs.mode_valid`](#c-struct-drm_encoder_helper_funcs),
  [`drm_crtc_helper_funcs.mode_valid`](#c-struct-drm_crtc_helper_funcs) and [`drm_bridge_funcs.mode_valid`](#c-struct-drm_bridge_funcs),
  which are also called by the atomic helpers from
  [`drm_atomic_helper_check_modeset()`](#c-drm_atomic_helper_check_modeset). This allows userspace to force and
  ignore sink constraint (like the pixel clock limits in the screen's
  EDID), which is useful for e.g. testing, or working around a broken
  EDID. Any source hardware constraint (which always need to be
  enforced) therefore should be checked in one of the above callbacks,
  and not this one here.

  To avoid races with concurrent connector state updates, the helper
  libraries always call this with the [`drm_mode_config.connection_mutex`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_mode_config)
  held. Because of this it's safe to inspect [`drm_connector->state`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_connector).

  RETURNS:

  Either [`drm_mode_status.MODE_OK`](/kernel/hardware/gpu/drm-kms.md#c-enum-drm_mode_status) or one of the failure reasons in [`enum drm_mode_status`](/kernel/hardware/gpu/drm-kms.md#c-enum-drm_mode_status).
- `mode_valid_ctx`: Callback to validate a mode for a connector, irrespective of the
  specific display configuration.

  This callback is used by the probe helpers to filter the mode list
  (which is usually derived from the EDID data block from the sink).
  See e.g. [`drm_helper_probe_single_connector_modes()`](#c-drm_helper_probe_single_connector_modes).

  This function is optional, and is the atomic version of
  [`drm_connector_helper_funcs.mode_valid`](#c-struct-drm_connector_helper_funcs).

  To allow for accessing the atomic state of modesetting objects, the
  helper libraries always call this with ctx set to a valid context,
  and [`drm_mode_config.connection_mutex`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_mode_config) will always be locked with
  the ctx parameter set to **ctx**. This allows for taking additional
  locks as required.

  Even though additional locks may be acquired, this callback is
  still expected not to take any constraints into account which would
  be influenced by the currently set display state - such constraints
  should be handled in the driver's atomic check. For example, if a
  connector shares display bandwidth with other connectors then it
  would be ok to validate the minimum bandwidth requirement of a mode
  against the maximum possible bandwidth of the connector. But it
  wouldn't be ok to take the current bandwidth usage of other
  connectors into account, as this would change depending on the
  display state.

  Returns:
  0 if [`drm_connector_helper_funcs.mode_valid_ctx`](#c-struct-drm_connector_helper_funcs) succeeded and wrote
  the [`enum drm_mode_status`](/kernel/hardware/gpu/drm-kms.md#c-enum-drm_mode_status) value to **status**, or a negative error
  code otherwise.
- `best_encoder`: This function should select the best encoder for the given connector.

  This function is used by both the atomic helpers (in the
  [`drm_atomic_helper_check_modeset()`](#c-drm_atomic_helper_check_modeset) function) and in the legacy CRTC
  helpers.

  NOTE:

  In atomic drivers this function is called in the check phase of an
  atomic update. The driver is not allowed to change or inspect
  anything outside of arguments passed-in. Atomic drivers which need to
  inspect dynamic configuration state should instead use
  **atomic_best_encoder**.

  You can leave this function to NULL if the connector is only
  attached to a single encoder. In this case, the core will call
  `drm_connector_get_single_encoder()` for you.

  RETURNS:

  Encoder that should be used for the given connector and connector
  state, or NULL if no suitable encoder exists. Note that the helpers
  will ensure that encoders aren't used twice, drivers should not check
  for this.
- `atomic_best_encoder`: This is the atomic version of **best_encoder** for atomic drivers which
  need to select the best encoder depending upon the desired
  configuration and can't select it statically.

  This function is used by [`drm_atomic_helper_check_modeset()`](#c-drm_atomic_helper_check_modeset).
  If it is not implemented, the core will fallback to **best_encoder**
  (or `drm_connector_get_single_encoder()` if **best_encoder** is NULL).

  NOTE:

  This function is called in the check phase of an atomic update. The
  driver is not allowed to change anything outside of the
  [`drm_atomic_state`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_atomic_state) update tracking structure passed in.

  RETURNS:

  Encoder that should be used for the given connector and connector
  state, or NULL if no suitable encoder exists. Note that the helpers
  will ensure that encoders aren't used twice, drivers should not check
  for this.
- `atomic_check`: This hook is used to validate connector state. This function is
  called from [`drm_atomic_helper_check_modeset`](#c-drm_atomic_helper_check_modeset), and is called when
  a connector property is set, or a modeset on the crtc is forced.

  Because [`drm_atomic_helper_check_modeset`](#c-drm_atomic_helper_check_modeset) may be called multiple times,
  this function should handle being called multiple times as well.

  This function is also allowed to inspect any other object's state and
  can add more state objects to the atomic commit if needed. Care must
  be taken though to ensure that state check and compute functions for
  these added states are all called, and derived state in other objects
  all updated. Again the recommendation is to just call check helpers
  until a maximal configuration is reached.

  NOTE:

  This function is called in the check phase of an atomic update. The
  driver is not allowed to change anything outside of the free-standing
  state objects passed-in or assembled in the overall [`drm_atomic_state`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_atomic_state)
  update tracking structure.

  RETURNS:

  0 on success, -EINVAL if the state or the transition can't be
  supported, -ENOMEM on memory allocation failure and -EDEADLK if an
  attempt to obtain another state object ran into a [`drm_modeset_lock`](/kernel/hardware/gpu/drm-kms.md#c-drm_modeset_lock)
  deadlock.
- `atomic_commit`: This hook is to be used by drivers implementing writeback connectors
  that need a point when to commit the writeback job to the hardware.
  The writeback_job to commit is available in the new connector state,
  in [`drm_connector_state.writeback_job`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_connector_state).

  This hook is optional.

  This callback is used by the atomic modeset helpers.
- `prepare_writeback_job`: As writeback jobs contain a framebuffer, drivers may need to
  prepare and clean them up the same way they can prepare and
  clean up framebuffers for planes. This optional connector operation
  is used to support the preparation of writeback jobs. The job
  prepare operation is called from [`drm_atomic_helper_prepare_planes()`](#c-drm_atomic_helper_prepare_planes)
  for struct [`drm_writeback_connector`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_writeback_connector) connectors only.

  This operation is optional.

  This callback is used by the atomic modeset helpers.
- `cleanup_writeback_job`: This optional connector operation is used to support the
  cleanup of writeback jobs. The job cleanup operation is called
  from the existing `drm_writeback_cleanup_job()` function, invoked
  both when destroying the job as part of an aborted commit, or when
  the job completes.

  This operation is optional.

  This callback is used by the atomic modeset helpers.
- `enable_hpd`: Enable hot-plug detection for the connector.

  This operation is optional.

  This callback is used by the [`drm_kms_helper_poll_enable()`](#c-drm_kms_helper_poll_enable) helpers.

  This operation does not need to perform any hpd state tracking as
  the DRM core handles that maintenance and ensures the calls to enable
  and disable hpd are balanced.
- `disable_hpd`: Disable hot-plug detection for the connector.

  This operation is optional.

  This callback is used by the [`drm_kms_helper_poll_disable()`](#c-drm_kms_helper_poll_disable) helpers.

  This operation does not need to perform any hpd state tracking as
  the DRM core handles that maintenance and ensures the calls to enable
  and disable hpd are balanced.

**Description**

These functions are used by the atomic and legacy modeset helpers and by the
probe helpers.

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

```c
void drm_connector_helper_add(struct drm_connector *connector, const struct drm_connector_helper_funcs *funcs)
```

sets the helper vtable for a connector

**Parameters**

- `struct drm_connector *connector`: DRM connector
- `const struct drm_connector_helper_funcs *funcs`: helper vtable to set for **connector**

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

helper operations for planes

**Definition**

```c
struct drm_plane_helper_funcs {
    int (*prepare_fb)(struct drm_plane *plane, struct drm_plane_state *new_state);
    void (*cleanup_fb)(struct drm_plane *plane, struct drm_plane_state *old_state);
    int (*begin_fb_access)(struct drm_plane *plane, struct drm_plane_state *new_plane_state);
    void (*end_fb_access)(struct drm_plane *plane, struct drm_plane_state *new_plane_state);
    int (*atomic_check)(struct drm_plane *plane, struct drm_atomic_state *state);
    void (*atomic_update)(struct drm_plane *plane, struct drm_atomic_state *state);
    void (*atomic_enable)(struct drm_plane *plane, struct drm_atomic_state *state);
    void (*atomic_disable)(struct drm_plane *plane, struct drm_atomic_state *state);
    int (*atomic_async_check)(struct drm_plane *plane, struct drm_atomic_state *state, bool flip);
    void (*atomic_async_update)(struct drm_plane *plane, struct drm_atomic_state *state);
    int (*get_scanout_buffer)(struct drm_plane *plane, struct drm_scanout_buffer *sb);
    void (*panic_flush)(struct drm_plane *plane);
};
```

**Members**

- `prepare_fb`: This hook is to prepare a framebuffer for scanout by e.g. pinning
  its backing storage or relocating it into a contiguous block of
  VRAM. Other possible preparatory work includes flushing caches.

  This function must not block for outstanding rendering, since it is
  called in the context of the atomic IOCTL even for async commits to
  be able to return any errors to userspace. Instead the recommended
  way is to fill out the [`drm_plane_state.fence`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_plane_state) of the passed-in
  [`drm_plane_state`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_plane_state). If the driver doesn't support native fences then
  equivalent functionality should be implemented through private
  members in the plane structure.

  For GEM drivers who neither have a **prepare_fb** nor **cleanup_fb** hook
  set [`drm_gem_plane_helper_prepare_fb()`](#c-drm_gem_plane_helper_prepare_fb) is called automatically to
  implement this. Other drivers which need additional plane processing
  can call [`drm_gem_plane_helper_prepare_fb()`](#c-drm_gem_plane_helper_prepare_fb) from their **prepare_fb**
  hook.

  The resources acquired in **prepare_fb** persist after the end of
  the atomic commit. Resources that can be release at the commit's end
  should be acquired in **begin_fb_access** and released in **end_fb_access**.
  For example, a GEM buffer's pin operation belongs into **prepare_fb** to
  keep the buffer pinned after the commit. But a vmap operation for
  shadow-plane helpers belongs into **begin_fb_access**, so that atomic
  helpers remove the mapping at the end of the commit.

  The helpers will call **cleanup_fb** with matching arguments for every
  successful call to this hook.

  This callback is used by the atomic modeset helpers, but it is
  optional. See **begin_fb_access** for preparing per-commit resources.

  RETURNS:

  0 on success or one of the following negative error codes allowed by
  the [`drm_mode_config_funcs.atomic_commit`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_mode_config_funcs) vfunc. When using helpers
  this callback is the only one which can fail an atomic commit,
  everything else must complete successfully.
- `cleanup_fb`: This hook is called to clean up any resources allocated for the given
  framebuffer and plane configuration in **prepare_fb**.

  This callback is used by the atomic modeset helpers, but it is
  optional.
- `begin_fb_access`: This hook prepares the plane for access during an atomic commit.
  In contrast to **prepare_fb**, resources acquired in **begin_fb_access**,
  are released at the end of the atomic commit in **end_fb_access**.

  For example, with shadow-plane helpers, the GEM buffer's vmap
  operation belongs into **begin_fb_access**, so that the buffer's
  memory will be unmapped at the end of the commit in **end_fb_access**.
  But a GEM buffer's pin operation belongs into **prepare_fb**
  to keep the buffer pinned after the commit.

  The callback is used by the atomic modeset helpers, but it is optional.
  See **end_fb_cleanup** for undoing the effects of **begin_fb_access** and
  **prepare_fb** for acquiring resources until the next pageflip.

  Returns:
  0 on success, or a negative errno code otherwise.
- `end_fb_access`: This hook cleans up resources allocated by **begin_fb_access**. It it called
  at the end of a commit for the new plane state.
- `atomic_check`: Drivers should check plane specific constraints in this hook.

  When using [`drm_atomic_helper_check_planes()`](#c-drm_atomic_helper_check_planes) plane's **atomic_check**
  hooks are called before the ones for CRTCs, which allows drivers to
  request shared resources that the CRTC controls here. For more
  complicated dependencies the driver can call the provided check helpers
  multiple times until the computed state has a final configuration and
  everything has been checked.

  This function is also allowed to inspect any other object's state and
  can add more state objects to the atomic commit if needed. Care must
  be taken though to ensure that state check and compute functions for
  these added states are all called, and derived state in other objects
  all updated. Again the recommendation is to just call check helpers
  until a maximal configuration is reached.

  This callback is used by the atomic modeset helpers, but it is
  optional.

  NOTE:

  This function is called in the check phase of an atomic update. The
  driver is not allowed to change anything outside of the
  [`drm_atomic_state`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_atomic_state) update tracking structure.

  RETURNS:

  0 on success, -EINVAL if the state or the transition can't be
  supported, -ENOMEM on memory allocation failure and -EDEADLK if an
  attempt to obtain another state object ran into a [`drm_modeset_lock`](/kernel/hardware/gpu/drm-kms.md#c-drm_modeset_lock)
  deadlock.
- `atomic_update`: Drivers should use this function to update the plane state.  This
  hook is called in-between the [`drm_crtc_helper_funcs.atomic_begin`](#c-struct-drm_crtc_helper_funcs) and
  drm_crtc_helper_funcs.atomic_flush callbacks.

  Note that the power state of the display pipe when this function is
  called depends upon the exact helpers and calling sequence the driver
  has picked. See [`drm_atomic_helper_commit_planes()`](#c-drm_atomic_helper_commit_planes) for a discussion of
  the tradeoffs and variants of plane commit helpers.

  This callback is used by the atomic modeset helpers, but it is optional.
- `atomic_enable`: Drivers should use this function to unconditionally enable a plane.
  This hook is called in-between the [`drm_crtc_helper_funcs.atomic_begin`](#c-struct-drm_crtc_helper_funcs)
  and drm_crtc_helper_funcs.atomic_flush callbacks. It is called after
  **atomic_update**, which will be called for all enabled planes. Drivers
  that use **atomic_enable** should set up a plane in **atomic_update** and
  afterwards enable the plane in **atomic_enable**. If a plane needs to be
  enabled before installing the scanout buffer, drivers can still do
  so in **atomic_update**.

  Note that the power state of the display pipe when this function is
  called depends upon the exact helpers and calling sequence the driver
  has picked. See [`drm_atomic_helper_commit_planes()`](#c-drm_atomic_helper_commit_planes) for a discussion of
  the tradeoffs and variants of plane commit helpers.

  This callback is used by the atomic modeset helpers, but it is
  optional. If implemented, **atomic_enable** should be the inverse of
  **atomic_disable**. Drivers that don't want to use either can still
  implement the complete plane update in **atomic_update**.
- `atomic_disable`: Drivers should use this function to unconditionally disable a plane.
  This hook is called in-between the
  [`drm_crtc_helper_funcs.atomic_begin`](#c-struct-drm_crtc_helper_funcs) and
  drm_crtc_helper_funcs.atomic_flush callbacks. It is an alternative to
  **atomic_update**, which will be called for disabling planes, too, if
  the **atomic_disable** hook isn't implemented.

  This hook is also useful to disable planes in preparation of a modeset,
  by calling [`drm_atomic_helper_disable_planes_on_crtc()`](#c-drm_atomic_helper_disable_planes_on_crtc) from the
  [`drm_crtc_helper_funcs.disable`](#c-struct-drm_crtc_helper_funcs) hook.

  Note that the power state of the display pipe when this function is
  called depends upon the exact helpers and calling sequence the driver
  has picked. See [`drm_atomic_helper_commit_planes()`](#c-drm_atomic_helper_commit_planes) for a discussion of
  the tradeoffs and variants of plane commit helpers.

  This callback is used by the atomic modeset helpers, but it is
  optional. It's intended to reverse the effects of **atomic_enable**.
- `atomic_async_check`: Drivers should set this function pointer to check if the plane's
  atomic state can be updated in a async fashion. Here async means
  "not vblank synchronized".

  This hook is called by `drm_atomic_async_check()` to establish if a
  given update can be committed asynchronously, that is, if it can
  jump ahead of the state currently queued for update.

  This function is also used by `drm_atomic_set_property()` to determine
  if the plane can be flipped in async. The flip flag is used to
  distinguish if the function is used for just the plane state or for a
  flip.

  RETURNS:

  Return 0 on success and any error returned indicates that the update
  can not be applied in asynchronous manner.
- `atomic_async_update`: Drivers should set this function pointer to perform asynchronous
  updates of planes, that is, jump ahead of the currently queued
  state and update the plane. Here async means "not vblank
  synchronized".

  This hook is called by [`drm_atomic_helper_async_commit()`](#c-drm_atomic_helper_async_commit).

  An async update will happen on legacy cursor updates. An async
  update won't happen if there is an outstanding commit modifying
  the same plane.

  When doing async_update drivers shouldn't replace the
  [`drm_plane_state`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_plane_state) but update the current one with the new plane
  configurations in the new plane_state.

  Drivers should also swap the framebuffers between current plane
  state ([`drm_plane.state`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_plane)) and new_state.
  This is required since cleanup for async commits is performed on
  the new state, rather than old state like for traditional commits.
  Since we want to give up the reference on the current (old) fb
  instead of our brand new one, swap them in the driver during the
  async commit.

  - FIXME:
    - It only works for single plane updates
    - Async Pageflips are not supported yet
    - Some hw might still scan out the old buffer until the next
      vblank, however we let go of the fb references as soon as
      we run this hook. For now drivers must implement their own workers
      for deferring if needed, until a common solution is created.
- `get_scanout_buffer`: Get the current scanout buffer, to display a message with drm_panic.
  The driver should do the minimum changes to provide a buffer,
  that can be used to display the panic screen. Currently only linear
  buffers are supported. Non-linear buffer support is on the TODO list.
  The device `dev.mode_config`.panic_lock is taken before calling this
  function, so you can safely access the `plane.state`
  It is called from a panic callback, and must follow its restrictions.
  Please look the documentation at [`drm_panic_trylock()`](/kernel/hardware/gpu/drm-kms.md#c-drm_panic_trylock) for an in-depth
  discussions of what's safe and what is not allowed.
  It's a best effort mode, so it's expected that in some complex cases
  the panic screen won't be displayed.
  The returned [`drm_scanout_buffer.map`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_scanout_buffer) must be valid if no error code is
  returned.

  Return:
  `0` on success, negative errno on failure.
- `panic_flush`: It is used by drm_panic, and is called after the panic screen is
  drawn to the scanout buffer. In this function, the driver
  can send additional commands to the hardware, to make the scanout
  buffer visible.
  It is only called if `get_scanout_buffer()` returned successfully, and
  the `dev.mode_config`.panic_lock is held during the entire sequence.
  It is called from a panic callback, and must follow its restrictions.
  Please look the documentation at [`drm_panic_trylock()`](/kernel/hardware/gpu/drm-kms.md#c-drm_panic_trylock) for an in-depth
  discussions of what's safe and what is not allowed.

**Description**

These functions are used by the atomic helpers.

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

```c
void drm_plane_helper_add(struct drm_plane *plane, const struct drm_plane_helper_funcs *funcs)
```

sets the helper vtable for a plane

**Parameters**

- `struct drm_plane *plane`: DRM plane
- `const struct drm_plane_helper_funcs *funcs`: helper vtable to set for **plane**

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

global modeset helper operations

**Definition**

```c
struct drm_mode_config_helper_funcs {
    void (*atomic_commit_tail)(struct drm_atomic_state *state);
    int (*atomic_commit_setup)(struct drm_atomic_state *state);
};
```

**Members**

- `atomic_commit_tail`: This hook is used by the default `atomic_commit()` hook implemented in
  [`drm_atomic_helper_commit()`](#c-drm_atomic_helper_commit) together with the nonblocking commit
  helpers (see [`drm_atomic_helper_setup_commit()`](#c-drm_atomic_helper_setup_commit) for a starting point)
  to implement blocking and nonblocking commits easily. It is not used
  by the atomic helpers

  This function is called when the new atomic state has already been
  swapped into the various state pointers. The passed in state
  therefore contains copies of the old/previous state. This hook should
  commit the new state into hardware. Note that the helpers have
  already waited for preceding atomic commits and fences, but drivers
  can add more waiting calls at the start of their implementation, e.g.
  to wait for driver-internal request for implicit syncing, before
  starting to commit the update to the hardware.

  After the atomic update is committed to the hardware this hook needs
  to call [`drm_atomic_helper_commit_hw_done()`](#c-drm_atomic_helper_commit_hw_done). Then wait for the update
  to be executed by the hardware, for example using
  [`drm_atomic_helper_wait_for_vblanks()`](#c-drm_atomic_helper_wait_for_vblanks) or
  [`drm_atomic_helper_wait_for_flip_done()`](#c-drm_atomic_helper_wait_for_flip_done), and then clean up the old
  framebuffers using [`drm_atomic_helper_cleanup_planes()`](#c-drm_atomic_helper_cleanup_planes).

  When disabling a CRTC this hook _must_ stall for the commit to
  complete. Vblank waits don't work on disabled CRTC, hence the core
  can't take care of this. And it also can't rely on the vblank event,
  since that can be signalled already when the screen shows black,
  which can happen much earlier than the last hardware access needed to
  shut off the display pipeline completely.

  This hook is optional, the default implementation is
  [`drm_atomic_helper_commit_tail()`](#c-drm_atomic_helper_commit_tail).
- `atomic_commit_setup`: This hook is used by the default `atomic_commit()` hook implemented in
  [`drm_atomic_helper_commit()`](#c-drm_atomic_helper_commit) together with the nonblocking helpers (see
  [`drm_atomic_helper_setup_commit()`](#c-drm_atomic_helper_setup_commit)) to extend the DRM commit setup. It
  is not used by the atomic helpers.

  This function is called at the end of
  [`drm_atomic_helper_setup_commit()`](#c-drm_atomic_helper_setup_commit), so once the commit has been
  properly setup across the generic DRM object states. It allows
  drivers to do some additional commit tracking that isn't related to a
  CRTC, plane or connector, tracked in a [`drm_private_obj`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_private_obj) structure.

  Note that the documentation of [`drm_private_obj`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_private_obj) has more details on
  how one should implement this.

  This hook is optional.

**Description**

These helper functions are used by the atomic helpers.


<a id="rst-atomic-modeset-helper-functions-reference"></a>
<a id="rst-drm-atomic-helper"></a>

## Atomic Modeset Helper Functions Reference

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

### Overview


This helper library provides implementations of check and commit functions on
top of the CRTC modeset helper callbacks and the plane helper callbacks. It
also provides convenience implementations for the atomic state handling
callbacks for drivers which don't need to subclass the drm core structures to
add their own additional internal state.

This library also provides default implementations for the check callback in
[`drm_atomic_helper_check()`](#c-drm_atomic_helper_check) and for the commit callback with
[`drm_atomic_helper_commit()`](#c-drm_atomic_helper_commit). But the individual stages and callbacks are
exposed to allow drivers to mix and match and e.g. use the plane helpers only
together with a driver private modeset implementation.

This library also provides implementations for all the legacy driver
interfaces on top of the atomic interface. See [`drm_atomic_helper_set_config()`](#c-drm_atomic_helper_set_config),
[`drm_atomic_helper_disable_plane()`](#c-drm_atomic_helper_disable_plane), and the various functions to implement
set_property callbacks. New drivers must not implement these functions
themselves but must use the provided helpers.

The atomic helper uses the same function table structures as all other
modesetting helpers. See the documentation for [`struct drm_crtc_helper_funcs`](#c-struct-drm_crtc_helper_funcs),
struct [`drm_encoder_helper_funcs`](#c-struct-drm_encoder_helper_funcs) and [`struct drm_connector_helper_funcs`](#c-struct-drm_connector_helper_funcs). It
also shares the [`struct drm_plane_helper_funcs`](#c-struct-drm_plane_helper_funcs) function table with the plane
helpers.


<a id="rst-implementing-asynchronous-atomic-commit"></a>

### Implementing Asynchronous Atomic Commit


Nonblocking atomic commits should use struct [`drm_crtc_commit`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_crtc_commit) to sequence
different operations against each another. Locks, especially struct
[`drm_modeset_lock`](/kernel/hardware/gpu/drm-kms.md#c-drm_modeset_lock), should not be held in worker threads or any other
asynchronous context used to commit the hardware state.

[`drm_atomic_helper_commit()`](#c-drm_atomic_helper_commit) implements the recommended sequence for
nonblocking commits, using [`drm_atomic_helper_setup_commit()`](#c-drm_atomic_helper_setup_commit) internally:

1. Run [`drm_atomic_helper_prepare_planes()`](#c-drm_atomic_helper_prepare_planes). Since this can fail and we
need to propagate out of memory/VRAM errors to userspace, it must be called
synchronously.

2. Synchronize with any outstanding nonblocking commit worker threads which
might be affected by the new state update. This is handled by
[`drm_atomic_helper_setup_commit()`](#c-drm_atomic_helper_setup_commit).

Asynchronous workers need to have sufficient parallelism to be able to run
different atomic commits on different CRTCs in parallel. The simplest way to
achieve this is by running them on the `system_unbound_wq` work queue. Note
that drivers are not required to split up atomic commits and run an
individual commit in parallel - userspace is supposed to do that if it cares.
But it might be beneficial to do that for modesets, since those necessarily
must be done as one global operation, and enabling or disabling a CRTC can
take a long time. But even that is not required.

IMPORTANT: A [`drm_atomic_state`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_atomic_state) update for multiple CRTCs is sequenced
against all CRTCs therein. Therefore for atomic state updates which only flip
planes the driver must not get the struct [`drm_crtc_state`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_crtc_state) of unrelated CRTCs
in its atomic check code: This would prevent committing of atomic updates to
multiple CRTCs in parallel. In general, adding additional state structures
should be avoided as much as possible, because this reduces parallelism in
(nonblocking) commits, both due to locking and due to commit sequencing
requirements.

3. The software state is updated synchronously with
[`drm_atomic_helper_swap_state()`](#c-drm_atomic_helper_swap_state). Doing this under the protection of all modeset
locks means concurrent callers never see inconsistent state. Note that commit
workers do not hold any locks; their access is only coordinated through
ordering. If workers would access state only through the pointers in the
free-standing state objects (currently not the case for any driver) then even
multiple pending commits could be in-flight at the same time.

4. Schedule a work item to do all subsequent steps, using the split-out
commit helpers: a) pre-plane commit b) plane commit c) post-plane commit and
then cleaning up the framebuffers after the old framebuffer is no longer
being displayed. The scheduled work should synchronize against other workers
using the [`drm_crtc_commit`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_crtc_commit) infrastructure as needed. See
[`drm_atomic_helper_setup_commit()`](#c-drm_atomic_helper_setup_commit) for more details.


<a id="rst-helper-functions-reference"></a>

### Helper Functions Reference


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

```c
drm_atomic_crtc_for_each_plane(plane, crtc)
```

iterate over planes currently attached to CRTC

**Parameters**

- `plane`: the loop cursor
- `crtc`: the CRTC whose planes are iterated

**Description**

This iterates over the current state, useful (for example) when applying
atomic state after it has been checked and swapped.  To iterate over the
planes which *will* be attached (more useful in code called from
[`drm_mode_config_funcs.atomic_check`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_mode_config_funcs)) see
[`drm_atomic_crtc_state_for_each_plane()`](#c-drm_atomic_crtc_state_for_each_plane).

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

```c
drm_atomic_crtc_state_for_each_plane(plane, crtc_state)
```

iterate over attached planes in new state

**Parameters**

- `plane`: the loop cursor
- `crtc_state`: the incoming CRTC state

**Description**

Similar to `drm_crtc_for_each_plane()`, but iterates the planes that will be
attached if the specified state is applied.  Useful during for example
in code called from [`drm_mode_config_funcs.atomic_check`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_mode_config_funcs) operations, to
validate the incoming state.

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

```c
drm_atomic_crtc_state_for_each_plane_state(plane, plane_state, crtc_state)
```

iterate over attached planes in new state

**Parameters**

- `plane`: the loop cursor
- `plane_state`: loop cursor for the plane's state, must be const
- `crtc_state`: the incoming CRTC state

**Description**

Similar to `drm_crtc_for_each_plane()`, but iterates the planes that will be
attached if the specified state is applied.  Useful during for example
in code called from [`drm_mode_config_funcs.atomic_check`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_mode_config_funcs) operations, to
validate the incoming state.

Compared to just [`drm_atomic_crtc_state_for_each_plane()`](#c-drm_atomic_crtc_state_for_each_plane) this also fills in a
const plane_state. This is useful when a driver just wants to peek at other
active planes on this CRTC, but does not need to change it.

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

```c
bool drm_atomic_plane_enabling(struct drm_plane_state *old_plane_state, struct drm_plane_state *new_plane_state)
```

check whether a plane is being enabled

**Parameters**

- `struct drm_plane_state *old_plane_state`: old atomic plane state
- `struct drm_plane_state *new_plane_state`: new atomic plane state

**Description**

Checks the atomic state of a plane to determine whether it's being enabled
or not. This also WARNs if it detects an invalid state (both CRTC and FB
need to either both be NULL or both be non-NULL).

**Return**

True if the plane is being enabled, false otherwise.

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

```c
bool drm_atomic_plane_disabling(struct drm_plane_state *old_plane_state, struct drm_plane_state *new_plane_state)
```

check whether a plane is being disabled

**Parameters**

- `struct drm_plane_state *old_plane_state`: old atomic plane state
- `struct drm_plane_state *new_plane_state`: new atomic plane state

**Description**

Checks the atomic state of a plane to determine whether it's being disabled
or not. This also WARNs if it detects an invalid state (both CRTC and FB
need to either both be NULL or both be non-NULL).

**Return**

True if the plane is being disabled, false otherwise.



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

```c
int drm_atomic_helper_check_modeset(struct drm_device *dev, struct drm_atomic_state *state)
```

validate state object for modeset changes

**Parameters**

- `struct drm_device *dev`: DRM device
- `struct drm_atomic_state *state`: the driver state object

**Description**

Check the state object to see if the requested state is physically possible.
This does all the CRTC and connector related computations for an atomic
update and adds any additional connectors needed for full modesets. It calls
the various per-object callbacks in the follow order:

1. [`drm_connector_helper_funcs.atomic_best_encoder`](#c-struct-drm_connector_helper_funcs) for determining the new encoder.
2. [`drm_connector_helper_funcs.atomic_check`](#c-struct-drm_connector_helper_funcs) to validate the connector state.
3. If it's determined a modeset is needed then all connectors on the affected
   CRTC are added and [`drm_connector_helper_funcs.atomic_check`](#c-struct-drm_connector_helper_funcs) is run on them.
4. [`drm_encoder_helper_funcs.mode_valid`](#c-struct-drm_encoder_helper_funcs), [`drm_bridge_funcs.mode_valid`](#c-struct-drm_bridge_funcs) and
   [`drm_crtc_helper_funcs.mode_valid`](#c-struct-drm_crtc_helper_funcs) are called on the affected components.
5. [`drm_bridge_funcs.mode_fixup`](#c-struct-drm_bridge_funcs) is called on all encoder bridges.
6. [`drm_encoder_helper_funcs.atomic_check`](#c-struct-drm_encoder_helper_funcs) is called to validate any encoder state.
   This function is only called when the encoder will be part of a configured CRTC,
   it must not be used for implementing connector property validation.
   If this function is NULL, `drm_atomic_encoder_helper_funcs.mode_fixup` is called
   instead.
7. [`drm_crtc_helper_funcs.mode_fixup`](#c-struct-drm_crtc_helper_funcs) is called last, to fix up the mode with CRTC constraints.

[`drm_crtc_state.mode_changed`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_crtc_state) is set when the input mode is changed.
[`drm_crtc_state.connectors_changed`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_crtc_state) is set when a connector is added or
removed from the CRTC.  [`drm_crtc_state.active_changed`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_crtc_state) is set when
[`drm_crtc_state.active`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_crtc_state) changes, which is used for DPMS.
[`drm_crtc_state.no_vblank`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_crtc_state) is set from the result of [`drm_dev_has_vblank()`](/kernel/hardware/gpu/drm-kms.md#c-drm_dev_has_vblank).
See also: [`drm_atomic_crtc_needs_modeset()`](/kernel/hardware/gpu/drm-kms.md#c-drm_atomic_crtc_needs_modeset)

IMPORTANT:

Drivers which set [`drm_crtc_state.mode_changed`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_crtc_state) (e.g. in their
[`drm_plane_helper_funcs.atomic_check`](#c-struct-drm_plane_helper_funcs) hooks if a plane update can't be done
without a full modeset) _must_ call this function after that change. It is
permitted to call this function multiple times for the same update, e.g.
when the [`drm_crtc_helper_funcs.atomic_check`](#c-struct-drm_crtc_helper_funcs) functions depend upon the
adjusted dotclock for fifo space allocation and watermark computation.

**Return**

Zero for success or -errno

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

```c
int drm_atomic_helper_check_wb_connector_state(struct drm_connector *connector, struct drm_atomic_state *state)
```

Check writeback connector state

**Parameters**

- `struct drm_connector *connector`: corresponding connector
- `struct drm_atomic_state *state`: the driver state object

**Description**

Checks if the writeback connector state is valid, and returns an error if it
isn't.

**Return**

Zero for success or -errno

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

```c
int drm_atomic_helper_check_plane_state(struct drm_plane_state *plane_state, const struct drm_crtc_state *crtc_state, int min_scale, int max_scale, bool can_position, bool can_update_disabled)
```

Check plane state for validity

**Parameters**

- `struct drm_plane_state *plane_state`: plane state to check
- `const struct drm_crtc_state *crtc_state`: CRTC state to check
- `int min_scale`: minimum **src**:**dest** scaling factor in 16.16 fixed point
- `int max_scale`: maximum **src**:**dest** scaling factor in 16.16 fixed point
- `bool can_position`: is it legal to position the plane such that it
  doesn't cover the entire CRTC?  This will generally
  only be false for primary planes.
- `bool can_update_disabled`: can the plane be updated while the CRTC
  is disabled?

**Description**

Checks that a desired plane update is valid, and updates various
bits of derived state (clipped coordinates etc.). Drivers that provide
their own plane handling rather than helper-provided implementations may
still wish to call this function to avoid duplication of error checking
code.

**Return**

Zero if update appears valid, error code on failure

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

```c
int drm_atomic_helper_check_crtc_primary_plane(struct drm_crtc_state *crtc_state)
```

Check CRTC state for primary plane

**Parameters**

- `struct drm_crtc_state *crtc_state`: CRTC state to check

**Description**

Checks that a CRTC has at least one primary plane attached to it, which is
a requirement on some hardware. Note that this only involves the CRTC side
of the test. To test if the primary plane is visible or if it can be updated
without the CRTC being enabled, use [`drm_atomic_helper_check_plane_state()`](#c-drm_atomic_helper_check_plane_state) in
the plane's atomic check.

**Return**

0 if a primary plane is attached to the CRTC, or an error code otherwise

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

```c
int drm_atomic_helper_check_planes(struct drm_device *dev, struct drm_atomic_state *state)
```

validate state object for planes changes

**Parameters**

- `struct drm_device *dev`: DRM device
- `struct drm_atomic_state *state`: the driver state object

**Description**

Check the state object to see if the requested state is physically possible.
This does all the plane update related checks using by calling into the
[`drm_crtc_helper_funcs.atomic_check`](#c-struct-drm_crtc_helper_funcs) and [`drm_plane_helper_funcs.atomic_check`](#c-struct-drm_plane_helper_funcs)
hooks provided by the driver.

It also sets [`drm_crtc_state.planes_changed`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_crtc_state) to indicate that a CRTC has
updated planes.

**Return**

Zero for success or -errno

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

```c
int drm_atomic_helper_check(struct drm_device *dev, struct drm_atomic_state *state)
```

validate state object

**Parameters**

- `struct drm_device *dev`: DRM device
- `struct drm_atomic_state *state`: the driver state object

**Description**

Check the state object to see if the requested state is physically possible.
Only CRTCs and planes have check callbacks, so for any additional (global)
checking that a driver needs it can simply wrap that around this function.
Drivers without such needs can directly use this as their
[`drm_mode_config_funcs.atomic_check`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_mode_config_funcs) callback.

This just wraps the two parts of the state checking for planes and modeset
state in the default order: First it calls [`drm_atomic_helper_check_modeset()`](#c-drm_atomic_helper_check_modeset)
and then [`drm_atomic_helper_check_planes()`](#c-drm_atomic_helper_check_planes). The assumption is that the
**drm_plane_helper_funcs.atomic_check** and **drm_crtc_helper_funcs.atomic_check**
functions depend upon an updated adjusted_mode.clock to e.g. properly compute
watermarks.

Note that zpos normalization will add all enable planes to the state which
might not desired for some drivers.
For example enable/disable of a cursor plane which have fixed zpos value
would trigger all other enabled planes to be forced to the state change.

IMPORTANT:

As this function calls [`drm_atomic_helper_check_modeset()`](#c-drm_atomic_helper_check_modeset) internally, its
restrictions also apply:
Drivers which set [`drm_crtc_state.mode_changed`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_crtc_state) (e.g. in their
[`drm_plane_helper_funcs.atomic_check`](#c-struct-drm_plane_helper_funcs) hooks if a plane update can't be done
without a full modeset) _must_ call [`drm_atomic_helper_check_modeset()`](#c-drm_atomic_helper_check_modeset)
function again after that change.

**Return**

Zero for success or -errno

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

```c
void drm_atomic_helper_commit_encoder_bridge_disable(struct drm_device *dev, struct drm_atomic_state *state)
```

disable bridges and encoder

**Parameters**

- `struct drm_device *dev`: DRM device
- `struct drm_atomic_state *state`: the driver state object

**Description**

Loops over all connectors in the current state and if the CRTC needs
it, disables the bridge chain all the way, then disables the encoder
afterwards.

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

```c
void drm_atomic_helper_commit_crtc_disable(struct drm_device *dev, struct drm_atomic_state *state)
```

disable CRTSs

**Parameters**

- `struct drm_device *dev`: DRM device
- `struct drm_atomic_state *state`: the driver state object

**Description**

Loops over all CRTCs in the current state and if the CRTC needs
it, disables it.

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

```c
void drm_atomic_helper_commit_encoder_bridge_post_disable(struct drm_device *dev, struct drm_atomic_state *state)
```

post-disable encoder bridges

**Parameters**

- `struct drm_device *dev`: DRM device
- `struct drm_atomic_state *state`: the driver state object

**Description**

Loops over all connectors in the current state and if the CRTC needs
it, post-disables all encoder bridges.

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

```c
void drm_atomic_helper_update_legacy_modeset_state(struct drm_device *dev, struct drm_atomic_state *state)
```

update legacy modeset state

**Parameters**

- `struct drm_device *dev`: DRM device
- `struct drm_atomic_state *state`: atomic state object being committed

**Description**

This function updates all the various legacy modeset state pointers in
connectors, encoders and CRTCs.

Drivers can use this for building their own atomic commit if they don't have
a pure helper-based modeset implementation.

Since these updates are not synchronized with lockings, only code paths
called from [`drm_mode_config_helper_funcs.atomic_commit_tail`](#c-struct-drm_mode_config_helper_funcs) can look at the
legacy state filled out by this helper. Defacto this means this helper and
the legacy state pointers are only really useful for transitioning an
existing driver to the atomic world.

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

```c
void drm_atomic_helper_calc_timestamping_constants(struct drm_atomic_state *state)
```

update vblank timestamping constants

**Parameters**

- `struct drm_atomic_state *state`: atomic state object

**Description**

Updates the timestamping constants used for precise vblank timestamps
by calling [`drm_calc_timestamping_constants()`](/kernel/hardware/gpu/drm-kms.md#c-drm_calc_timestamping_constants) for all enabled crtcs in **state**.

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

```c
void drm_atomic_helper_commit_crtc_set_mode(struct drm_device *dev, struct drm_atomic_state *state)
```

set the new mode

**Parameters**

- `struct drm_device *dev`: DRM device
- `struct drm_atomic_state *state`: the driver state object

**Description**

Loops over all connectors in the current state and if the mode has
changed, change the mode of the CRTC, then call down the bridge
chain and change the mode in all bridges as well.

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

```c
void drm_atomic_helper_commit_modeset_disables(struct drm_device *dev, struct drm_atomic_state *state)
```

modeset commit to disable outputs

**Parameters**

- `struct drm_device *dev`: DRM device
- `struct drm_atomic_state *state`: atomic state object being committed

**Description**

This function shuts down all the outputs that need to be shut down and
prepares them (if required) with the new mode.

For compatibility with legacy CRTC helpers this should be called before
[`drm_atomic_helper_commit_planes()`](#c-drm_atomic_helper_commit_planes), which is what the default commit function
does. But drivers with different needs can group the modeset commits together
and do the plane commits at the end. This is useful for drivers doing runtime
PM since planes updates then only happen when the CRTC is actually enabled.

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

```c
void drm_atomic_helper_commit_writebacks(struct drm_device *dev, struct drm_atomic_state *state)
```

issue writebacks

**Parameters**

- `struct drm_device *dev`: DRM device
- `struct drm_atomic_state *state`: atomic state object being committed

**Description**

This loops over the connectors, checks if the new state requires
a writeback job to be issued and in that case issues an atomic
commit on each connector.

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

```c
void drm_atomic_helper_commit_encoder_bridge_pre_enable(struct drm_device *dev, struct drm_atomic_state *state)
```

pre-enable bridges

**Parameters**

- `struct drm_device *dev`: DRM device
- `struct drm_atomic_state *state`: atomic state object being committed

**Description**

This loops over the connectors and if the CRTC needs it, pre-enables
the entire bridge chain.

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

```c
void drm_atomic_helper_commit_crtc_enable(struct drm_device *dev, struct drm_atomic_state *state)
```

enables the CRTCs

**Parameters**

- `struct drm_device *dev`: DRM device
- `struct drm_atomic_state *state`: atomic state object being committed

**Description**

This loops over CRTCs in the new state, and of the CRTC needs
it, enables it.

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

```c
void drm_atomic_helper_commit_encoder_bridge_enable(struct drm_device *dev, struct drm_atomic_state *state)
```

enables the bridges

**Parameters**

- `struct drm_device *dev`: DRM device
- `struct drm_atomic_state *state`: atomic state object being committed

**Description**

This loops over all connectors in the new state, and of the CRTC needs
it, enables the entire bridge chain.

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

```c
void drm_atomic_helper_commit_modeset_enables(struct drm_device *dev, struct drm_atomic_state *state)
```

modeset commit to enable outputs

**Parameters**

- `struct drm_device *dev`: DRM device
- `struct drm_atomic_state *state`: atomic state object being committed

**Description**

This function enables all the outputs with the new configuration which had to
be turned off for the update.

For compatibility with legacy CRTC helpers this should be called after
[`drm_atomic_helper_commit_planes()`](#c-drm_atomic_helper_commit_planes), which is what the default commit function
does. But drivers with different needs can group the modeset commits together
and do the plane commits at the end. This is useful for drivers doing runtime
PM since planes updates then only happen when the CRTC is actually enabled.

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

```c
int drm_atomic_helper_wait_for_fences(struct drm_device *dev, struct drm_atomic_state *state, bool pre_swap)
```

wait for fences stashed in plane state

**Parameters**

- `struct drm_device *dev`: DRM device
- `struct drm_atomic_state *state`: atomic state object with old state structures
- `bool pre_swap`: If true, do an interruptible wait, and **state** is the new state.
  Otherwise **state** is the old state.

**Description**

For implicit sync, driver should fish the exclusive fence out from the
incoming fb's and stash it in the drm_plane_state.  This is called after
[`drm_atomic_helper_swap_state()`](#c-drm_atomic_helper_swap_state) so it uses the current plane state (and
just uses the atomic state to find the changed planes)

Note that **pre_swap** is needed since the point where we block for fences moves
around depending upon whether an atomic commit is blocking or
non-blocking. For non-blocking commit all waiting needs to happen after
[`drm_atomic_helper_swap_state()`](#c-drm_atomic_helper_swap_state) is called, but for blocking commits we want
to wait **before** we do anything that can't be easily rolled back. That is
before we call [`drm_atomic_helper_swap_state()`](#c-drm_atomic_helper_swap_state).

Returns zero if success or \< 0 if [`dma_fence_wait()`](/kernel/hardware/driver-api/io-and-dma/dma-buf.md#c-dma_fence_wait) fails.

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

```c
void drm_atomic_helper_wait_for_vblanks(struct drm_device *dev, struct drm_atomic_state *state)
```

wait for vblank on CRTCs

**Parameters**

- `struct drm_device *dev`: DRM device
- `struct drm_atomic_state *state`: atomic state object being committed

**Description**

Helper to, after atomic commit, wait for vblanks on all affected
CRTCs (ie. before cleaning up old framebuffers using
[`drm_atomic_helper_cleanup_planes()`](#c-drm_atomic_helper_cleanup_planes)). It will only wait on CRTCs where the
framebuffers have actually changed to optimize for the legacy cursor and
plane update use-case.

Drivers using the nonblocking commit tracking support initialized by calling
[`drm_atomic_helper_setup_commit()`](#c-drm_atomic_helper_setup_commit) should look at
[`drm_atomic_helper_wait_for_flip_done()`](#c-drm_atomic_helper_wait_for_flip_done) as an alternative.

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

```c
void drm_atomic_helper_wait_for_flip_done(struct drm_device *dev, struct drm_atomic_state *state)
```

wait for all page flips to be done

**Parameters**

- `struct drm_device *dev`: DRM device
- `struct drm_atomic_state *state`: atomic state object being committed

**Description**

Helper to, after atomic commit, wait for page flips on all affected
crtcs (ie. before cleaning up old framebuffers using
[`drm_atomic_helper_cleanup_planes()`](#c-drm_atomic_helper_cleanup_planes)). Compared to
[`drm_atomic_helper_wait_for_vblanks()`](#c-drm_atomic_helper_wait_for_vblanks) this waits for the completion on all
CRTCs, assuming that cursors-only updates are signalling their completion
immediately (or using a different path).

This requires that drivers use the nonblocking commit tracking support
initialized using [`drm_atomic_helper_setup_commit()`](#c-drm_atomic_helper_setup_commit).

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

```c
void drm_atomic_helper_commit_tail(struct drm_atomic_state *state)
```

commit atomic update to hardware

**Parameters**

- `struct drm_atomic_state *state`: atomic state object being committed

**Description**

This is the default implementation for the
[`drm_mode_config_helper_funcs.atomic_commit_tail`](#c-struct-drm_mode_config_helper_funcs) hook, for drivers
that do not support runtime_pm or do not need the CRTC to be
enabled to perform a commit. Otherwise, see
[`drm_atomic_helper_commit_tail_rpm()`](#c-drm_atomic_helper_commit_tail_rpm).

Note that the default ordering of how the various stages are called is to
match the legacy modeset helper library closest.

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

```c
void drm_atomic_helper_commit_tail_rpm(struct drm_atomic_state *state)
```

commit atomic update to hardware

**Parameters**

- `struct drm_atomic_state *state`: new modeset state to be committed

**Description**

This is an alternative implementation for the
[`drm_mode_config_helper_funcs.atomic_commit_tail`](#c-struct-drm_mode_config_helper_funcs) hook, for drivers
that support runtime_pm or need the CRTC to be enabled to perform a
commit. Otherwise, one should use the default implementation
[`drm_atomic_helper_commit_tail()`](#c-drm_atomic_helper_commit_tail).

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

```c
int drm_atomic_helper_async_check(struct drm_device *dev, struct drm_atomic_state *state)
```

check if state can be committed asynchronously

**Parameters**

- `struct drm_device *dev`: DRM device
- `struct drm_atomic_state *state`: the driver state object

**Description**

This helper will check if it is possible to commit the state asynchronously.
Async commits are not supposed to swap the states like normal sync commits
but just do in-place changes on the current state.

It will return 0 if the commit can happen in an asynchronous fashion or error
if not. Note that error just mean it can't be committed asynchronously, if it
fails the commit should be treated like a normal synchronous commit.

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

```c
void drm_atomic_helper_async_commit(struct drm_device *dev, struct drm_atomic_state *state)
```

commit state asynchronously

**Parameters**

- `struct drm_device *dev`: DRM device
- `struct drm_atomic_state *state`: the driver state object

**Description**

This function commits a state asynchronously, i.e., not vblank
synchronized. It should be used on a state only when
`drm_atomic_async_check()` succeeds. Async commits are not supposed to swap
the states like normal sync commits, but just do in-place changes on the
current state.

TODO: Implement full swap instead of doing in-place changes.

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

```c
int drm_atomic_helper_commit(struct drm_device *dev, struct drm_atomic_state *state, bool nonblock)
```

commit validated state object

**Parameters**

- `struct drm_device *dev`: DRM device
- `struct drm_atomic_state *state`: the driver state object
- `bool nonblock`: whether nonblocking behavior is requested.

**Description**

This function commits a with [`drm_atomic_helper_check()`](#c-drm_atomic_helper_check) pre-validated state
object. This can still fail when e.g. the framebuffer reservation fails. This
function implements nonblocking commits, using
[`drm_atomic_helper_setup_commit()`](#c-drm_atomic_helper_setup_commit) and related functions.

Committing the actual hardware state is done through the
[`drm_mode_config_helper_funcs.atomic_commit_tail`](#c-struct-drm_mode_config_helper_funcs) callback, or its default
implementation [`drm_atomic_helper_commit_tail()`](#c-drm_atomic_helper_commit_tail).

**Return**

Zero for success or -errno.

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

```c
int drm_atomic_helper_setup_commit(struct drm_atomic_state *state, bool nonblock)
```

setup possibly nonblocking commit

**Parameters**

- `struct drm_atomic_state *state`: new modeset state to be committed
- `bool nonblock`: whether nonblocking behavior is requested.

**Description**

This function prepares **state** to be used by the atomic helper's support for
nonblocking commits. Drivers using the nonblocking commit infrastructure
should always call this function from their
[`drm_mode_config_funcs.atomic_commit`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_mode_config_funcs) hook.

Drivers that need to extend the commit setup to private objects can use the
[`drm_mode_config_helper_funcs.atomic_commit_setup`](#c-struct-drm_mode_config_helper_funcs) hook.

To be able to use this support drivers need to use a few more helper
functions. [`drm_atomic_helper_wait_for_dependencies()`](#c-drm_atomic_helper_wait_for_dependencies) must be called before
actually committing the hardware state, and for nonblocking commits this call
must be placed in the async worker. See also [`drm_atomic_helper_swap_state()`](#c-drm_atomic_helper_swap_state)
and its stall parameter, for when a driver's commit hooks look at the
[`drm_crtc.state`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_crtc), [`drm_plane.state`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_plane) or [`drm_connector.state`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_connector) pointer directly.

Completion of the hardware commit step must be signalled using
[`drm_atomic_helper_commit_hw_done()`](#c-drm_atomic_helper_commit_hw_done). After this step the driver is not allowed
to read or change any permanent software or hardware modeset state. The only
exception is state protected by other means than [`drm_modeset_lock`](/kernel/hardware/gpu/drm-kms.md#c-drm_modeset_lock) locks.
Only the free standing **state** with pointers to the old state structures can
be inspected, e.g. to clean up old buffers using
[`drm_atomic_helper_cleanup_planes()`](#c-drm_atomic_helper_cleanup_planes).

At the very end, before cleaning up **state** drivers must call
[`drm_atomic_helper_commit_cleanup_done()`](#c-drm_atomic_helper_commit_cleanup_done).

This is all implemented by in [`drm_atomic_helper_commit()`](#c-drm_atomic_helper_commit), giving drivers a
complete and easy-to-use default implementation of the `atomic_commit()` hook.

The tracking of asynchronously executed and still pending commits is done
using the core structure [`drm_crtc_commit`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_crtc_commit).

By default there's no need to clean up resources allocated by this function
explicitly: [`drm_atomic_state_default_clear()`](/kernel/hardware/gpu/drm-kms.md#c-drm_atomic_state_default_clear) will take care of that
automatically.

**Return**

0 on success. -EBUSY when userspace schedules nonblocking commits too fast,
-ENOMEM on allocation failures and -EINTR when a signal is pending.

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

```c
void drm_atomic_helper_wait_for_dependencies(struct drm_atomic_state *state)
```

wait for required preceding commits

**Parameters**

- `struct drm_atomic_state *state`: atomic state object being committed

**Description**

This function waits for all preceding commits that touch the same CRTC as
**state** to both be committed to the hardware (as signalled by
[`drm_atomic_helper_commit_hw_done()`](#c-drm_atomic_helper_commit_hw_done)) and executed by the hardware (as signalled
by calling [`drm_crtc_send_vblank_event()`](/kernel/hardware/gpu/drm-kms.md#c-drm_crtc_send_vblank_event) on the [`drm_crtc_state.event`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_crtc_state)).

This is part of the atomic helper support for nonblocking commits, see
[`drm_atomic_helper_setup_commit()`](#c-drm_atomic_helper_setup_commit) for an overview.

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

```c
void drm_atomic_helper_fake_vblank(struct drm_atomic_state *state)
```

fake VBLANK events if needed

**Parameters**

- `struct drm_atomic_state *state`: atomic state object being committed

**Description**

This function walks all CRTCs and fakes VBLANK events on those with
[`drm_crtc_state.no_vblank`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_crtc_state) set to true and [`drm_crtc_state.event`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_crtc_state) != NULL.
The primary use of this function is writeback connectors working in oneshot
mode and faking VBLANK events. In this case they only fake the VBLANK event
when a job is queued, and any change to the pipeline that does not touch the
connector is leading to timeouts when calling
[`drm_atomic_helper_wait_for_vblanks()`](#c-drm_atomic_helper_wait_for_vblanks) or
[`drm_atomic_helper_wait_for_flip_done()`](#c-drm_atomic_helper_wait_for_flip_done). In addition to writeback
connectors, this function can also fake VBLANK events for CRTCs without
VBLANK interrupt.

This is part of the atomic helper support for nonblocking commits, see
[`drm_atomic_helper_setup_commit()`](#c-drm_atomic_helper_setup_commit) for an overview.

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

```c
void drm_atomic_helper_commit_hw_done(struct drm_atomic_state *state)
```

setup possible nonblocking commit

**Parameters**

- `struct drm_atomic_state *state`: atomic state object being committed

**Description**

This function is used to signal completion of the hardware commit step. After
this step the driver is not allowed to read or change any permanent software
or hardware modeset state. The only exception is state protected by other
means than [`drm_modeset_lock`](/kernel/hardware/gpu/drm-kms.md#c-drm_modeset_lock) locks.

Drivers should try to postpone any expensive or delayed cleanup work after
this function is called.

This is part of the atomic helper support for nonblocking commits, see
[`drm_atomic_helper_setup_commit()`](#c-drm_atomic_helper_setup_commit) for an overview.

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

```c
void drm_atomic_helper_commit_cleanup_done(struct drm_atomic_state *state)
```

signal completion of commit

**Parameters**

- `struct drm_atomic_state *state`: atomic state object being committed

**Description**

This signals completion of the atomic update **state**, including any
cleanup work. If used, it must be called right before calling
[`drm_atomic_state_put()`](/kernel/hardware/gpu/drm-kms.md#c-drm_atomic_state_put).

This is part of the atomic helper support for nonblocking commits, see
[`drm_atomic_helper_setup_commit()`](#c-drm_atomic_helper_setup_commit) for an overview.

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

```c
int drm_atomic_helper_prepare_planes(struct drm_device *dev, struct drm_atomic_state *state)
```

prepare plane resources before commit

**Parameters**

- `struct drm_device *dev`: DRM device
- `struct drm_atomic_state *state`: atomic state object with new state structures

**Description**

This function prepares plane state, specifically framebuffers, for the new
configuration, by calling [`drm_plane_helper_funcs.prepare_fb`](#c-struct-drm_plane_helper_funcs). If any failure
is encountered this function will call [`drm_plane_helper_funcs.cleanup_fb`](#c-struct-drm_plane_helper_funcs) on
any already successfully prepared framebuffer.

**Return**

0 on success, negative error code on failure.

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

```c
void drm_atomic_helper_unprepare_planes(struct drm_device *dev, struct drm_atomic_state *state)
```

release plane resources on aborts

**Parameters**

- `struct drm_device *dev`: DRM device
- `struct drm_atomic_state *state`: atomic state object with old state structures

**Description**

This function cleans up plane state, specifically framebuffers, from the
atomic state. It undoes the effects of [`drm_atomic_helper_prepare_planes()`](#c-drm_atomic_helper_prepare_planes)
when aborting an atomic commit. For cleaning up after a successful commit
use [`drm_atomic_helper_cleanup_planes()`](#c-drm_atomic_helper_cleanup_planes).

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

```c
void drm_atomic_helper_commit_planes(struct drm_device *dev, struct drm_atomic_state *state, uint32_t flags)
```

commit plane state

**Parameters**

- `struct drm_device *dev`: DRM device
- `struct drm_atomic_state *state`: atomic state object being committed
- `uint32_t flags`: flags for committing plane state

**Description**

This function commits the new plane state using the plane and atomic helper
functions for planes and CRTCs. It assumes that the atomic state has already
been pushed into the relevant object state pointers, since this step can no
longer fail.

It still requires the global state object **state** to know which planes and
crtcs need to be updated though.

Note that this function does all plane updates across all CRTCs in one step.
If the hardware can't support this approach look at
[`drm_atomic_helper_commit_planes_on_crtc()`](#c-drm_atomic_helper_commit_planes_on_crtc) instead.

Plane parameters can be updated by applications while the associated CRTC is
disabled. The DRM/KMS core will store the parameters in the plane state,
which will be available to the driver when the CRTC is turned on. As a result
most drivers don't need to be immediately notified of plane updates for a
disabled CRTC.

Unless otherwise needed, drivers are advised to set the ACTIVE_ONLY flag in
**flags** in order not to receive plane update notifications related to a
disabled CRTC. This avoids the need to manually ignore plane updates in
driver code when the driver and/or hardware can't or just don't need to deal
with updates on disabled CRTCs, for example when supporting runtime PM.

Drivers may set the NO_DISABLE_AFTER_MODESET flag in **flags** if the relevant
display controllers require to disable a CRTC's planes when the CRTC is
disabled. This function would skip the [`drm_plane_helper_funcs.atomic_disable`](#c-struct-drm_plane_helper_funcs)
call for a plane if the CRTC of the old plane state needs a modesetting
operation. Of course, the drivers need to disable the planes in their CRTC
disable callbacks since no one else would do that.

The [`drm_atomic_helper_commit()`](#c-drm_atomic_helper_commit) default implementation doesn't set the
ACTIVE_ONLY flag to most closely match the behaviour of the legacy helpers.
This should not be copied blindly by drivers.

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

```c
void drm_atomic_helper_commit_planes_on_crtc(struct drm_crtc_state *old_crtc_state)
```

commit plane state for a CRTC

**Parameters**

- `struct drm_crtc_state *old_crtc_state`: atomic state object with the old CRTC state

**Description**

This function commits the new plane state using the plane and atomic helper
functions for planes on the specific CRTC. It assumes that the atomic state
has already been pushed into the relevant object state pointers, since this
step can no longer fail.

This function is useful when plane updates should be done CRTC-by-CRTC
instead of one global step like [`drm_atomic_helper_commit_planes()`](#c-drm_atomic_helper_commit_planes) does.

This function can only be savely used when planes are not allowed to move
between different CRTCs because this function doesn't handle inter-CRTC
dependencies. Callers need to ensure that either no such dependencies exist,
resolve them through ordering of commit calls or through some other means.

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

```c
void drm_atomic_helper_disable_planes_on_crtc(struct drm_crtc_state *old_crtc_state, bool atomic)
```

helper to disable CRTC's planes

**Parameters**

- `struct drm_crtc_state *old_crtc_state`: atomic state object with the old CRTC state
- `bool atomic`: if set, synchronize with CRTC's atomic_begin/flush hooks

**Description**

Disables all planes associated with the given CRTC. This can be
used for instance in the CRTC helper atomic_disable callback to disable
all planes.

If the atomic-parameter is set the function calls the CRTC's
atomic_begin hook before and atomic_flush hook after disabling the
planes.

It is a bug to call this function without having implemented the
[`drm_plane_helper_funcs.atomic_disable`](#c-struct-drm_plane_helper_funcs) plane hook.

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

```c
void drm_atomic_helper_cleanup_planes(struct drm_device *dev, struct drm_atomic_state *state)
```

cleanup plane resources after commit

**Parameters**

- `struct drm_device *dev`: DRM device
- `struct drm_atomic_state *state`: atomic state object being committed

**Description**

This function cleans up plane state, specifically framebuffers, from the old
configuration. Hence the old configuration must be perserved in **state** to
be able to call this function.

This function may not be called on the new state when the atomic update
fails at any point after calling [`drm_atomic_helper_prepare_planes()`](#c-drm_atomic_helper_prepare_planes). Use
[`drm_atomic_helper_unprepare_planes()`](#c-drm_atomic_helper_unprepare_planes) in this case.

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

```c
int drm_atomic_helper_swap_state(struct drm_atomic_state *state, bool stall)
```

store atomic state into current sw state

**Parameters**

- `struct drm_atomic_state *state`: atomic state
- `bool stall`: stall for preceding commits

**Description**

This function stores the atomic state into the current state pointers in all
driver objects. It should be called after all failing steps have been done
and succeeded, but before the actual hardware state is committed.

For cleanup and error recovery the current state for all changed objects will
be swapped into **state**.

With that sequence it fits perfectly into the plane prepare/cleanup sequence:

1. Call [`drm_atomic_helper_prepare_planes()`](#c-drm_atomic_helper_prepare_planes) with the staged atomic state.

2. Do any other steps that might fail.

3. Put the staged state into the current state pointers with this function.

4. Actually commit the hardware state.

5. Call [`drm_atomic_helper_cleanup_planes()`](#c-drm_atomic_helper_cleanup_planes) with **state**, which since step 3
contains the old state. Also do any other cleanup required with that state.

**stall** must be set when nonblocking commits for this driver directly access
the [`drm_plane.state`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_plane), [`drm_crtc.state`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_crtc) or [`drm_connector.state`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_connector) pointer. With
the current atomic helpers this is almost always the case, since the helpers
don't pass the right state structures to the callbacks.

**Return**

Returns 0 on success. Can return -ERESTARTSYS when **stall** is true and the
waiting for the previous commits has been interrupted.

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

```c
int drm_atomic_helper_update_plane(struct drm_plane *plane, struct drm_crtc *crtc, struct drm_framebuffer *fb, int crtc_x, int crtc_y, unsigned int crtc_w, unsigned int crtc_h, uint32_t src_x, uint32_t src_y, uint32_t src_w, uint32_t src_h, struct drm_modeset_acquire_ctx *ctx)
```

Helper for primary plane update using atomic

**Parameters**

- `struct drm_plane *plane`: plane object to update
- `struct drm_crtc *crtc`: owning CRTC of owning plane
- `struct drm_framebuffer *fb`: framebuffer to flip onto plane
- `int crtc_x`: x offset of primary plane on **crtc**
- `int crtc_y`: y offset of primary plane on **crtc**
- `unsigned int crtc_w`: width of primary plane rectangle on **crtc**
- `unsigned int crtc_h`: height of primary plane rectangle on **crtc**
- `uint32_t src_x`: x offset of **fb** for panning
- `uint32_t src_y`: y offset of **fb** for panning
- `uint32_t src_w`: width of source rectangle in **fb**
- `uint32_t src_h`: height of source rectangle in **fb**
- `struct drm_modeset_acquire_ctx *ctx`: lock acquire context

**Description**

Provides a default plane update handler using the atomic driver interface.

**Return**

Zero on success, error code on failure

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

```c
int drm_atomic_helper_disable_plane(struct drm_plane *plane, struct drm_modeset_acquire_ctx *ctx)
```

Helper for primary plane disable using atomic

**Parameters**

- `struct drm_plane *plane`: plane to disable
- `struct drm_modeset_acquire_ctx *ctx`: lock acquire context

**Description**

Provides a default plane disable handler using the atomic driver interface.

**Return**

Zero on success, error code on failure

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

```c
int drm_atomic_helper_set_config(struct drm_mode_set *set, struct drm_modeset_acquire_ctx *ctx)
```

set a new config from userspace

**Parameters**

- `struct drm_mode_set *set`: mode set configuration
- `struct drm_modeset_acquire_ctx *ctx`: lock acquisition context

**Description**

Provides a default CRTC set_config handler using the atomic driver interface.

**NOTE**

For backwards compatibility with old userspace this automatically
resets the "link-status" property to GOOD, to force any link
re-training. The SETCRTC ioctl does not define whether an update does
need a full modeset or just a plane update, hence we're allowed to do
that. See also [`drm_connector_set_link_status_property()`](/kernel/hardware/gpu/drm-kms.md#c-drm_connector_set_link_status_property).

**Return**

Returns 0 on success, negative errno numbers on failure.

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

```c
int drm_atomic_helper_disable_all(struct drm_device *dev, struct drm_modeset_acquire_ctx *ctx)
```

disable all currently active outputs

**Parameters**

- `struct drm_device *dev`: DRM device
- `struct drm_modeset_acquire_ctx *ctx`: lock acquisition context

**Description**

Loops through all connectors, finding those that aren't turned off and then
turns them off by setting their DPMS mode to OFF and deactivating the CRTC
that they are connected to.

This is used for example in suspend/resume to disable all currently active
functions when suspending. If you just want to shut down everything at e.g.
driver unload, look at [`drm_atomic_helper_shutdown()`](#c-drm_atomic_helper_shutdown).

Note that if callers haven't already acquired all modeset locks this might
return -EDEADLK, which must be handled by calling [`drm_modeset_backoff()`](/kernel/hardware/gpu/drm-kms.md#c-drm_modeset_backoff).

See also:
[`drm_atomic_helper_suspend()`](#c-drm_atomic_helper_suspend), [`drm_atomic_helper_resume()`](#c-drm_atomic_helper_resume) and
[`drm_atomic_helper_shutdown()`](#c-drm_atomic_helper_shutdown).

**Return**

0 on success or a negative error code on failure.

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

```c
int drm_atomic_helper_reset_crtc(struct drm_crtc *crtc, struct drm_modeset_acquire_ctx *ctx)
```

reset the active outputs of a CRTC

**Parameters**

- `struct drm_crtc *crtc`: DRM CRTC
- `struct drm_modeset_acquire_ctx *ctx`: lock acquisition context

**Description**

Reset the active outputs by indicating that connectors have changed.
This implies a reset of all active components available between the CRTC and
connectors.

A variant of this function exists with
`drm_bridge_helper_reset_crtc()`, dedicated to bridges.

**NOTE**

This relies on resetting [`drm_crtc_state.connectors_changed`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_crtc_state).
For drivers which optimize out unnecessary modesets this will result in
a no-op commit, achieving nothing.

**Return**

0 on success or a negative error code on failure.

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

```c
void drm_atomic_helper_shutdown(struct drm_device *dev)
```

shutdown all CRTC

**Parameters**

- `struct drm_device *dev`: DRM device

**Description**

This shuts down all CRTC, which is useful for driver unloading. Shutdown on
suspend should instead be handled with [`drm_atomic_helper_suspend()`](#c-drm_atomic_helper_suspend), since
that also takes a snapshot of the modeset state to be restored on resume.

This is just a convenience wrapper around [`drm_atomic_helper_disable_all()`](#c-drm_atomic_helper_disable_all),
and it is the atomic version of [`drm_helper_force_disable_all()`](#c-drm_helper_force_disable_all).

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

```c
struct drm_atomic_state * drm_atomic_helper_duplicate_state(struct drm_device *dev, struct drm_modeset_acquire_ctx *ctx)
```

duplicate an atomic state object

**Parameters**

- `struct drm_device *dev`: DRM device
- `struct drm_modeset_acquire_ctx *ctx`: lock acquisition context

**Description**

Makes a copy of the current atomic state by looping over all objects and
duplicating their respective states. This is used for example by suspend/
resume support code to save the state prior to suspend such that it can
be restored upon resume.

Note that this treats atomic state as persistent between save and restore.
Drivers must make sure that this is possible and won't result in confusion
or erroneous behaviour.

Note that if callers haven't already acquired all modeset locks this might
return -EDEADLK, which must be handled by calling [`drm_modeset_backoff()`](/kernel/hardware/gpu/drm-kms.md#c-drm_modeset_backoff).

See also:
[`drm_atomic_helper_suspend()`](#c-drm_atomic_helper_suspend), [`drm_atomic_helper_resume()`](#c-drm_atomic_helper_resume)

**Return**

A pointer to the copy of the atomic state object on success or an
[`ERR_PTR()`](/kernel/internals/core-api/kernel-api.md#c-ERR_PTR)-encoded error code on failure.

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

```c
struct drm_atomic_state * drm_atomic_helper_suspend(struct drm_device *dev)
```

subsystem-level suspend helper

**Parameters**

- `struct drm_device *dev`: DRM device

**Description**

Duplicates the current atomic state, disables all active outputs and then
returns a pointer to the original atomic state to the caller. Drivers can
pass this pointer to the [`drm_atomic_helper_resume()`](#c-drm_atomic_helper_resume) helper upon resume to
restore the output configuration that was active at the time the system
entered suspend.

Note that it is potentially unsafe to use this. The atomic state object
returned by this function is assumed to be persistent. Drivers must ensure
that this holds true. Before calling this function, drivers must make sure
to suspend fbdev emulation so that nothing can be using the device.

See also:
[`drm_atomic_helper_duplicate_state()`](#c-drm_atomic_helper_duplicate_state), [`drm_atomic_helper_disable_all()`](#c-drm_atomic_helper_disable_all),
[`drm_atomic_helper_resume()`](#c-drm_atomic_helper_resume), [`drm_atomic_helper_commit_duplicated_state()`](#c-drm_atomic_helper_commit_duplicated_state)

**Return**

A pointer to a copy of the state before suspend on success or an [`ERR_PTR()`](/kernel/internals/core-api/kernel-api.md#c-ERR_PTR)-
encoded error code on failure. Drivers should store the returned atomic
state object and pass it to the [`drm_atomic_helper_resume()`](#c-drm_atomic_helper_resume) helper upon
resume.

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

```c
int drm_atomic_helper_commit_duplicated_state(struct drm_atomic_state *state, struct drm_modeset_acquire_ctx *ctx)
```

commit duplicated state

**Parameters**

- `struct drm_atomic_state *state`: duplicated atomic state to commit
- `struct drm_modeset_acquire_ctx *ctx`: pointer to acquire_ctx to use for commit.

**Description**

The state returned by [`drm_atomic_helper_duplicate_state()`](#c-drm_atomic_helper_duplicate_state) and
[`drm_atomic_helper_suspend()`](#c-drm_atomic_helper_suspend) is partially invalid, and needs to
be fixed up before commit.

See also:
[`drm_atomic_helper_suspend()`](#c-drm_atomic_helper_suspend)

**Return**

0 on success or a negative error code on failure.

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

```c
int drm_atomic_helper_resume(struct drm_device *dev, struct drm_atomic_state *state)
```

subsystem-level resume helper

**Parameters**

- `struct drm_device *dev`: DRM device
- `struct drm_atomic_state *state`: atomic state to resume to

**Description**

Calls [`drm_mode_config_reset()`](/kernel/hardware/gpu/drm-kms.md#c-drm_mode_config_reset) to synchronize hardware and software states,
grabs all modeset locks and commits the atomic state object. This can be
used in conjunction with the [`drm_atomic_helper_suspend()`](#c-drm_atomic_helper_suspend) helper to
implement suspend/resume for drivers that support atomic mode-setting.

See also:
[`drm_atomic_helper_suspend()`](#c-drm_atomic_helper_suspend)

**Return**

0 on success or a negative error code on failure.

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

```c
int drm_atomic_helper_page_flip(struct drm_crtc *crtc, struct drm_framebuffer *fb, struct drm_pending_vblank_event *event, uint32_t flags, struct drm_modeset_acquire_ctx *ctx)
```

execute a legacy page flip

**Parameters**

- `struct drm_crtc *crtc`: DRM CRTC
- `struct drm_framebuffer *fb`: DRM framebuffer
- `struct drm_pending_vblank_event *event`: optional DRM event to signal upon completion
- `uint32_t flags`: flip flags for non-vblank sync'ed updates
- `struct drm_modeset_acquire_ctx *ctx`: lock acquisition context

**Description**

Provides a default [`drm_crtc_funcs.page_flip`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_crtc_funcs) implementation
using the atomic driver interface.

See also:
[`drm_atomic_helper_page_flip_target()`](#c-drm_atomic_helper_page_flip_target)

**Return**

Returns 0 on success, negative errno numbers on failure.

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

```c
int drm_atomic_helper_page_flip_target(struct drm_crtc *crtc, struct drm_framebuffer *fb, struct drm_pending_vblank_event *event, uint32_t flags, uint32_t target, struct drm_modeset_acquire_ctx *ctx)
```

do page flip on target vblank period.

**Parameters**

- `struct drm_crtc *crtc`: DRM CRTC
- `struct drm_framebuffer *fb`: DRM framebuffer
- `struct drm_pending_vblank_event *event`: optional DRM event to signal upon completion
- `uint32_t flags`: flip flags for non-vblank sync'ed updates
- `uint32_t target`: specifying the target vblank period when the flip to take effect
- `struct drm_modeset_acquire_ctx *ctx`: lock acquisition context

**Description**

Provides a default [`drm_crtc_funcs.page_flip_target`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_crtc_funcs) implementation.
Similar to [`drm_atomic_helper_page_flip()`](#c-drm_atomic_helper_page_flip) with extra parameter to specify
target vblank period to flip.

**Return**

Returns 0 on success, negative errno numbers on failure.

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

```c
u32 * drm_atomic_helper_bridge_propagate_bus_fmt(struct drm_bridge *bridge, struct drm_bridge_state *bridge_state, struct drm_crtc_state *crtc_state, struct drm_connector_state *conn_state, u32 output_fmt, unsigned int *num_input_fmts)
```

Propagate output format to the input end of a bridge

**Parameters**

- `struct drm_bridge *bridge`: bridge control structure
- `struct drm_bridge_state *bridge_state`: new bridge state
- `struct drm_crtc_state *crtc_state`: new CRTC state
- `struct drm_connector_state *conn_state`: new connector state
- `u32 output_fmt`: tested output bus format
- `unsigned int *num_input_fmts`: will contain the size of the returned array

**Description**

This helper is a pluggable implementation of the
[`drm_bridge_funcs.atomic_get_input_bus_fmts`](#c-struct-drm_bridge_funcs) operation for bridges that don't
modify the bus configuration between their input and their output. It
returns an array of input formats with a single element set to **output_fmt**.

**Return**

a valid format array of size **num_input_fmts**, or NULL if the allocation
failed


<a id="rst-atomic-state-reset-and-initialization"></a>

### Atomic State Reset and Initialization


Both the drm core and the atomic helpers assume that there is always the full
and correct atomic software state for all connectors, CRTCs and planes
available. Which is a bit a problem on driver load and also after system
suspend. One way to solve this is to have a hardware state read-out
infrastructure which reconstructs the full software state (e.g. the i915
driver).

The simpler solution is to just reset the software state to everything off,
which is easiest to do by calling [`drm_mode_config_reset()`](/kernel/hardware/gpu/drm-kms.md#c-drm_mode_config_reset). To facilitate this
the atomic helpers provide default reset implementations for all hooks.

On the upside the precise state tracking of atomic simplifies system suspend
and resume a lot. For drivers using [`drm_mode_config_reset()`](/kernel/hardware/gpu/drm-kms.md#c-drm_mode_config_reset) a complete recipe
is implemented in [`drm_atomic_helper_suspend()`](#c-drm_atomic_helper_suspend) and [`drm_atomic_helper_resume()`](#c-drm_atomic_helper_resume).
For other drivers the building blocks are split out, see the documentation
for these functions.


<a id="rst-atomic-state-helper-reference"></a>

### Atomic State Helper Reference


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

```c
void __drm_atomic_helper_crtc_state_reset(struct drm_crtc_state *crtc_state, struct drm_crtc *crtc)
```

reset the CRTC state

**Parameters**

- `struct drm_crtc_state *crtc_state`: atomic CRTC state, must not be NULL
- `struct drm_crtc *crtc`: CRTC object, must not be NULL

**Description**

Initializes the newly allocated **crtc_state** with default
values. This is useful for drivers that subclass the CRTC state.

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

```c
void __drm_atomic_helper_crtc_reset(struct drm_crtc *crtc, struct drm_crtc_state *crtc_state)
```

reset state on CRTC

**Parameters**

- `struct drm_crtc *crtc`: drm CRTC
- `struct drm_crtc_state *crtc_state`: CRTC state to assign

**Description**

Initializes the newly allocated **crtc_state** and assigns it to
the [`drm_crtc->state`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_crtc) pointer of **crtc**, usually required when
initializing the drivers or when called from the [`drm_crtc_funcs.reset`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_crtc_funcs)
hook.

This is useful for drivers that subclass the CRTC state.

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

```c
void drm_atomic_helper_crtc_reset(struct drm_crtc *crtc)
```

default [`drm_crtc_funcs.reset`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_crtc_funcs) hook for CRTCs

**Parameters**

- `struct drm_crtc *crtc`: drm CRTC

**Description**

Resets the atomic state for **crtc** by freeing the state pointer (which might
be NULL, e.g. at driver load time) and allocating a new empty state object.

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

```c
void __drm_atomic_helper_crtc_duplicate_state(struct drm_crtc *crtc, struct drm_crtc_state *state)
```

copy atomic CRTC state

**Parameters**

- `struct drm_crtc *crtc`: CRTC object
- `struct drm_crtc_state *state`: atomic CRTC state

**Description**

Copies atomic state from a CRTC's current state and resets inferred values.
This is useful for drivers that subclass the CRTC state.

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

```c
struct drm_crtc_state * drm_atomic_helper_crtc_duplicate_state(struct drm_crtc *crtc)
```

default state duplicate hook

**Parameters**

- `struct drm_crtc *crtc`: drm CRTC

**Description**

Default CRTC state duplicate hook for drivers which don't have their own
subclassed CRTC state structure.

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

```c
void __drm_atomic_helper_crtc_destroy_state(struct drm_crtc_state *state)
```

release CRTC state

**Parameters**

- `struct drm_crtc_state *state`: CRTC state object to release

**Description**

Releases all resources stored in the CRTC state without actually freeing
the memory of the CRTC state. This is useful for drivers that subclass the
CRTC state.

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

```c
void drm_atomic_helper_crtc_destroy_state(struct drm_crtc *crtc, struct drm_crtc_state *state)
```

default state destroy hook

**Parameters**

- `struct drm_crtc *crtc`: drm CRTC
- `struct drm_crtc_state *state`: CRTC state object to release

**Description**

Default CRTC state destroy hook for drivers which don't have their own
subclassed CRTC state structure.

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

```c
void __drm_atomic_helper_plane_state_reset(struct drm_plane_state *plane_state, struct drm_plane *plane)
```

resets plane state to default values

**Parameters**

- `struct drm_plane_state *plane_state`: atomic plane state, must not be NULL
- `struct drm_plane *plane`: plane object, must not be NULL

**Description**

Initializes the newly allocated **plane_state** with default
values. This is useful for drivers that subclass the CRTC state.

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

```c
void __drm_atomic_helper_plane_reset(struct drm_plane *plane, struct drm_plane_state *plane_state)
```

reset state on plane

**Parameters**

- `struct drm_plane *plane`: drm plane
- `struct drm_plane_state *plane_state`: plane state to assign

**Description**

Initializes the newly allocated **plane_state** and assigns it to
the [`drm_crtc->state`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_crtc) pointer of **plane**, usually required when
initializing the drivers or when called from the [`drm_plane_funcs.reset`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_plane_funcs)
hook.

This is useful for drivers that subclass the plane state.

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

```c
void drm_atomic_helper_plane_reset(struct drm_plane *plane)
```

default [`drm_plane_funcs.reset`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_plane_funcs) hook for planes

**Parameters**

- `struct drm_plane *plane`: drm plane

**Description**

Resets the atomic state for **plane** by freeing the state pointer (which might
be NULL, e.g. at driver load time) and allocating a new empty state object.

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

```c
void __drm_atomic_helper_plane_duplicate_state(struct drm_plane *plane, struct drm_plane_state *state)
```

copy atomic plane state

**Parameters**

- `struct drm_plane *plane`: plane object
- `struct drm_plane_state *state`: atomic plane state

**Description**

Copies atomic state from a plane's current state. This is useful for
drivers that subclass the plane state.

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

```c
struct drm_plane_state * drm_atomic_helper_plane_duplicate_state(struct drm_plane *plane)
```

default state duplicate hook

**Parameters**

- `struct drm_plane *plane`: drm plane

**Description**

Default plane state duplicate hook for drivers which don't have their own
subclassed plane state structure.

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

```c
void __drm_atomic_helper_plane_destroy_state(struct drm_plane_state *state)
```

release plane state

**Parameters**

- `struct drm_plane_state *state`: plane state object to release

**Description**

Releases all resources stored in the plane state without actually freeing
the memory of the plane state. This is useful for drivers that subclass the
plane state.

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

```c
void drm_atomic_helper_plane_destroy_state(struct drm_plane *plane, struct drm_plane_state *state)
```

default state destroy hook

**Parameters**

- `struct drm_plane *plane`: drm plane
- `struct drm_plane_state *state`: plane state object to release

**Description**

Default plane state destroy hook for drivers which don't have their own
subclassed plane state structure.

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

```c
void __drm_atomic_helper_connector_state_reset(struct drm_connector_state *conn_state, struct drm_connector *connector)
```

reset the connector state

**Parameters**

- `struct drm_connector_state *conn_state`: atomic connector state, must not be NULL
- `struct drm_connector *connector`: connectotr object, must not be NULL

**Description**

Initializes the newly allocated **conn_state** with default
values. This is useful for drivers that subclass the connector state.

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

```c
void __drm_atomic_helper_connector_reset(struct drm_connector *connector, struct drm_connector_state *conn_state)
```

reset state on connector

**Parameters**

- `struct drm_connector *connector`: drm connector
- `struct drm_connector_state *conn_state`: connector state to assign

**Description**

Initializes the newly allocated **conn_state** and assigns it to
the [`drm_connector->state`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_connector) pointer of **connector**, usually required when
initializing the drivers or when called from the [`drm_connector_funcs.reset`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_connector_funcs)
hook.

This is useful for drivers that subclass the connector state.

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

```c
void drm_atomic_helper_connector_reset(struct drm_connector *connector)
```

default [`drm_connector_funcs.reset`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_connector_funcs) hook for connectors

**Parameters**

- `struct drm_connector *connector`: drm connector

**Description**

Resets the atomic state for **connector** by freeing the state pointer (which
might be NULL, e.g. at driver load time) and allocating a new empty state
object.

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

```c
void drm_atomic_helper_connector_tv_margins_reset(struct drm_connector *connector)
```

Resets TV connector properties

**Parameters**

- `struct drm_connector *connector`: DRM connector

**Description**

Resets the TV-related properties attached to a connector.

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

```c
void drm_atomic_helper_connector_tv_reset(struct drm_connector *connector)
```

Resets Analog TV connector properties

**Parameters**

- `struct drm_connector *connector`: DRM connector

**Description**

Resets the analog TV properties attached to a connector

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

```c
int drm_atomic_helper_connector_tv_check(struct drm_connector *connector, struct drm_atomic_state *state)
```

Validate an analog TV connector state

**Parameters**

- `struct drm_connector *connector`: DRM Connector
- `struct drm_atomic_state *state`: the DRM State object

**Description**

Checks the state object to see if the requested state is valid for an
analog TV connector.

**Return**

`0` for success, a negative error code on error.

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

```c
void __drm_atomic_helper_connector_duplicate_state(struct drm_connector *connector, struct drm_connector_state *state)
```

copy atomic connector state

**Parameters**

- `struct drm_connector *connector`: connector object
- `struct drm_connector_state *state`: atomic connector state

**Description**

Copies atomic state from a connector's current state. This is useful for
drivers that subclass the connector state.

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

```c
struct drm_connector_state * drm_atomic_helper_connector_duplicate_state(struct drm_connector *connector)
```

default state duplicate hook

**Parameters**

- `struct drm_connector *connector`: drm connector

**Description**

Default connector state duplicate hook for drivers which don't have their own
subclassed connector state structure.

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

```c
void __drm_atomic_helper_connector_destroy_state(struct drm_connector_state *state)
```

release connector state

**Parameters**

- `struct drm_connector_state *state`: connector state object to release

**Description**

Releases all resources stored in the connector state without actually
freeing the memory of the connector state. This is useful for drivers that
subclass the connector state.

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

```c
void drm_atomic_helper_connector_destroy_state(struct drm_connector *connector, struct drm_connector_state *state)
```

default state destroy hook

**Parameters**

- `struct drm_connector *connector`: drm connector
- `struct drm_connector_state *state`: connector state object to release

**Description**

Default connector state destroy hook for drivers which don't have their own
subclassed connector state structure.

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

```c
void __drm_atomic_helper_private_obj_duplicate_state(struct drm_private_obj *obj, struct drm_private_state *state)
```

copy atomic private state

**Parameters**

- `struct drm_private_obj *obj`: CRTC object
- `struct drm_private_state *state`: new private object state

**Description**

Copies atomic state from a private objects's current state and resets inferred values.
This is useful for drivers that subclass the private state.

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

```c
void __drm_atomic_helper_bridge_duplicate_state(struct drm_bridge *bridge, struct drm_bridge_state *state)
```

Copy atomic bridge state

**Parameters**

- `struct drm_bridge *bridge`: bridge object
- `struct drm_bridge_state *state`: atomic bridge state

**Description**

Copies atomic state from a bridge's current state and resets inferred values.
This is useful for drivers that subclass the bridge state.

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

```c
struct drm_bridge_state * drm_atomic_helper_bridge_duplicate_state(struct drm_bridge *bridge)
```

Duplicate a bridge state object

**Parameters**

- `struct drm_bridge *bridge`: bridge object

**Description**

Allocates a new bridge state and initializes it with the current bridge
state values. This helper is meant to be used as a bridge
[`drm_bridge_funcs.atomic_duplicate_state`](#c-struct-drm_bridge_funcs) hook for bridges that don't
subclass the bridge state.

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

```c
void drm_atomic_helper_bridge_destroy_state(struct drm_bridge *bridge, struct drm_bridge_state *state)
```

Destroy a bridge state object

**Parameters**

- `struct drm_bridge *bridge`: the bridge this state refers to
- `struct drm_bridge_state *state`: bridge state to destroy

**Description**

Destroys a bridge state previously created by
[`drm_atomic_helper_bridge_reset`](#c-drm_atomic_helper_bridge_reset)() or
[`drm_atomic_helper_bridge_duplicate_state`](#c-drm_atomic_helper_bridge_duplicate_state)(). This helper is meant to be
used as a bridge [`drm_bridge_funcs.atomic_destroy_state`](#c-struct-drm_bridge_funcs) hook for bridges
that don't subclass the bridge state.

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

```c
void __drm_atomic_helper_bridge_reset(struct drm_bridge *bridge, struct drm_bridge_state *state)
```

Initialize a bridge state to its default

**Parameters**

- `struct drm_bridge *bridge`: the bridge this state refers to
- `struct drm_bridge_state *state`: bridge state to initialize

**Description**

Initializes the bridge state to default values. This is meant to be called
by the bridge [`drm_bridge_funcs.atomic_reset`](#c-struct-drm_bridge_funcs) hook for bridges that subclass
the bridge state.

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

```c
struct drm_bridge_state * drm_atomic_helper_bridge_reset(struct drm_bridge *bridge)
```

Allocate and initialize a bridge state to its default

**Parameters**

- `struct drm_bridge *bridge`: the bridge this state refers to

**Description**

Allocates the bridge state and initializes it to default values. This helper
is meant to be used as a bridge [`drm_bridge_funcs.atomic_reset`](#c-struct-drm_bridge_funcs) hook for
bridges that don't subclass the bridge state.


<a id="rst-gem-atomic-helper-reference"></a>

### GEM Atomic Helper Reference


The GEM atomic helpers library implements generic atomic-commit
functions for drivers that use GEM objects. Currently, it provides
synchronization helpers, and plane state and framebuffer BO mappings
for planes with shadow buffers.

Before scanout, a plane's framebuffer needs to be synchronized with
possible writers that draw into the framebuffer. All drivers should
call [`drm_gem_plane_helper_prepare_fb()`](#c-drm_gem_plane_helper_prepare_fb) from their implementation of
struct `drm_plane_helper.prepare_fb` . It sets the plane's fence from
the framebuffer so that the DRM core can synchronize access automatically.
[`drm_gem_plane_helper_prepare_fb()`](#c-drm_gem_plane_helper_prepare_fb) can also be used directly as
implementation of prepare_fb.

```c
#include <drm/drm_gem_atomic_helper.h>

struct drm_plane_helper_funcs driver_plane_helper_funcs = {
        ...,
        . prepare_fb = drm_gem_plane_helper_prepare_fb,
};
```

A driver using a shadow buffer copies the content of the shadow buffers
into the HW's framebuffer memory during an atomic update. This requires
a mapping of the shadow buffer into kernel address space. The mappings
cannot be established by commit-tail functions, such as atomic_update,
as this would violate locking rules around [`dma_buf_vmap()`](/kernel/hardware/driver-api/io-and-dma/dma-buf.md#c-dma_buf_vmap).

The helpers for shadow-buffered planes establish and release mappings,
and provide struct drm_shadow_plane_state, which stores the plane's mapping
for commit-tail functions.

Shadow-buffered planes can easily be enabled by using the provided macros
`DRM_GEM_SHADOW_PLANE_FUNCS` and `DRM_GEM_SHADOW_PLANE_HELPER_FUNCS`.
These macros set up the plane and plane-helper callbacks to point to the
shadow-buffer helpers.

```c
#include <drm/drm_gem_atomic_helper.h>

struct drm_plane_funcs driver_plane_funcs = {
        ...,
        DRM_GEM_SHADOW_PLANE_FUNCS,
};

struct drm_plane_helper_funcs driver_plane_helper_funcs = {
        ...,
        DRM_GEM_SHADOW_PLANE_HELPER_FUNCS,
};
```

In the driver's atomic-update function, shadow-buffer mappings are available
from the plane state. Use [`to_drm_shadow_plane_state()`](#c-to_drm_shadow_plane_state) to upcast from
struct drm_plane_state.

```c
void driver_plane_atomic_update(struct drm_plane *plane,
                                struct drm_plane_state *old_plane_state)
{
        struct drm_plane_state *plane_state = plane->state;
        struct drm_shadow_plane_state *shadow_plane_state =
                to_drm_shadow_plane_state(plane_state);

        // access shadow buffer via shadow_plane_state->map
}
```

A mapping address for each of the framebuffer's buffer object is stored in
struct [`drm_shadow_plane_state.map`](#c-struct-drm_shadow_plane_state). The mappings are valid while the state
is being used.

Drivers that use struct drm_simple_display_pipe can use
`DRM_GEM_SIMPLE_DISPLAY_PIPE_SHADOW_PLANE_FUNCS` to initialize the rsp
callbacks. Access to shadow-buffer mappings is similar to regular
atomic_update.

```c
struct drm_simple_display_pipe_funcs driver_pipe_funcs = {
        ...,
        DRM_GEM_SIMPLE_DISPLAY_PIPE_SHADOW_PLANE_FUNCS,
};

void driver_pipe_enable(struct drm_simple_display_pipe *pipe,
                        struct drm_crtc_state *crtc_state,
                        struct drm_plane_state *plane_state)
{
        struct drm_shadow_plane_state *shadow_plane_state =
                to_drm_shadow_plane_state(plane_state);

        // access shadow buffer via shadow_plane_state->map
}
```



#### <a id="c-DRM_SHADOW_PLANE_MAX_WIDTH"></a>`DRM_SHADOW_PLANE_MAX_WIDTH`

```c
DRM_SHADOW_PLANE_MAX_WIDTH
```

Maximum width of a plane's shadow buffer in pixels

**Description**

For drivers with shadow planes, the maximum width of the framebuffer is
usually independent from hardware limitations. Drivers can initialize struct
drm_mode_config.max_width from DRM_SHADOW_PLANE_MAX_WIDTH.

#### <a id="c-DRM_SHADOW_PLANE_MAX_HEIGHT"></a>`DRM_SHADOW_PLANE_MAX_HEIGHT`

```c
DRM_SHADOW_PLANE_MAX_HEIGHT
```

Maximum height of a plane's shadow buffer in scanlines

**Description**

For drivers with shadow planes, the maximum height of the framebuffer is
usually independent from hardware limitations. Drivers can initialize struct
drm_mode_config.max_height from DRM_SHADOW_PLANE_MAX_HEIGHT.

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

plane state for planes with shadow buffers

**Definition**

```c
struct drm_shadow_plane_state {
    struct drm_plane_state base;
    struct drm_format_conv_state fmtcnv_state;
    struct iosys_map map[DRM_FORMAT_MAX_PLANES];
    struct iosys_map data[DRM_FORMAT_MAX_PLANES];
};
```

**Members**

- `base`: plane state
- `fmtcnv_state`: Format-conversion state

  Per-plane state for format conversion.
  Flags for copying shadow buffers into backend storage. Also holds
  temporary storage for format conversion.
- `map`: Mappings of the plane's framebuffer BOs in to kernel address space

  The memory mappings stored in map should be established in the plane's
  prepare_fb callback and removed in the cleanup_fb callback.
- `data`: Address of each framebuffer BO's data

  The address of the data stored in each mapping. This is different
  for framebuffers with non-zero offset fields.

**Description**

For planes that use a shadow buffer, struct drm_shadow_plane_state
provides the regular plane state plus mappings of the shadow buffer
into kernel address space.

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

```c
struct drm_shadow_plane_state * to_drm_shadow_plane_state(struct drm_plane_state *state)
```

upcasts from struct drm_plane_state

**Parameters**

- `struct drm_plane_state *state`: the plane state

#### <a id="c-DRM_GEM_SHADOW_PLANE_FUNCS"></a>`DRM_GEM_SHADOW_PLANE_FUNCS`

```c
DRM_GEM_SHADOW_PLANE_FUNCS
```

Initializes struct drm_plane_funcs for shadow-buffered planes

**Description**

Drivers may use GEM BOs as shadow buffers over the framebuffer memory. This
macro initializes struct drm_plane_funcs to use the rsp helper functions.

#### <a id="c-DRM_GEM_SHADOW_PLANE_HELPER_FUNCS"></a>`DRM_GEM_SHADOW_PLANE_HELPER_FUNCS`

```c
DRM_GEM_SHADOW_PLANE_HELPER_FUNCS
```

Initializes struct drm_plane_helper_funcs for shadow-buffered planes

**Description**

Drivers may use GEM BOs as shadow buffers over the framebuffer memory. This
macro initializes struct drm_plane_helper_funcs to use the rsp helper
functions.

#### <a id="c-DRM_GEM_SIMPLE_DISPLAY_PIPE_SHADOW_PLANE_FUNCS"></a>`DRM_GEM_SIMPLE_DISPLAY_PIPE_SHADOW_PLANE_FUNCS`

```c
DRM_GEM_SIMPLE_DISPLAY_PIPE_SHADOW_PLANE_FUNCS
```

Initializes struct drm_simple_display_pipe_funcs for shadow-buffered planes

**Description**

Drivers may use GEM BOs as shadow buffers over the framebuffer memory. This
macro initializes struct drm_simple_display_pipe_funcs to use the rsp helper
functions.



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

```c
int drm_gem_plane_helper_prepare_fb(struct drm_plane *plane, struct drm_plane_state *state)
```

Prepare a GEM backed framebuffer

**Parameters**

- `struct drm_plane *plane`: Plane
- `struct drm_plane_state *state`: Plane state the fence will be attached to

**Description**

This function extracts the exclusive fence from [`drm_gem_object.resv`](/kernel/hardware/gpu/drm-mm.md#c-struct-drm_gem_object) and
attaches it to plane state for the atomic helper to wait on. This is
necessary to correctly implement implicit synchronization for any buffers
shared as a struct [`dma_buf`](/kernel/hardware/driver-api/io-and-dma/dma-buf.md#c-struct-dma_buf). This function can be used as the
[`drm_plane_helper_funcs.prepare_fb`](#c-struct-drm_plane_helper_funcs) callback.

There is no need for [`drm_plane_helper_funcs.cleanup_fb`](#c-struct-drm_plane_helper_funcs) hook for simple
GEM based framebuffer drivers which have their buffers always pinned in
memory.

This function is the default implementation for GEM drivers of
[`drm_plane_helper_funcs.prepare_fb`](#c-struct-drm_plane_helper_funcs) if no callback is provided.

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

```c
void __drm_gem_duplicate_shadow_plane_state(struct drm_plane *plane, struct drm_shadow_plane_state *new_shadow_plane_state)
```

duplicates shadow-buffered plane state

**Parameters**

- `struct drm_plane *plane`: the plane
- `struct drm_shadow_plane_state *new_shadow_plane_state`: the new shadow-buffered plane state

**Description**

This function duplicates shadow-buffered plane state. This is helpful for drivers
that subclass struct drm_shadow_plane_state.

The function does not duplicate existing mappings of the shadow buffers.
Mappings are maintained during the atomic commit by the plane's prepare_fb
and cleanup_fb helpers. See `drm_gem_prepare_shadow_fb()` and `drm_gem_cleanup_shadow_fb()`
for corresponding helpers.

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

```c
struct drm_plane_state * drm_gem_duplicate_shadow_plane_state(struct drm_plane *plane)
```

duplicates shadow-buffered plane state

**Parameters**

- `struct drm_plane *plane`: the plane

**Description**

This function implements struct [`drm_plane_funcs.atomic_duplicate_state`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_plane_funcs) for
shadow-buffered planes. It assumes the existing state to be of type
struct drm_shadow_plane_state and it allocates the new state to be of this
type.

The function does not duplicate existing mappings of the shadow buffers.
Mappings are maintained during the atomic commit by the plane's prepare_fb
and cleanup_fb helpers. See `drm_gem_prepare_shadow_fb()` and `drm_gem_cleanup_shadow_fb()`
for corresponding helpers.

**Return**

A pointer to a new plane state on success, or NULL otherwise.

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

```c
void __drm_gem_destroy_shadow_plane_state(struct drm_shadow_plane_state *shadow_plane_state)
```

cleans up shadow-buffered plane state

**Parameters**

- `struct drm_shadow_plane_state *shadow_plane_state`: the shadow-buffered plane state

**Description**

This function cleans up shadow-buffered plane state. Helpful for drivers that
subclass struct drm_shadow_plane_state.

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

```c
void drm_gem_destroy_shadow_plane_state(struct drm_plane *plane, struct drm_plane_state *plane_state)
```

deletes shadow-buffered plane state

**Parameters**

- `struct drm_plane *plane`: the plane
- `struct drm_plane_state *plane_state`: the plane state of type struct drm_shadow_plane_state

**Description**

This function implements struct [`drm_plane_funcs.atomic_destroy_state`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_plane_funcs)
for shadow-buffered planes. It expects that mappings of shadow buffers
have been released already.

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

```c
void __drm_gem_reset_shadow_plane(struct drm_plane *plane, struct drm_shadow_plane_state *shadow_plane_state)
```

resets a shadow-buffered plane

**Parameters**

- `struct drm_plane *plane`: the plane
- `struct drm_shadow_plane_state *shadow_plane_state`: the shadow-buffered plane state

**Description**

This function resets state for shadow-buffered planes. Helpful
for drivers that subclass struct drm_shadow_plane_state.

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

```c
void drm_gem_reset_shadow_plane(struct drm_plane *plane)
```

resets a shadow-buffered plane

**Parameters**

- `struct drm_plane *plane`: the plane

**Description**

This function implements struct [`drm_plane_funcs.reset_plane`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_plane_funcs) for
shadow-buffered planes. It assumes the current plane state to be
of type struct drm_shadow_plane and it allocates the new state of
this type.

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

```c
int drm_gem_begin_shadow_fb_access(struct drm_plane *plane, struct drm_plane_state *plane_state)
```

prepares shadow framebuffers for CPU access

**Parameters**

- `struct drm_plane *plane`: the plane
- `struct drm_plane_state *plane_state`: the plane state of type struct drm_shadow_plane_state

**Description**

This function implements struct [`drm_plane_helper_funcs.begin_fb_access`](#c-struct-drm_plane_helper_funcs). It
maps all buffer objects of the plane's framebuffer into kernel address
space and stores them in struct [`drm_shadow_plane_state.map`](#c-struct-drm_shadow_plane_state). The first data
bytes are available in struct [`drm_shadow_plane_state.data`](#c-struct-drm_shadow_plane_state).

See [`drm_gem_end_shadow_fb_access()`](#c-drm_gem_end_shadow_fb_access) for cleanup.

**Return**

0 on success, or a negative errno code otherwise.

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

```c
void drm_gem_end_shadow_fb_access(struct drm_plane *plane, struct drm_plane_state *plane_state)
```

releases shadow framebuffers from CPU access

**Parameters**

- `struct drm_plane *plane`: the plane
- `struct drm_plane_state *plane_state`: the plane state of type struct drm_shadow_plane_state

**Description**

This function implements struct [`drm_plane_helper_funcs.end_fb_access`](#c-struct-drm_plane_helper_funcs). It
undoes all effects of [`drm_gem_begin_shadow_fb_access()`](#c-drm_gem_begin_shadow_fb_access) in reverse order.

See [`drm_gem_begin_shadow_fb_access()`](#c-drm_gem_begin_shadow_fb_access) for more information.

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

```c
int drm_gem_simple_kms_begin_shadow_fb_access(struct drm_simple_display_pipe *pipe, struct drm_plane_state *plane_state)
```

prepares shadow framebuffers for CPU access

**Parameters**

- `struct drm_simple_display_pipe *pipe`: the simple display pipe
- `struct drm_plane_state *plane_state`: the plane state of type struct drm_shadow_plane_state

**Description**

This function implements struct drm_simple_display_funcs.begin_fb_access.

See [`drm_gem_begin_shadow_fb_access()`](#c-drm_gem_begin_shadow_fb_access) for details and
`drm_gem_simple_kms_cleanup_shadow_fb()` for cleanup.

**Return**

0 on success, or a negative errno code otherwise.

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

```c
void drm_gem_simple_kms_end_shadow_fb_access(struct drm_simple_display_pipe *pipe, struct drm_plane_state *plane_state)
```

releases shadow framebuffers from CPU access

**Parameters**

- `struct drm_simple_display_pipe *pipe`: the simple display pipe
- `struct drm_plane_state *plane_state`: the plane state of type struct drm_shadow_plane_state

**Description**

This function implements struct drm_simple_display_funcs.end_fb_access.
It undoes all effects of [`drm_gem_simple_kms_begin_shadow_fb_access()`](#c-drm_gem_simple_kms_begin_shadow_fb_access) in
reverse order.

See [`drm_gem_simple_kms_begin_shadow_fb_access()`](#c-drm_gem_simple_kms_begin_shadow_fb_access).

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

```c
void drm_gem_simple_kms_reset_shadow_plane(struct drm_simple_display_pipe *pipe)
```

resets a shadow-buffered plane

**Parameters**

- `struct drm_simple_display_pipe *pipe`: the simple display pipe

**Description**

This function implements struct drm_simple_display_funcs.reset_plane
for shadow-buffered planes.

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

```c
struct drm_plane_state * drm_gem_simple_kms_duplicate_shadow_plane_state(struct drm_simple_display_pipe *pipe)
```

duplicates shadow-buffered plane state

**Parameters**

- `struct drm_simple_display_pipe *pipe`: the simple display pipe

**Description**

This function implements struct drm_simple_display_funcs.duplicate_plane_state
for shadow-buffered planes. It does not duplicate existing mappings of the shadow
buffers. Mappings are maintained during the atomic commit by the plane's prepare_fb
and cleanup_fb helpers.

**Return**

A pointer to a new plane state on success, or NULL otherwise.

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

```c
void drm_gem_simple_kms_destroy_shadow_plane_state(struct drm_simple_display_pipe *pipe, struct drm_plane_state *plane_state)
```

resets shadow-buffered plane state

**Parameters**

- `struct drm_simple_display_pipe *pipe`: the simple display pipe
- `struct drm_plane_state *plane_state`: the plane state of type struct drm_shadow_plane_state

**Description**

This function implements struct drm_simple_display_funcs.destroy_plane_state
for shadow-buffered planes. It expects that mappings of shadow buffers
have been released already.


<a id="rst-vblank-helper-reference"></a>

### VBLANK Helper Reference


The vblank helper library provides functions for supporting vertical
blanking in DRM drivers.

For vblank timers, several callback implementations are available.
Drivers enable support for vblank timers by setting the vblank callbacks
in struct [`drm_crtc_funcs`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_crtc_funcs) to the helpers provided by this library. The
initializer macro DRM_CRTC_VBLANK_TIMER_FUNCS does this conveniently.
The driver further has to send the VBLANK event from its atomic_flush
callback and control vblank from the CRTC's atomic_enable and atomic_disable
callbacks. The callbacks are located in struct [`drm_crtc_helper_funcs`](#c-struct-drm_crtc_helper_funcs).
The vblank helper library provides implementations of these callbacks
for drivers without further requirements. The initializer macro
DRM_CRTC_HELPER_VBLANK_FUNCS sets them coveniently.

Once the driver enables vblank support with [`drm_vblank_init()`](/kernel/hardware/gpu/drm-kms.md#c-drm_vblank_init), each
CRTC's vblank timer fires according to the programmed display mode. By
default, the vblank timer invokes [`drm_crtc_handle_vblank()`](/kernel/hardware/gpu/drm-kms.md#c-drm_crtc_handle_vblank). Drivers with
more specific requirements can set their own handler function in
struct [`drm_crtc_helper_funcs.handle_vblank_timeout`](#c-struct-drm_crtc_helper_funcs).



#### <a id="c-DRM_CRTC_HELPER_VBLANK_FUNCS"></a>`DRM_CRTC_HELPER_VBLANK_FUNCS`

```c
DRM_CRTC_HELPER_VBLANK_FUNCS
```

Default implementation for VBLANK helpers

**Description**

This macro initializes struct [`drm_crtc_helper_funcs`](#c-struct-drm_crtc_helper_funcs) to default helpers
for VBLANK handling.

#### <a id="c-DRM_CRTC_VBLANK_TIMER_FUNCS"></a>`DRM_CRTC_VBLANK_TIMER_FUNCS`

```c
DRM_CRTC_VBLANK_TIMER_FUNCS
```

Default implementation for VBLANK timers

**Description**

This macro initializes struct [`drm_crtc_funcs`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_crtc_funcs) to default helpers for
VBLANK timers.



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

```c
void drm_crtc_vblank_atomic_flush(struct drm_crtc *crtc, struct drm_atomic_state *state)
```

Implements struct [`drm_crtc_helper_funcs.atomic_flush`](#c-struct-drm_crtc_helper_funcs)

**Parameters**

- `struct drm_crtc *crtc`: The CRTC
- `struct drm_atomic_state *state`: The atomic state to apply

**Description**

The helper [`drm_crtc_vblank_atomic_flush()`](#c-drm_crtc_vblank_atomic_flush) implements atomic_flush of
struct drm_crtc_helper_funcs for CRTCs that only need to send out a
VBLANK event.

See also struct [`drm_crtc_helper_funcs.atomic_flush`](#c-struct-drm_crtc_helper_funcs).

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

```c
void drm_crtc_vblank_atomic_enable(struct drm_crtc *crtc, struct drm_atomic_state *state)
```

Implements struct [`drm_crtc_helper_funcs.atomic_enable`](#c-struct-drm_crtc_helper_funcs)

**Parameters**

- `struct drm_crtc *crtc`: The CRTC
- `struct drm_atomic_state *state`: The atomic state

**Description**

The helper [`drm_crtc_vblank_atomic_enable()`](#c-drm_crtc_vblank_atomic_enable) implements atomic_enable
of struct drm_crtc_helper_funcs for CRTCs the only need to enable VBLANKs.

See also struct [`drm_crtc_helper_funcs.atomic_enable`](#c-struct-drm_crtc_helper_funcs).

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

```c
void drm_crtc_vblank_atomic_disable(struct drm_crtc *crtc, struct drm_atomic_state *state)
```

Implements struct [`drm_crtc_helper_funcs.atomic_disable`](#c-struct-drm_crtc_helper_funcs)

**Parameters**

- `struct drm_crtc *crtc`: The CRTC
- `struct drm_atomic_state *state`: The atomic state

**Description**

The helper [`drm_crtc_vblank_atomic_disable()`](#c-drm_crtc_vblank_atomic_disable) implements atomic_disable
of struct drm_crtc_helper_funcs for CRTCs the only need to disable VBLANKs.

See also struct [`drm_crtc_funcs.atomic_disable`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_crtc_funcs).

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

```c
int drm_crtc_vblank_helper_enable_vblank_timer(struct drm_crtc *crtc)
```

Implements struct [`drm_crtc_funcs.enable_vblank`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_crtc_funcs)

**Parameters**

- `struct drm_crtc *crtc`: The CRTC

**Description**

The helper [`drm_crtc_vblank_helper_enable_vblank_timer()`](#c-drm_crtc_vblank_helper_enable_vblank_timer) implements
enable_vblank of struct drm_crtc_helper_funcs for CRTCs that require
a VBLANK timer. It sets up the timer on the first invocation. The
started timer expires after the current frame duration. See struct
[`drm_vblank_crtc.framedur_ns`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_vblank_crtc).

See also struct [`drm_crtc_helper_funcs.enable_vblank`](#c-struct-drm_crtc_helper_funcs).

**Return**

0 on success, or a negative errno code otherwise.

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

```c
void drm_crtc_vblank_helper_disable_vblank_timer(struct drm_crtc *crtc)
```

Implements struct [`drm_crtc_funcs.disable_vblank`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_crtc_funcs)

**Parameters**

- `struct drm_crtc *crtc`: The CRTC

**Description**

The helper [`drm_crtc_vblank_helper_disable_vblank_timer()`](#c-drm_crtc_vblank_helper_disable_vblank_timer) implements
disable_vblank of struct drm_crtc_funcs for CRTCs that require a
VBLANK timer.

See also struct [`drm_crtc_helper_funcs.disable_vblank`](#c-struct-drm_crtc_helper_funcs).

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

```c
bool drm_crtc_vblank_helper_get_vblank_timestamp_from_timer(struct drm_crtc *crtc, int *max_error, ktime_t *vblank_time, bool in_vblank_irq)
```

Implements struct [`drm_crtc_funcs.get_vblank_timestamp`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_crtc_funcs)

**Parameters**

- `struct drm_crtc *crtc`: The CRTC
- `int *max_error`: Maximum acceptable error
- `ktime_t *vblank_time`: Returns the next vblank timestamp
- `bool in_vblank_irq`: True is called from [`drm_crtc_handle_vblank()`](/kernel/hardware/gpu/drm-kms.md#c-drm_crtc_handle_vblank)

**Description**

The helper `drm_crtc_helper_get_vblank_timestamp_from_timer()` implements
get_vblank_timestamp of struct drm_crtc_funcs for CRTCs that require a
VBLANK timer. It returns the timestamp according to the timer's expiry
time.

See also struct [`drm_crtc_funcs.get_vblank_timestamp`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_crtc_funcs).

**Return**

True on success, or false otherwise.


<a id="rst-simple-kms-helper-reference"></a>

## Simple KMS Helper Reference


This helper library provides helpers for drivers for simple display
hardware.

[`drm_simple_display_pipe_init()`](#c-drm_simple_display_pipe_init) initializes a simple display pipeline
which has only one full-screen scanout buffer feeding one output. The
pipeline is represented by [`struct drm_simple_display_pipe`](#c-struct-drm_simple_display_pipe) and binds
together [`drm_plane`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_plane), [`drm_crtc`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_crtc) and [`drm_encoder`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_encoder) structures into one fixed
entity. Some flexibility for code reuse is provided through a separately
allocated [`drm_connector`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_connector) object and supporting optional [`drm_bridge`](#c-struct-drm_bridge)
encoder drivers.

Many drivers require only a very simple encoder that fulfills the minimum
requirements of the display pipeline and does not add additional
functionality. The function [`drm_simple_encoder_init()`](#c-drm_simple_encoder_init) provides an
implementation of such an encoder.



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

helper operations for a simple display pipeline

**Definition**

```c
struct drm_simple_display_pipe_funcs {
    enum drm_mode_status (*mode_valid)(struct drm_simple_display_pipe *pipe, const struct drm_display_mode *mode);
    void (*enable)(struct drm_simple_display_pipe *pipe, struct drm_crtc_state *crtc_state, struct drm_plane_state *plane_state);
    void (*disable)(struct drm_simple_display_pipe *pipe);
    int (*check)(struct drm_simple_display_pipe *pipe, struct drm_plane_state *plane_state, struct drm_crtc_state *crtc_state);
    void (*update)(struct drm_simple_display_pipe *pipe, struct drm_plane_state *old_plane_state);
    int (*prepare_fb)(struct drm_simple_display_pipe *pipe, struct drm_plane_state *plane_state);
    void (*cleanup_fb)(struct drm_simple_display_pipe *pipe, struct drm_plane_state *plane_state);
    int (*begin_fb_access)(struct drm_simple_display_pipe *pipe, struct drm_plane_state *new_plane_state);
    void (*end_fb_access)(struct drm_simple_display_pipe *pipe, struct drm_plane_state *plane_state);
    int (*enable_vblank)(struct drm_simple_display_pipe *pipe);
    void (*disable_vblank)(struct drm_simple_display_pipe *pipe);
    void (*reset_crtc)(struct drm_simple_display_pipe *pipe);
    struct drm_crtc_state * (*duplicate_crtc_state)(struct drm_simple_display_pipe *pipe);
    void (*destroy_crtc_state)(struct drm_simple_display_pipe *pipe, struct drm_crtc_state *crtc_state);
    void (*reset_plane)(struct drm_simple_display_pipe *pipe);
    struct drm_plane_state * (*duplicate_plane_state)(struct drm_simple_display_pipe *pipe);
    void (*destroy_plane_state)(struct drm_simple_display_pipe *pipe, struct drm_plane_state *plane_state);
};
```

**Members**

- `mode_valid`: This callback is used to check if a specific mode is valid in the
  crtc used in this simple display pipe. This should be implemented
  if the display pipe has some sort of restriction in the modes
  it can display. For example, a given display pipe may be responsible
  to set a clock value. If the clock can not produce all the values
  for the available modes then this callback can be used to restrict
  the number of modes to only the ones that can be displayed. Another
  reason can be bandwidth mitigation: the memory port on the display
  controller can have bandwidth limitations not allowing pixel data
  to be fetched at any rate.

  This hook is used by the probe helpers to filter the mode list in
  [`drm_helper_probe_single_connector_modes()`](#c-drm_helper_probe_single_connector_modes), and it is used by the
  atomic helpers to validate modes supplied by userspace in
  [`drm_atomic_helper_check_modeset()`](#c-drm_atomic_helper_check_modeset).

  This function is optional.

  NOTE:

  Since this function is both called from the check phase of an atomic
  commit, and the mode validation in the probe paths it is not allowed
  to look at anything else but the passed-in mode, and validate it
  against configuration-invariant hardware constraints.

  RETURNS:

  drm_mode_status Enum
- `enable`: This function should be used to enable the pipeline.
  It is called when the underlying crtc is enabled.
  This hook is optional.
- `disable`: This function should be used to disable the pipeline.
  It is called when the underlying crtc is disabled.
  This hook is optional.
- `check`: This function is called in the check phase of an atomic update,
  specifically when the underlying plane is checked.
  The simple display pipeline helpers already check that the plane is
  not scaled, fills the entire visible area and is always enabled
  when the crtc is also enabled.
  This hook is optional.

  RETURNS:

  0 on success, -EINVAL if the state or the transition can't be
  supported, -ENOMEM on memory allocation failure and -EDEADLK if an
  attempt to obtain another state object ran into a [`drm_modeset_lock`](/kernel/hardware/gpu/drm-kms.md#c-drm_modeset_lock)
  deadlock.
- `update`: This function is called when the underlying plane state is updated.
  This hook is optional.

  This is the function drivers should submit the
  [`drm_pending_vblank_event`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_pending_vblank_event) from. Using either
  [`drm_crtc_arm_vblank_event()`](/kernel/hardware/gpu/drm-kms.md#c-drm_crtc_arm_vblank_event), when the driver supports vblank
  interrupt handling, or [`drm_crtc_send_vblank_event()`](/kernel/hardware/gpu/drm-kms.md#c-drm_crtc_send_vblank_event) for more
  complex case. In case the hardware lacks vblank support entirely,
  drivers can set [`struct drm_crtc_state`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_crtc_state).no_vblank in
  [`struct drm_simple_display_pipe_funcs`](#c-struct-drm_simple_display_pipe_funcs).check and let DRM's
  atomic helper fake a vblank event.
- `prepare_fb`: Optional, called by [`drm_plane_helper_funcs.prepare_fb`](#c-struct-drm_plane_helper_funcs).  Please read
  the documentation for the [`drm_plane_helper_funcs.prepare_fb`](#c-struct-drm_plane_helper_funcs) hook for
  more details.

  For GEM drivers who neither have a **prepare_fb** nor **cleanup_fb** hook
  set, [`drm_gem_plane_helper_prepare_fb()`](#c-drm_gem_plane_helper_prepare_fb) is called automatically
  to implement this. Other drivers which need additional plane
  processing can call [`drm_gem_plane_helper_prepare_fb()`](#c-drm_gem_plane_helper_prepare_fb) from
  their **prepare_fb** hook.
- `cleanup_fb`: Optional, called by [`drm_plane_helper_funcs.cleanup_fb`](#c-struct-drm_plane_helper_funcs).  Please read
  the documentation for the [`drm_plane_helper_funcs.cleanup_fb`](#c-struct-drm_plane_helper_funcs) hook for
  more details.
- `begin_fb_access`: Optional, called by [`drm_plane_helper_funcs.begin_fb_access`](#c-struct-drm_plane_helper_funcs). Please read
  the documentation for the [`drm_plane_helper_funcs.begin_fb_access`](#c-struct-drm_plane_helper_funcs) hook for
  more details.
- `end_fb_access`: Optional, called by [`drm_plane_helper_funcs.end_fb_access`](#c-struct-drm_plane_helper_funcs). Please read
  the documentation for the [`drm_plane_helper_funcs.end_fb_access`](#c-struct-drm_plane_helper_funcs) hook for
  more details.
- `enable_vblank`: Optional, called by [`drm_crtc_funcs.enable_vblank`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_crtc_funcs). Please read
  the documentation for the [`drm_crtc_funcs.enable_vblank`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_crtc_funcs) hook for
  more details.
- `disable_vblank`: Optional, called by [`drm_crtc_funcs.disable_vblank`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_crtc_funcs). Please read
  the documentation for the [`drm_crtc_funcs.disable_vblank`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_crtc_funcs) hook for
  more details.
- `reset_crtc`: Optional, called by [`drm_crtc_funcs.reset`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_crtc_funcs). Please read the
  documentation for the [`drm_crtc_funcs.reset`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_crtc_funcs) hook for more details.
- `duplicate_crtc_state`: Optional, called by [`drm_crtc_funcs.atomic_duplicate_state`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_crtc_funcs). Please
  read the documentation for the [`drm_crtc_funcs.atomic_duplicate_state`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_crtc_funcs)
  hook for more details.
- `destroy_crtc_state`: Optional, called by [`drm_crtc_funcs.atomic_destroy_state`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_crtc_funcs). Please
  read the documentation for the [`drm_crtc_funcs.atomic_destroy_state`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_crtc_funcs)
  hook for more details.
- `reset_plane`: Optional, called by [`drm_plane_funcs.reset`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_plane_funcs). Please read the
  documentation for the [`drm_plane_funcs.reset`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_plane_funcs) hook for more details.
- `duplicate_plane_state`: Optional, called by [`drm_plane_funcs.atomic_duplicate_state`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_plane_funcs).  Please
  read the documentation for the [`drm_plane_funcs.atomic_duplicate_state`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_plane_funcs)
  hook for more details.
- `destroy_plane_state`: Optional, called by [`drm_plane_funcs.atomic_destroy_state`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_plane_funcs).  Please
  read the documentation for the [`drm_plane_funcs.atomic_destroy_state`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_plane_funcs)
  hook for more details.

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

simple display pipeline

**Definition**

```c
struct drm_simple_display_pipe {
    struct drm_crtc crtc;
    struct drm_plane plane;
    struct drm_encoder encoder;
    struct drm_connector *connector;
    const struct drm_simple_display_pipe_funcs *funcs;
};
```

**Members**

- `crtc`: CRTC control structure
- `plane`: Plane control structure
- `encoder`: Encoder control structure
- `connector`: Connector control structure
- `funcs`: Pipeline control functions (optional)

**Description**

Simple display pipeline with plane, crtc and encoder collapsed into one
entity. It should be initialized by calling [`drm_simple_display_pipe_init()`](#c-drm_simple_display_pipe_init).

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

```c
drmm_simple_encoder_alloc(dev, type, member, encoder_type)
```

Allocate and initialize an encoder with basic functionality.

**Parameters**

- `dev`: drm device
- `type`: the type of the struct which contains struct [`drm_encoder`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_encoder)
- `member`: the name of the [`drm_encoder`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_encoder) within **type**.
- `encoder_type`: user visible type of the encoder

**Description**

Allocates and initializes an encoder that has no further functionality.
Settings for possible CRTC and clones are left to their initial values.
Cleanup is automatically handled through registering [`drm_encoder_cleanup()`](/kernel/hardware/gpu/drm-kms.md#c-drm_encoder_cleanup)
with [`drmm_add_action()`](/kernel/hardware/gpu/drm-internals.md#c-drmm_add_action).

**Return**

Pointer to new encoder, or ERR_PTR on failure.



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

```c
int drm_simple_encoder_init(struct drm_device *dev, struct drm_encoder *encoder, int encoder_type)
```

Initialize a preallocated encoder with basic functionality.

**Parameters**

- `struct drm_device *dev`: drm device
- `struct drm_encoder *encoder`: the encoder to initialize
- `int encoder_type`: user visible type of the encoder

**Description**

Initialises a preallocated encoder that has no further functionality.
Settings for possible CRTC and clones are left to their initial values.
The encoder will be cleaned up automatically as part of the mode-setting
cleanup.

The caller of [`drm_simple_encoder_init()`](#c-drm_simple_encoder_init) is responsible for freeing
the encoder's memory after the encoder has been cleaned up. At the
moment this only works reliably if the encoder data structure is
stored in the device structure. Free the encoder's memory as part of
the device release function.

**Note**

consider using [`drmm_simple_encoder_alloc()`](#c-drmm_simple_encoder_alloc) instead of
[`drm_simple_encoder_init()`](#c-drm_simple_encoder_init) to let the DRM managed resource infrastructure
take care of cleanup and deallocation.

**Return**

Zero on success, error code on failure.

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

```c
int drm_simple_display_pipe_attach_bridge(struct drm_simple_display_pipe *pipe, struct drm_bridge *bridge)
```

Attach a bridge to the display pipe

**Parameters**

- `struct drm_simple_display_pipe *pipe`: simple display pipe object
- `struct drm_bridge *bridge`: bridge to attach

**Description**

Makes it possible to still use the drm_simple_display_pipe helpers when
a DRM bridge has to be used.

Note that you probably want to initialize the pipe by passing a NULL
connector to [`drm_simple_display_pipe_init()`](#c-drm_simple_display_pipe_init).

**Return**

Zero on success, negative error code on failure.

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

```c
int drm_simple_display_pipe_init(struct drm_device *dev, struct drm_simple_display_pipe *pipe, const struct drm_simple_display_pipe_funcs *funcs, const uint32_t *formats, unsigned int format_count, const uint64_t *format_modifiers, struct drm_connector *connector)
```

Initialize a simple display pipeline

**Parameters**

- `struct drm_device *dev`: DRM device
- `struct drm_simple_display_pipe *pipe`: simple display pipe object to initialize
- `const struct drm_simple_display_pipe_funcs *funcs`: callbacks for the display pipe (optional)
- `const uint32_t *formats`: array of supported formats (DRM_FORMAT\_\*)
- `unsigned int format_count`: number of elements in **formats**
- `const uint64_t *format_modifiers`: array of formats modifiers
- `struct drm_connector *connector`: connector to attach and register (optional)

**Description**

Sets up a display pipeline which consist of a really simple
plane-crtc-encoder pipe.

If a connector is supplied, the pipe will be coupled with the provided
connector. You may supply a NULL connector when using drm bridges, that
handle connectors themselves (see [`drm_simple_display_pipe_attach_bridge()`](#c-drm_simple_display_pipe_attach_bridge)).

Teardown of a simple display pipe is all handled automatically by the drm
core through calling [`drm_mode_config_cleanup()`](/kernel/hardware/gpu/drm-kms.md#c-drm_mode_config_cleanup). Drivers afterwards need to
release the memory for the structure themselves.

**Return**

Zero on success, negative error code on failure.


<a id="rst-fbdev-helper-functions-reference"></a>

## fbdev Helper Functions Reference


The fb helper functions are useful to provide an fbdev on top of a drm kernel
mode setting driver. They can be used mostly independently from the crtc
helper functions used by many drivers to implement the kernel mode setting
interfaces. Drivers that use one of the shared memory managers, TTM, SHMEM,
DMA, should instead use the corresponding fbdev emulation.

For suspend/resume consider using [`drm_mode_config_helper_suspend()`](#c-drm_mode_config_helper_suspend) and
[`drm_mode_config_helper_resume()`](#c-drm_mode_config_helper_resume) which takes care of fbdev as well.

All other functions exported by the fb helper library can be used to
implement the fbdev driver interface by the driver.

It is possible, though perhaps somewhat tricky, to implement race-free
hotplug detection using the fbdev helpers. The [`drm_fb_helper_prepare()`](#c-drm_fb_helper_prepare)
helper must be called first to initialize the minimum required to make
hotplug detection work. Drivers also need to make sure to properly set up
the [`drm_mode_config.funcs`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_mode_config) member. After calling [`drm_kms_helper_poll_init()`](#c-drm_kms_helper_poll_init)
it is safe to enable interrupts and start processing hotplug events. At the
same time, drivers should initialize all modeset objects such as CRTCs,
encoders and connectors. To finish up the fbdev helper initialization, the
[`drm_fb_helper_init()`](#c-drm_fb_helper_init) function is called. To probe for all attached displays
and set up an initial configuration using the detected hardware, drivers
should call [`drm_fb_helper_initial_config()`](#c-drm_fb_helper_initial_config).

If [`drm_framebuffer_funcs.dirty`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_framebuffer_funcs) is set, the
drm_fb_helper_{cfb,sys}_{write,fillrect,copyarea,imageblit} functions will
accumulate changes and schedule [`drm_fb_helper.dirty_work`](#c-struct-drm_fb_helper) to run right
away. This worker then calls the `dirty()` function ensuring that it will
always run in process context since the fb_*() function could be running in
atomic context. If [`drm_fb_helper_deferred_io()`](#c-drm_fb_helper_deferred_io) is used as the deferred_io
callback it will also schedule dirty_work with the damage collected from the
mmap page writes.



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

describes fbdev size and scanout surface size

**Definition**

```c
struct drm_fb_helper_surface_size {
    u32 fb_width;
    u32 fb_height;
    u32 surface_width;
    u32 surface_height;
    u32 surface_bpp;
    u32 surface_depth;
};
```

**Members**

- `fb_width`: fbdev width
- `fb_height`: fbdev height
- `surface_width`: scanout buffer width
- `surface_height`: scanout buffer height
- `surface_bpp`: scanout buffer bpp
- `surface_depth`: scanout buffer depth

**Description**

Note that the scanout surface width/height may be larger than the fbdev
width/height.  In case of multiple displays, the scanout surface is sized
according to the largest width/height (so it is large enough for all CRTCs
to scanout).  But the fbdev width/height is sized to the minimum width/
height of all the displays.  This ensures that fbcon fits on the smallest
of the attached displays. fb_width/fb_height is used by
[`drm_fb_helper_fill_info()`](#c-drm_fb_helper_fill_info) to fill out the `fb_info.var` structure.

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

driver callbacks for the fbdev emulation library

**Definition**

```c
struct drm_fb_helper_funcs {
    int (*fb_dirty)(struct drm_fb_helper *helper, struct drm_clip_rect *clip);
    void (*fb_restore)(struct drm_fb_helper *helper);
    void (*fb_set_suspend)(struct drm_fb_helper *helper, bool suspend);
};
```

**Members**

- `fb_dirty`: Driver callback to update the framebuffer memory. If set, fbdev
  emulation will invoke this callback in regular intervals after
  the framebuffer has been written.

  This callback is optional.

  Returns:
  0 on success, or an error code otherwise.
- `fb_restore`: Driver callback to restore internal fbdev state. If set, fbdev
  emulation will invoke this callback after restoring the display
  mode.

  Only for i915. Do not use in new code.

  TODO: Fix i915 to not require this callback.
- `fb_set_suspend`: Driver callback to suspend or resume, if set, fbdev emulation will
  invoke this callback during suspend and resume. Driver should call
  [`fb_set_suspend()`](/kernel/hardware/driver-api/fundamentals/frame-buffer.md#c-fb_set_suspend) from their implementation. If not set, fbdev
  emulation will invoke [`fb_set_suspend()`](/kernel/hardware/driver-api/fundamentals/frame-buffer.md#c-fb_set_suspend) directly.

  Only for i915. Do not use in new code.

  TODO: Fix i915 to not require this callback.

**Description**

Driver callbacks used by the fbdev emulation helper library.

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

main structure to emulate fbdev on top of KMS

**Definition**

```c
struct drm_fb_helper {
        struct drm_client_dev client;
        struct drm_client_buffer *buffer;
        struct drm_framebuffer *fb;
        struct drm_device *dev;
        const struct drm_fb_helper_funcs *funcs;
        struct fb_info *info;
        u32 pseudo_palette[17];
        struct drm_clip_rect damage_clip;
        spinlock_t damage_lock;
        struct work_struct damage_work;
        struct work_struct resume_work;
        struct mutex lock;
        bool delayed_hotplug;
        bool deferred_setup;
        int preferred_bpp;
    #ifdef CONFIG_FB_DEFERRED_IO;
        struct fb_deferred_io fbdefio;
    #endif;
};
```

**Members**

- `client`: DRM client used by the generic fbdev emulation.
- `buffer`: Framebuffer used by the generic fbdev emulation.
- `fb`: Scanout framebuffer object
- `dev`: DRM device
- `funcs`: driver callbacks for fb helper
- `info`: emulated fbdev device info struct
- `pseudo_palette`: fake palette of 16 colors
- `damage_clip`: clip rectangle used with deferred_io to accumulate damage to
  the screen buffer
- `damage_lock`: spinlock protecting **damage_clip**
- `damage_work`: worker used to flush the framebuffer
- `resume_work`: worker used during resume if the console lock is already taken
- `lock`: Top-level FBDEV helper lock. This protects all internal data
  structures and lists, such as **connector_info** and **crtc_info**.

  FIXME: fbdev emulation locking is a mess and long term we want to
  protect all helper internal state with this lock as well as reduce
  core KMS locking as much as possible.
- `delayed_hotplug`: A hotplug was received while fbdev wasn't in control of the DRM
  device, i.e. another KMS master was active. The output configuration
  needs to be reprobe when fbdev is in control again.
- `deferred_setup`: If no outputs are connected (disconnected or unknown) the FB helper
  code will defer setup until at least one of the outputs shows up.
  This field keeps track of the status so that setup can be retried
  at every hotplug event until it succeeds eventually.

  Protected by **lock**.
- `preferred_bpp`: Temporary storage for the driver's preferred BPP setting passed to
  FB helper initialization. This needs to be tracked so that deferred
  FB helper setup can pass this on.

  See also: **deferred_setup**
- `fbdefio`: Temporary storage for the driver's FB deferred I/O handler. If the
  driver uses the DRM fbdev emulation layer, this is set by the core
  to a generic deferred I/O handler if a driver is preferring to use
  a shadow buffer.

**Description**

This is the main structure used by the fbdev helpers. Drivers supporting
fbdev emulation should embedded this into their overall driver structure.
Drivers must also fill out a [`struct drm_fb_helper_funcs`](#c-struct-drm_fb_helper_funcs) with a few
operations.

#### <a id="c-DRM_FB_HELPER_DEFAULT_OPS"></a>`DRM_FB_HELPER_DEFAULT_OPS`

```c
DRM_FB_HELPER_DEFAULT_OPS
```

helper define for drm drivers

**Description**

Helper define to register default implementations of drm_fb_helper
functions. To be used in struct fb_ops of drm drivers.



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

```c
int drm_fb_helper_restore_fbdev_mode_unlocked(struct drm_fb_helper *fb_helper, bool force)
```

restore fbdev configuration

**Parameters**

- `struct drm_fb_helper *fb_helper`: driver-allocated fbdev helper, can be NULL
- `bool force`: ignore present DRM master

**Description**

This helper should be called from fbdev emulation's [`drm_client_funcs.restore`](/kernel/hardware/gpu/drm-client.md#c-struct-drm_client_funcs)
callback. It ensures that the user isn't greeted with a black screen when the
userspace compositor releases the display device.

**Return**

0 on success, or a negative errno code otherwise.

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

```c
int drm_fb_helper_blank(int blank, struct fb_info *info)
```

implementation for `fb_ops.fb_blank`

**Parameters**

- `int blank`: desired blanking state
- `struct fb_info *info`: fbdev registered by the helper

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

```c
void drm_fb_helper_prepare(struct drm_device *dev, struct drm_fb_helper *helper, unsigned int preferred_bpp, const struct drm_fb_helper_funcs *funcs)
```

setup a drm_fb_helper structure

**Parameters**

- `struct drm_device *dev`: DRM device
- `struct drm_fb_helper *helper`: driver-allocated fbdev helper structure to set up
- `unsigned int preferred_bpp`: Preferred bits per pixel for the device.
- `const struct drm_fb_helper_funcs *funcs`: pointer to structure of functions associate with this helper

**Description**

Sets up the bare minimum to make the framebuffer helper usable. This is
useful to implement race-free initialization of the polling helpers.

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

```c
void drm_fb_helper_unprepare(struct drm_fb_helper *fb_helper)
```

clean up a drm_fb_helper structure

**Parameters**

- `struct drm_fb_helper *fb_helper`: driver-allocated fbdev helper structure to set up

**Description**

Cleans up the framebuffer helper. Inverse of [`drm_fb_helper_prepare()`](#c-drm_fb_helper_prepare).

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

```c
int drm_fb_helper_init(struct drm_device *dev, struct drm_fb_helper *fb_helper)
```

initialize a [`struct drm_fb_helper`](#c-struct-drm_fb_helper)

**Parameters**

- `struct drm_device *dev`: drm device
- `struct drm_fb_helper *fb_helper`: driver-allocated fbdev helper structure to initialize

**Description**

This allocates the structures for the fbdev helper with the given limits.
Note that this won't yet touch the hardware (through the driver interfaces)
nor register the fbdev. This is only done in [`drm_fb_helper_initial_config()`](#c-drm_fb_helper_initial_config)
to allow driver writes more control over the exact init sequence.

Drivers must call [`drm_fb_helper_prepare()`](#c-drm_fb_helper_prepare) before calling this function.

**Return**

Zero if everything went ok, nonzero otherwise.

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

```c
void drm_fb_helper_unregister_info(struct drm_fb_helper *fb_helper)
```

unregister fb_info framebuffer device

**Parameters**

- `struct drm_fb_helper *fb_helper`: driver-allocated fbdev helper, must not be NULL

**Description**

A wrapper around unregister_framebuffer, to release the fb_info
framebuffer device. This must be called before releasing all resources for
**fb_helper** by calling [`drm_fb_helper_fini()`](#c-drm_fb_helper_fini).

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

```c
void drm_fb_helper_fini(struct drm_fb_helper *fb_helper)
```

finialize a [`struct drm_fb_helper`](#c-struct-drm_fb_helper)

**Parameters**

- `struct drm_fb_helper *fb_helper`: driver-allocated fbdev helper, can be NULL

**Description**

This cleans up all remaining resources associated with **fb_helper**.

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

```c
void drm_fb_helper_deferred_io(struct fb_info *info, struct list_head *pagereflist)
```

fbdev deferred_io callback function

**Parameters**

- `struct fb_info *info`: fb_info struct pointer
- `struct list_head *pagereflist`: list of mmap framebuffer pages that have to be flushed

**Description**

This function is used as the `fb_deferred_io.deferred_io`
callback function for flushing the fbdev mmap writes.

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

```c
void drm_fb_helper_set_suspend(struct drm_fb_helper *fb_helper, bool suspend)
```

wrapper around fb_set_suspend

**Parameters**

- `struct drm_fb_helper *fb_helper`: driver-allocated fbdev helper, can be NULL
- `bool suspend`: whether to suspend or resume

**Description**

A wrapper around fb_set_suspend implemented by fbdev core.
Use [`drm_fb_helper_set_suspend_unlocked()`](#c-drm_fb_helper_set_suspend_unlocked) if you don't need to take
the lock yourself

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

```c
void drm_fb_helper_set_suspend_unlocked(struct drm_fb_helper *fb_helper, bool suspend)
```

wrapper around fb_set_suspend that also takes the console lock

**Parameters**

- `struct drm_fb_helper *fb_helper`: driver-allocated fbdev helper, can be NULL
- `bool suspend`: whether to suspend or resume

**Description**

A wrapper around [`fb_set_suspend()`](/kernel/hardware/driver-api/fundamentals/frame-buffer.md#c-fb_set_suspend) that takes the console lock. If the lock
isn't available on resume, a worker is tasked with waiting for the lock
to become available. The console lock can be pretty contented on resume
due to all the printk activity.

This function can be called multiple times with the same state since
`fb_info.state` is checked to see if fbdev is running or not before locking.

Use [`drm_fb_helper_set_suspend()`](#c-drm_fb_helper_set_suspend) if you need to take the lock yourself.

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

```c
int drm_fb_helper_setcmap(struct fb_cmap *cmap, struct fb_info *info)
```

implementation for `fb_ops.fb_setcmap`

**Parameters**

- `struct fb_cmap *cmap`: cmap to set
- `struct fb_info *info`: fbdev registered by the helper

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

```c
int drm_fb_helper_ioctl(struct fb_info *info, unsigned int cmd, unsigned long arg)
```

legacy ioctl implementation

**Parameters**

- `struct fb_info *info`: fbdev registered by the helper
- `unsigned int cmd`: ioctl command
- `unsigned long arg`: ioctl argument

**Description**

A helper to implement the standard fbdev ioctl. Only
FBIO_WAITFORVSYNC is implemented for now.

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

```c
int drm_fb_helper_check_var(struct fb_var_screeninfo *var, struct fb_info *info)
```

implementation for `fb_ops.fb_check_var`

**Parameters**

- `struct fb_var_screeninfo *var`: screeninfo to check
- `struct fb_info *info`: fbdev registered by the helper

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

```c
int drm_fb_helper_set_par(struct fb_info *info)
```

implementation for `fb_ops.fb_set_par`

**Parameters**

- `struct fb_info *info`: fbdev registered by the helper

**Description**

This will let fbcon do the mode init and is called at initialization time by
the fbdev core when registering the driver, and later on through the hotplug
callback.

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

```c
int drm_fb_helper_pan_display(struct fb_var_screeninfo *var, struct fb_info *info)
```

implementation for `fb_ops.fb_pan_display`

**Parameters**

- `struct fb_var_screeninfo *var`: updated screen information
- `struct fb_info *info`: fbdev registered by the helper

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

```c
void drm_fb_helper_fill_info(struct fb_info *info, struct drm_fb_helper *fb_helper, struct drm_fb_helper_surface_size *sizes)
```

initializes fbdev information

**Parameters**

- `struct fb_info *info`: fbdev instance to set up
- `struct drm_fb_helper *fb_helper`: fb helper instance to use as template
- `struct drm_fb_helper_surface_size *sizes`: describes fbdev size and scanout surface size

**Description**

Sets up the variable and fixed fbdev metainformation from the given fb helper
instance and the drm framebuffer allocated in [`drm_fb_helper.fb`](#c-struct-drm_fb_helper).

Drivers should call this (or their equivalent setup code) from their
[`drm_driver.fbdev_probe`](/kernel/hardware/gpu/drm-internals.md#c-struct-drm_driver) callback after having allocated the fbdev
backing storage framebuffer.

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

```c
int drm_fb_helper_initial_config(struct drm_fb_helper *fb_helper)
```

setup a sane initial connector configuration

**Parameters**

- `struct drm_fb_helper *fb_helper`: fb_helper device struct

**Description**

Scans the CRTCs and connectors and tries to put together an initial setup.
At the moment, this is a cloned configuration across all heads with
a new framebuffer object as the backing store.

Note that this also registers the fbdev and so allows userspace to call into
the driver through the fbdev interfaces.

This function will call down into the [`drm_driver.fbdev_probe`](/kernel/hardware/gpu/drm-internals.md#c-struct-drm_driver) callback
to let the driver allocate and initialize the fbdev info structure and the
drm framebuffer used to back the fbdev. [`drm_fb_helper_fill_info()`](#c-drm_fb_helper_fill_info) is provided
as a helper to setup simple default values for the fbdev info structure.

HANG DEBUGGING:

When you have fbcon support built-in or already loaded, this function will do
a full modeset to setup the fbdev console. Due to locking misdesign in the
VT/fbdev subsystem that entire modeset sequence has to be done while holding
console_lock. Until console_unlock is called no dmesg lines will be sent out
to consoles, not even serial console. This means when your driver crashes,
you will see absolutely nothing else but a system stuck in this function,
with no further output. Any kind of [`printk()`](/kernel/internals/core-api/printk-basics.md#c-printk) you place within your own driver
or in the drm core modeset code will also never show up.

Standard debug practice is to run the fbcon setup without taking the
console_lock as a hack, to be able to see backtraces and crashes on the
serial line. This can be done by setting the fb.lockless_register_fb=1 kernel
cmdline option.

The other option is to just disable fbdev emulation since very likely the
first modeset from userspace will crash in the same way, and is even easier
to debug. This can be done by setting the drm_kms_helper.fbdev_emulation=0
kernel cmdline option.

**Return**

Zero if everything went ok, nonzero otherwise.

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

```c
int drm_fb_helper_hotplug_event(struct drm_fb_helper *fb_helper)
```

respond to a hotplug notification by probing all the outputs attached to the fb

**Parameters**

- `struct drm_fb_helper *fb_helper`: driver-allocated fbdev helper, can be NULL

**Description**

Scan the connectors attached to the fb_helper and try to put together a
setup after notification of a change in output configuration.

Called at runtime, takes the mode config locks to be able to check/change the
modeset configuration. Must be run from process context (which usually means
either the output polling work or a work item launched from the driver's
hotplug interrupt).

Note that drivers may call this even before calling
drm_fb_helper_initial_config but only after drm_fb_helper_init. This allows
for a race-free fbcon setup and will make sure that the fbdev emulation will
not miss any hotplug events.

**Return**

0 on success and a non-zero error code otherwise.


<a id="rst-format-helper-functions-reference"></a>

## format Helper Functions Reference


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

```c
void drm_format_conv_state_init(struct drm_format_conv_state *state)
```

Initialize format-conversion state

**Parameters**

- `struct drm_format_conv_state *state`: The state to initialize

**Description**

Clears all fields in struct drm_format_conv_state. The state will
be empty with no preallocated resources.

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

```c
void drm_format_conv_state_copy(struct drm_format_conv_state *state, const struct drm_format_conv_state *old_state)
```

Copy format-conversion state

**Parameters**

- `struct drm_format_conv_state *state`: Destination state
- `const struct drm_format_conv_state *old_state`: Source state

**Description**

Copies format-conversion state from **old_state** to **state**; except for
temporary storage.

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

```c
void * drm_format_conv_state_reserve(struct drm_format_conv_state *state, size_t new_size, gfp_t flags)
```

Allocates storage for format conversion

**Parameters**

- `struct drm_format_conv_state *state`: The format-conversion state
- `size_t new_size`: The minimum allocation size
- `gfp_t flags`: Flags for [`kmalloc()`](/kernel/internals/core-api/mm-api.md#c-kmalloc)

**Description**

Allocates at least **new_size** bytes and returns a pointer to the memory
range. After calling this function, previously returned memory blocks
are invalid. It's best to collect all memory requirements of a format
conversion and call this function once to allocate the range.

**Return**

A pointer to the allocated memory range, or NULL otherwise.

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

```c
void drm_format_conv_state_release(struct drm_format_conv_state *state)
```

Releases an format-conversion storage

**Parameters**

- `struct drm_format_conv_state *state`: The format-conversion state

**Description**

Releases the memory range references by the format-conversion state.
After this call, all pointers to the memory are invalid. Prefer
[`drm_format_conv_state_init()`](#c-drm_format_conv_state_init) for cleaning up and unloading a driver.

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

```c
unsigned int drm_fb_clip_offset(unsigned int pitch, const struct drm_format_info *format, const struct drm_rect *clip)
```

Returns the clipping rectangles byte-offset in a framebuffer

**Parameters**

- `unsigned int pitch`: Framebuffer line pitch in byte
- `const struct drm_format_info *format`: Framebuffer format
- `const struct drm_rect *clip`: Clip rectangle

**Return**

The byte offset of the clip rectangle's top-left corner within the framebuffer.

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

```c
void drm_fb_memcpy(struct iosys_map *dst, const unsigned int *dst_pitch, const struct iosys_map *src, const struct drm_framebuffer *fb, const struct drm_rect *clip)
```

Copy clip buffer

**Parameters**

- `struct iosys_map *dst`: Array of destination buffers
- `const unsigned int *dst_pitch`: Array of numbers of bytes between the start of two consecutive scanlines
  within **dst**; can be NULL if scanlines are stored next to each other.
- `const struct iosys_map *src`: Array of source buffers
- `const struct drm_framebuffer *fb`: DRM framebuffer
- `const struct drm_rect *clip`: Clip rectangle area to copy

**Description**

This function copies parts of a framebuffer to display memory. Destination and
framebuffer formats must match. No conversion takes place. The parameters **dst**,
**dst_pitch** and **src** refer to arrays. Each array must have at least as many entries
as there are planes in **fb**'s format. Each entry stores the value for the format's
respective color plane at the same index.

This function does not apply clipping on **dst** (i.e. the destination is at the
top-left corner).

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

```c
void drm_fb_swab(struct iosys_map *dst, const unsigned int *dst_pitch, const struct iosys_map *src, const struct drm_framebuffer *fb, const struct drm_rect *clip, bool cached, struct drm_format_conv_state *state)
```

Swap bytes into clip buffer

**Parameters**

- `struct iosys_map *dst`: Array of destination buffers
- `const unsigned int *dst_pitch`: Array of numbers of bytes between the start of two consecutive scanlines
  within **dst**; can be NULL if scanlines are stored next to each other.
- `const struct iosys_map *src`: Array of source buffers
- `const struct drm_framebuffer *fb`: DRM framebuffer
- `const struct drm_rect *clip`: Clip rectangle area to copy
- `bool cached`: Source buffer is mapped cached (eg. not write-combined)
- `struct drm_format_conv_state *state`: Transform and conversion state

**Description**

This function copies parts of a framebuffer to display memory and swaps per-pixel
bytes during the process. Destination and framebuffer formats must match. The
parameters **dst**, **dst_pitch** and **src** refer to arrays. Each array must have at
least as many entries as there are planes in **fb**'s format. Each entry stores the
value for the format's respective color plane at the same index. If **cached** is
false a temporary buffer is used to cache one pixel line at a time to speed up
slow uncached reads.

This function does not apply clipping on **dst** (i.e. the destination is at the
top-left corner).

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

```c
void drm_fb_xrgb8888_to_rgb332(struct iosys_map *dst, const unsigned int *dst_pitch, const struct iosys_map *src, const struct drm_framebuffer *fb, const struct drm_rect *clip, struct drm_format_conv_state *state)
```

Convert XRGB8888 to RGB332 clip buffer

**Parameters**

- `struct iosys_map *dst`: Array of RGB332 destination buffers
- `const unsigned int *dst_pitch`: Array of numbers of bytes between the start of two consecutive scanlines
  within **dst**; can be NULL if scanlines are stored next to each other.
- `const struct iosys_map *src`: Array of XRGB8888 source buffers
- `const struct drm_framebuffer *fb`: DRM framebuffer
- `const struct drm_rect *clip`: Clip rectangle area to copy
- `struct drm_format_conv_state *state`: Transform and conversion state

**Description**

This function copies parts of a framebuffer to display memory and converts the
color format during the process. Destination and framebuffer formats must match. The
parameters **dst**, **dst_pitch** and **src** refer to arrays. Each array must have at
least as many entries as there are planes in **fb**'s format. Each entry stores the
value for the format's respective color plane at the same index.

This function does not apply clipping on **dst** (i.e. the destination is at the
top-left corner).

Drivers can use this function for RGB332 devices that don't support XRGB8888 natively.

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

```c
void drm_fb_xrgb8888_to_rgb565(struct iosys_map *dst, const unsigned int *dst_pitch, const struct iosys_map *src, const struct drm_framebuffer *fb, const struct drm_rect *clip, struct drm_format_conv_state *state)
```

Convert XRGB8888 to RGB565 clip buffer

**Parameters**

- `struct iosys_map *dst`: Array of RGB565 destination buffers
- `const unsigned int *dst_pitch`: Array of numbers of bytes between the start of two consecutive scanlines
  within **dst**; can be NULL if scanlines are stored next to each other.
- `const struct iosys_map *src`: Array of XRGB8888 source buffer
- `const struct drm_framebuffer *fb`: DRM framebuffer
- `const struct drm_rect *clip`: Clip rectangle area to copy
- `struct drm_format_conv_state *state`: Transform and conversion state

**Description**

This function copies parts of a framebuffer to display memory and converts the
color format during the process. Destination and framebuffer formats must match. The
parameters **dst**, **dst_pitch** and **src** refer to arrays. Each array must have at
least as many entries as there are planes in **fb**'s format. Each entry stores the
value for the format's respective color plane at the same index.

This function does not apply clipping on **dst** (i.e. the destination is at the
top-left corner).

Drivers can use this function for RGB565 devices that don't support XRGB8888 natively.

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

```c
void drm_fb_xrgb8888_to_rgb565be(struct iosys_map *dst, const unsigned int *dst_pitch, const struct iosys_map *src, const struct drm_framebuffer *fb, const struct drm_rect *clip, struct drm_format_conv_state *state)
```

Convert XRGB8888 to RGB565|DRM_FORMAT_BIG_ENDIAN clip buffer

**Parameters**

- `struct iosys_map *dst`: Array of RGB565BE destination buffers
- `const unsigned int *dst_pitch`: Array of numbers of bytes between the start of two consecutive scanlines
  within **dst**; can be NULL if scanlines are stored next to each other.
- `const struct iosys_map *src`: Array of XRGB8888 source buffer
- `const struct drm_framebuffer *fb`: DRM framebuffer
- `const struct drm_rect *clip`: Clip rectangle area to copy
- `struct drm_format_conv_state *state`: Transform and conversion state

**Description**

This function copies parts of a framebuffer to display memory and converts the
color format during the process. Destination and framebuffer formats must match. The
parameters **dst**, **dst_pitch** and **src** refer to arrays. Each array must have at
least as many entries as there are planes in **fb**'s format. Each entry stores the
value for the format's respective color plane at the same index.

This function does not apply clipping on **dst** (i.e. the destination is at the
top-left corner).

Drivers can use this function for RGB565BE devices that don't support XRGB8888 natively.

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

```c
void drm_fb_xrgb8888_to_xrgb1555(struct iosys_map *dst, const unsigned int *dst_pitch, const struct iosys_map *src, const struct drm_framebuffer *fb, const struct drm_rect *clip, struct drm_format_conv_state *state)
```

Convert XRGB8888 to XRGB1555 clip buffer

**Parameters**

- `struct iosys_map *dst`: Array of XRGB1555 destination buffers
- `const unsigned int *dst_pitch`: Array of numbers of bytes between the start of two consecutive scanlines
  within **dst**; can be NULL if scanlines are stored next to each other.
- `const struct iosys_map *src`: Array of XRGB8888 source buffer
- `const struct drm_framebuffer *fb`: DRM framebuffer
- `const struct drm_rect *clip`: Clip rectangle area to copy
- `struct drm_format_conv_state *state`: Transform and conversion state

**Description**

This function copies parts of a framebuffer to display memory and converts
the color format during the process. The parameters **dst**, **dst_pitch** and
**src** refer to arrays. Each array must have at least as many entries as
there are planes in **fb**'s format. Each entry stores the value for the
format's respective color plane at the same index.

This function does not apply clipping on **dst** (i.e. the destination is at the
top-left corner).

Drivers can use this function for XRGB1555 devices that don't support
XRGB8888 natively.

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

```c
void drm_fb_xrgb8888_to_argb1555(struct iosys_map *dst, const unsigned int *dst_pitch, const struct iosys_map *src, const struct drm_framebuffer *fb, const struct drm_rect *clip, struct drm_format_conv_state *state)
```

Convert XRGB8888 to ARGB1555 clip buffer

**Parameters**

- `struct iosys_map *dst`: Array of ARGB1555 destination buffers
- `const unsigned int *dst_pitch`: Array of numbers of bytes between the start of two consecutive scanlines
  within **dst**; can be NULL if scanlines are stored next to each other.
- `const struct iosys_map *src`: Array of XRGB8888 source buffer
- `const struct drm_framebuffer *fb`: DRM framebuffer
- `const struct drm_rect *clip`: Clip rectangle area to copy
- `struct drm_format_conv_state *state`: Transform and conversion state

**Description**

This function copies parts of a framebuffer to display memory and converts
the color format during the process. The parameters **dst**, **dst_pitch** and
**src** refer to arrays. Each array must have at least as many entries as
there are planes in **fb**'s format. Each entry stores the value for the
format's respective color plane at the same index.

This function does not apply clipping on **dst** (i.e. the destination is at the
top-left corner).

Drivers can use this function for ARGB1555 devices that don't support
XRGB8888 natively. It sets an opaque alpha channel as part of the conversion.

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

```c
void drm_fb_xrgb8888_to_rgba5551(struct iosys_map *dst, const unsigned int *dst_pitch, const struct iosys_map *src, const struct drm_framebuffer *fb, const struct drm_rect *clip, struct drm_format_conv_state *state)
```

Convert XRGB8888 to RGBA5551 clip buffer

**Parameters**

- `struct iosys_map *dst`: Array of RGBA5551 destination buffers
- `const unsigned int *dst_pitch`: Array of numbers of bytes between the start of two consecutive scanlines
  within **dst**; can be NULL if scanlines are stored next to each other.
- `const struct iosys_map *src`: Array of XRGB8888 source buffer
- `const struct drm_framebuffer *fb`: DRM framebuffer
- `const struct drm_rect *clip`: Clip rectangle area to copy
- `struct drm_format_conv_state *state`: Transform and conversion state

**Description**

This function copies parts of a framebuffer to display memory and converts
the color format during the process. The parameters **dst**, **dst_pitch** and
**src** refer to arrays. Each array must have at least as many entries as
there are planes in **fb**'s format. Each entry stores the value for the
format's respective color plane at the same index.

This function does not apply clipping on **dst** (i.e. the destination is at the
top-left corner).

Drivers can use this function for RGBA5551 devices that don't support
XRGB8888 natively. It sets an opaque alpha channel as part of the conversion.

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

```c
void drm_fb_xrgb8888_to_rgb888(struct iosys_map *dst, const unsigned int *dst_pitch, const struct iosys_map *src, const struct drm_framebuffer *fb, const struct drm_rect *clip, struct drm_format_conv_state *state)
```

Convert XRGB8888 to RGB888 clip buffer

**Parameters**

- `struct iosys_map *dst`: Array of RGB888 destination buffers
- `const unsigned int *dst_pitch`: Array of numbers of bytes between the start of two consecutive scanlines
  within **dst**; can be NULL if scanlines are stored next to each other.
- `const struct iosys_map *src`: Array of XRGB8888 source buffers
- `const struct drm_framebuffer *fb`: DRM framebuffer
- `const struct drm_rect *clip`: Clip rectangle area to copy
- `struct drm_format_conv_state *state`: Transform and conversion state

**Description**

This function copies parts of a framebuffer to display memory and converts the
color format during the process. Destination and framebuffer formats must match. The
parameters **dst**, **dst_pitch** and **src** refer to arrays. Each array must have at
least as many entries as there are planes in **fb**'s format. Each entry stores the
value for the format's respective color plane at the same index.

This function does not apply clipping on **dst** (i.e. the destination is at the
top-left corner).

Drivers can use this function for RGB888 devices that don't natively
support XRGB8888.

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

```c
void drm_fb_xrgb8888_to_bgr888(struct iosys_map *dst, const unsigned int *dst_pitch, const struct iosys_map *src, const struct drm_framebuffer *fb, const struct drm_rect *clip, struct drm_format_conv_state *state)
```

Convert XRGB8888 to BGR888 clip buffer

**Parameters**

- `struct iosys_map *dst`: Array of BGR888 destination buffers
- `const unsigned int *dst_pitch`: Array of numbers of bytes between the start of two consecutive scanlines
  within **dst**; can be NULL if scanlines are stored next to each other.
- `const struct iosys_map *src`: Array of XRGB8888 source buffers
- `const struct drm_framebuffer *fb`: DRM framebuffer
- `const struct drm_rect *clip`: Clip rectangle area to copy
- `struct drm_format_conv_state *state`: Transform and conversion state

**Description**

This function copies parts of a framebuffer to display memory and converts the
color format during the process. Destination and framebuffer formats must match. The
parameters **dst**, **dst_pitch** and **src** refer to arrays. Each array must have at
least as many entries as there are planes in **fb**'s format. Each entry stores the
value for the format's respective color plane at the same index.

This function does not apply clipping on **dst** (i.e. the destination is at the
top-left corner).

Drivers can use this function for BGR888 devices that don't natively
support XRGB8888.

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

```c
void drm_fb_xrgb8888_to_argb8888(struct iosys_map *dst, const unsigned int *dst_pitch, const struct iosys_map *src, const struct drm_framebuffer *fb, const struct drm_rect *clip, struct drm_format_conv_state *state)
```

Convert XRGB8888 to ARGB8888 clip buffer

**Parameters**

- `struct iosys_map *dst`: Array of ARGB8888 destination buffers
- `const unsigned int *dst_pitch`: Array of numbers of bytes between the start of two consecutive scanlines
  within **dst**; can be NULL if scanlines are stored next to each other.
- `const struct iosys_map *src`: Array of XRGB8888 source buffer
- `const struct drm_framebuffer *fb`: DRM framebuffer
- `const struct drm_rect *clip`: Clip rectangle area to copy
- `struct drm_format_conv_state *state`: Transform and conversion state

**Description**

This function copies parts of a framebuffer to display memory and converts the
color format during the process. The parameters **dst**, **dst_pitch** and **src** refer
to arrays. Each array must have at least as many entries as there are planes in
**fb**'s format. Each entry stores the value for the format's respective color plane
at the same index.

This function does not apply clipping on **dst** (i.e. the destination is at the
top-left corner).

Drivers can use this function for ARGB8888 devices that don't support XRGB8888
natively. It sets an opaque alpha channel as part of the conversion.

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

```c
void drm_fb_xrgb8888_to_abgr8888(struct iosys_map *dst, const unsigned int *dst_pitch, const struct iosys_map *src, const struct drm_framebuffer *fb, const struct drm_rect *clip, struct drm_format_conv_state *state)
```

Convert XRGB8888 to ABGR8888 clip buffer

**Parameters**

- `struct iosys_map *dst`: Array of ABGR8888 destination buffers
- `const unsigned int *dst_pitch`: Array of numbers of bytes between the start of two consecutive scanlines
  within **dst**; can be NULL if scanlines are stored next to each other.
- `const struct iosys_map *src`: Array of XRGB8888 source buffer
- `const struct drm_framebuffer *fb`: DRM framebuffer
- `const struct drm_rect *clip`: Clip rectangle area to copy
- `struct drm_format_conv_state *state`: Transform and conversion state

**Description**

This function copies parts of a framebuffer to display memory and converts the
color format during the process. The parameters **dst**, **dst_pitch** and **src** refer
to arrays. Each array must have at least as many entries as there are planes in
**fb**'s format. Each entry stores the value for the format's respective color plane
at the same index.

This function does not apply clipping on **dst** (i.e. the destination is at the
top-left corner).

Drivers can use this function for ABGR8888 devices that don't support XRGB8888
natively. It sets an opaque alpha channel as part of the conversion.

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

```c
void drm_fb_xrgb8888_to_xbgr8888(struct iosys_map *dst, const unsigned int *dst_pitch, const struct iosys_map *src, const struct drm_framebuffer *fb, const struct drm_rect *clip, struct drm_format_conv_state *state)
```

Convert XRGB8888 to XBGR8888 clip buffer

**Parameters**

- `struct iosys_map *dst`: Array of XBGR8888 destination buffers
- `const unsigned int *dst_pitch`: Array of numbers of bytes between the start of two consecutive scanlines
  within **dst**; can be NULL if scanlines are stored next to each other.
- `const struct iosys_map *src`: Array of XRGB8888 source buffer
- `const struct drm_framebuffer *fb`: DRM framebuffer
- `const struct drm_rect *clip`: Clip rectangle area to copy
- `struct drm_format_conv_state *state`: Transform and conversion state

**Description**

This function copies parts of a framebuffer to display memory and converts the
color format during the process. The parameters **dst**, **dst_pitch** and **src** refer
to arrays. Each array must have at least as many entries as there are planes in
**fb**'s format. Each entry stores the value for the format's respective color plane
at the same index.

This function does not apply clipping on **dst** (i.e. the destination is at the
top-left corner).

Drivers can use this function for XBGR8888 devices that don't support XRGB8888
natively.

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

```c
void drm_fb_xrgb8888_to_bgrx8888(struct iosys_map *dst, const unsigned int *dst_pitch, const struct iosys_map *src, const struct drm_framebuffer *fb, const struct drm_rect *clip, struct drm_format_conv_state *state)
```

Convert XRGB8888 to BGRX8888 clip buffer

**Parameters**

- `struct iosys_map *dst`: Array of BGRX8888 destination buffers
- `const unsigned int *dst_pitch`: Array of numbers of bytes between the start of two consecutive scanlines
  within **dst**; can be NULL if scanlines are stored next to each other.
- `const struct iosys_map *src`: Array of XRGB8888 source buffer
- `const struct drm_framebuffer *fb`: DRM framebuffer
- `const struct drm_rect *clip`: Clip rectangle area to copy
- `struct drm_format_conv_state *state`: Transform and conversion state

**Description**

This function copies parts of a framebuffer to display memory and converts the
color format during the process. The parameters **dst**, **dst_pitch** and **src** refer
to arrays. Each array must have at least as many entries as there are planes in
**fb**'s format. Each entry stores the value for the format's respective color plane
at the same index.

This function does not apply clipping on **dst** (i.e. the destination is at the
top-left corner).

Drivers can use this function for BGRX8888 devices that don't support XRGB8888
natively.

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

```c
void drm_fb_xrgb8888_to_xrgb2101010(struct iosys_map *dst, const unsigned int *dst_pitch, const struct iosys_map *src, const struct drm_framebuffer *fb, const struct drm_rect *clip, struct drm_format_conv_state *state)
```

Convert XRGB8888 to XRGB2101010 clip buffer

**Parameters**

- `struct iosys_map *dst`: Array of XRGB2101010 destination buffers
- `const unsigned int *dst_pitch`: Array of numbers of bytes between the start of two consecutive scanlines
  within **dst**; can be NULL if scanlines are stored next to each other.
- `const struct iosys_map *src`: Array of XRGB8888 source buffers
- `const struct drm_framebuffer *fb`: DRM framebuffer
- `const struct drm_rect *clip`: Clip rectangle area to copy
- `struct drm_format_conv_state *state`: Transform and conversion state

**Description**

This function copies parts of a framebuffer to display memory and converts the
color format during the process. Destination and framebuffer formats must match. The
parameters **dst**, **dst_pitch** and **src** refer to arrays. Each array must have at
least as many entries as there are planes in **fb**'s format. Each entry stores the
value for the format's respective color plane at the same index.

This function does not apply clipping on **dst** (i.e. the destination is at the
top-left corner).

Drivers can use this function for XRGB2101010 devices that don't support XRGB8888
natively.

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

```c
void drm_fb_xrgb8888_to_argb2101010(struct iosys_map *dst, const unsigned int *dst_pitch, const struct iosys_map *src, const struct drm_framebuffer *fb, const struct drm_rect *clip, struct drm_format_conv_state *state)
```

Convert XRGB8888 to ARGB2101010 clip buffer

**Parameters**

- `struct iosys_map *dst`: Array of ARGB2101010 destination buffers
- `const unsigned int *dst_pitch`: Array of numbers of bytes between the start of two consecutive scanlines
  within **dst**; can be NULL if scanlines are stored next to each other.
- `const struct iosys_map *src`: Array of XRGB8888 source buffers
- `const struct drm_framebuffer *fb`: DRM framebuffer
- `const struct drm_rect *clip`: Clip rectangle area to copy
- `struct drm_format_conv_state *state`: Transform and conversion state

**Description**

This function copies parts of a framebuffer to display memory and converts
the color format during the process. The parameters **dst**, **dst_pitch** and
**src** refer to arrays. Each array must have at least as many entries as
there are planes in **fb**'s format. Each entry stores the value for the
format's respective color plane at the same index.

This function does not apply clipping on **dst** (i.e. the destination is at the
top-left corner).

Drivers can use this function for ARGB2101010 devices that don't support XRGB8888
natively.

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

```c
void drm_fb_xrgb8888_to_gray8(struct iosys_map *dst, const unsigned int *dst_pitch, const struct iosys_map *src, const struct drm_framebuffer *fb, const struct drm_rect *clip, struct drm_format_conv_state *state)
```

Convert XRGB8888 to grayscale

**Parameters**

- `struct iosys_map *dst`: Array of 8-bit grayscale destination buffers
- `const unsigned int *dst_pitch`: Array of numbers of bytes between the start of two consecutive scanlines
  within **dst**; can be NULL if scanlines are stored next to each other.
- `const struct iosys_map *src`: Array of XRGB8888 source buffers
- `const struct drm_framebuffer *fb`: DRM framebuffer
- `const struct drm_rect *clip`: Clip rectangle area to copy
- `struct drm_format_conv_state *state`: Transform and conversion state

**Description**

This function copies parts of a framebuffer to display memory and converts the
color format during the process. Destination and framebuffer formats must match. The
parameters **dst**, **dst_pitch** and **src** refer to arrays. Each array must have at
least as many entries as there are planes in **fb**'s format. Each entry stores the
value for the format's respective color plane at the same index.

This function does not apply clipping on **dst** (i.e. the destination is at the
top-left corner).

DRM doesn't have native monochrome or grayscale support. Drivers can use this
function for grayscale devices that don't support XRGB8888 natively.Such
drivers can announce the commonly supported XR24 format to userspace and use
this function to convert to the native format. Monochrome drivers will use the
most significant bit, where 1 means foreground color and 0 background color.
ITU BT.601 is being used for the RGB -> luma (brightness) conversion.

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

```c
void drm_fb_argb8888_to_argb4444(struct iosys_map *dst, const unsigned int *dst_pitch, const struct iosys_map *src, const struct drm_framebuffer *fb, const struct drm_rect *clip, struct drm_format_conv_state *state)
```

Convert ARGB8888 to ARGB4444 clip buffer

**Parameters**

- `struct iosys_map *dst`: Array of ARGB4444 destination buffers
- `const unsigned int *dst_pitch`: Array of numbers of bytes between the start of two consecutive scanlines
  within **dst**; can be NULL if scanlines are stored next to each other.
- `const struct iosys_map *src`: Array of ARGB8888 source buffer
- `const struct drm_framebuffer *fb`: DRM framebuffer
- `const struct drm_rect *clip`: Clip rectangle area to copy
- `struct drm_format_conv_state *state`: Transform and conversion state

**Description**

This function copies parts of a framebuffer to display memory and converts
the color format during the process. The parameters **dst**, **dst_pitch** and
**src** refer to arrays. Each array must have at least as many entries as
there are planes in **fb**'s format. Each entry stores the value for the
format's respective color plane at the same index.

This function does not apply clipping on **dst** (i.e. the destination is at the
top-left corner).

Drivers can use this function for ARGB4444 devices that don't support
ARGB8888 natively.

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

```c
void drm_fb_xrgb8888_to_mono(struct iosys_map *dst, const unsigned int *dst_pitch, const struct iosys_map *src, const struct drm_framebuffer *fb, const struct drm_rect *clip, struct drm_format_conv_state *state)
```

Convert XRGB8888 to monochrome

**Parameters**

- `struct iosys_map *dst`: Array of monochrome destination buffers (0=black, 1=white)
- `const unsigned int *dst_pitch`: Array of numbers of bytes between the start of two consecutive scanlines
  within **dst**; can be NULL if scanlines are stored next to each other.
- `const struct iosys_map *src`: Array of XRGB8888 source buffers
- `const struct drm_framebuffer *fb`: DRM framebuffer
- `const struct drm_rect *clip`: Clip rectangle area to copy
- `struct drm_format_conv_state *state`: Transform and conversion state

**Description**

This function copies parts of a framebuffer to display memory and converts the
color format during the process. Destination and framebuffer formats must match. The
parameters **dst**, **dst_pitch** and **src** refer to arrays. Each array must have at
least as many entries as there are planes in **fb**'s format. Each entry stores the
value for the format's respective color plane at the same index.

This function does not apply clipping on **dst** (i.e. the destination is at the
top-left corner). The first pixel (upper left corner of the clip rectangle) will
be converted and copied to the first bit (LSB) in the first byte of the monochrome
destination buffer. If the caller requires that the first pixel in a byte must
be located at an x-coordinate that is a multiple of 8, then the caller must take
care itself of supplying a suitable clip rectangle.

DRM doesn't have native monochrome support. Drivers can use this function for
monochrome devices that don't support XRGB8888 natively. Such drivers can
announce the commonly supported XR24 format to userspace and use this function
to convert to the native format.

This function uses [`drm_fb_xrgb8888_to_gray8()`](#c-drm_fb_xrgb8888_to_gray8) to convert to grayscale and
then the result is converted from grayscale to monochrome.

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

```c
void drm_fb_xrgb8888_to_gray2(struct iosys_map *dst, const unsigned int *dst_pitch, const struct iosys_map *src, const struct drm_framebuffer *fb, const struct drm_rect *clip, struct drm_format_conv_state *state)
```

Convert XRGB8888 to gray2

**Parameters**

- `struct iosys_map *dst`: Array of gray2 destination buffer
- `const unsigned int *dst_pitch`: Array of numbers of bytes between the start of two consecutive scanlines
  within **dst**; can be NULL if scanlines are stored next to each other.
- `const struct iosys_map *src`: Array of XRGB8888 source buffers
- `const struct drm_framebuffer *fb`: DRM framebuffer
- `const struct drm_rect *clip`: Clip rectangle area to copy
- `struct drm_format_conv_state *state`: Transform and conversion state

**Description**

This function copies parts of a framebuffer to display memory and converts the
color format during the process. Destination and framebuffer formats must match. The
parameters **dst**, **dst_pitch** and **src** refer to arrays. Each array must have at
least as many entries as there are planes in **fb**'s format. Each entry stores the
value for the format's respective color plane at the same index.

This function does not apply clipping on **dst** (i.e. the destination is at the
top-left corner). The first pixel (upper left corner of the clip rectangle) will
be converted and copied to the two first bits (LSB) in the first byte of the gray2
destination buffer. If the caller requires that the first pixel in a byte must
be located at an x-coordinate that is a multiple of 8, then the caller must take
care itself of supplying a suitable clip rectangle.

DRM doesn't have native gray2 support. Drivers can use this function for
gray2 devices that don't support XRGB8888 natively. Such drivers can
announce the commonly supported XR24 format to userspace and use this function
to convert to the native format.


<a id="rst-framebuffer-dma-helper-functions-reference"></a>

## Framebuffer DMA Helper Functions Reference


Provides helper functions for creating a DMA-contiguous framebuffer.

Depending on the platform, the buffers may be physically non-contiguous and
mapped through an IOMMU or a similar mechanism, or allocated from
physically-contiguous memory (using, for instance, CMA or a pool of memory
reserved at early boot). This is handled behind the scenes by the DMA mapping
API.

[`drm_gem_fb_create()`](#c-drm_gem_fb_create) is used in the [`drm_mode_config_funcs.fb_create`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_mode_config_funcs)
callback function to create a DMA-contiguous framebuffer.



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

```c
struct drm_gem_dma_object * drm_fb_dma_get_gem_obj(struct drm_framebuffer *fb, unsigned int plane)
```

Get DMA GEM object for framebuffer

**Parameters**

- `struct drm_framebuffer *fb`: The framebuffer
- `unsigned int plane`: Which plane

**Description**

Return the DMA GEM object for given framebuffer.

This function will usually be called from the CRTC callback functions.

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

```c
dma_addr_t drm_fb_dma_get_gem_addr(struct drm_framebuffer *fb, struct drm_plane_state *state, unsigned int plane)
```

Get DMA (bus) address for framebuffer, for pixel formats where values are grouped in blocks this will get you the beginning of the block

**Parameters**

- `struct drm_framebuffer *fb`: The framebuffer
- `struct drm_plane_state *state`: Which state of drm plane
- `unsigned int plane`: Which plane
  Return the DMA GEM address for given framebuffer.

**Description**

This function will usually be called from the PLANE callback functions.

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

```c
void drm_fb_dma_sync_non_coherent(struct drm_device *drm, struct drm_plane_state *old_state, struct drm_plane_state *state)
```

Sync GEM object to non-coherent backing memory

**Parameters**

- `struct drm_device *drm`: DRM device
- `struct drm_plane_state *old_state`: Old plane state
- `struct drm_plane_state *state`: New plane state

**Description**

This function can be used by drivers that use damage clips and have
DMA GEM objects backed by non-coherent memory. Calling this function
in a plane's .atomic_update ensures that all the data in the backing
memory have been written to RAM.

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

```c
int drm_fb_dma_get_scanout_buffer(struct drm_plane *plane, struct drm_scanout_buffer *sb)
```

Provide a scanout buffer in case of panic

**Parameters**

- `struct drm_plane *plane`: DRM primary plane
- `struct drm_scanout_buffer *sb`: scanout buffer for the panic handler

**Return**

0 or negative error code

**Description**

Generic `get_scanout_buffer()` implementation, for drivers that uses the
drm_fb_dma_helper. It won't call vmap in the panic context, so the driver
should make sure the primary plane is vmapped, otherwise the panic screen
won't get displayed.


<a id="rst-framebuffer-gem-helper-reference"></a>

## Framebuffer GEM Helper Reference


This library provides helpers for drivers that don't subclass
[`drm_framebuffer`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_framebuffer) and use [`drm_gem_object`](/kernel/hardware/gpu/drm-mm.md#c-struct-drm_gem_object) for their backing storage.

Drivers without additional needs to validate framebuffers can simply use
[`drm_gem_fb_create()`](#c-drm_gem_fb_create) and everything is wired up automatically. Other drivers
can use all parts independently.



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

```c
struct drm_gem_object * drm_gem_fb_get_obj(struct drm_framebuffer *fb, unsigned int plane)
```

Get GEM object backing the framebuffer

**Parameters**

- `struct drm_framebuffer *fb`: Framebuffer
- `unsigned int plane`: Plane index

**Description**

No additional reference is taken beyond the one that the `drm_frambuffer`
already holds.

**Return**

Pointer to [`drm_gem_object`](/kernel/hardware/gpu/drm-mm.md#c-struct-drm_gem_object) for the given framebuffer and plane index or NULL
if it does not exist.

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

```c
void drm_gem_fb_destroy(struct drm_framebuffer *fb)
```

Free GEM backed framebuffer

**Parameters**

- `struct drm_framebuffer *fb`: Framebuffer

**Description**

Frees a GEM backed framebuffer with its backing buffer(s) and the structure
itself. Drivers can use this as their [`drm_framebuffer_funcs->destroy`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_framebuffer_funcs)
callback.

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

```c
int drm_gem_fb_create_handle(struct drm_framebuffer *fb, struct drm_file *file, unsigned int *handle)
```

Create handle for GEM backed framebuffer

**Parameters**

- `struct drm_framebuffer *fb`: Framebuffer
- `struct drm_file *file`: DRM file to register the handle for
- `unsigned int *handle`: Pointer to return the created handle

**Description**

This function creates a handle for the GEM object backing the framebuffer.
Drivers can use this as their [`drm_framebuffer_funcs->create_handle`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_framebuffer_funcs)
callback. The GETFB IOCTL calls into this callback.

**Return**

0 on success or a negative error code on failure.

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

```c
int drm_gem_fb_init_with_funcs(struct drm_device *dev, struct drm_framebuffer *fb, struct drm_file *file, const struct drm_format_info *info, const struct drm_mode_fb_cmd2 *mode_cmd, const struct drm_framebuffer_funcs *funcs)
```

Helper function for implementing [`drm_mode_config_funcs.fb_create`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_mode_config_funcs) callback in cases when the driver allocates a subclass of struct drm_framebuffer

**Parameters**

- `struct drm_device *dev`: DRM device
- `struct drm_framebuffer *fb`: framebuffer object
- `struct drm_file *file`: DRM file that holds the GEM handle(s) backing the framebuffer
- `const struct drm_format_info *info`: pixel format information
- `const struct drm_mode_fb_cmd2 *mode_cmd`: Metadata from the userspace framebuffer creation request
- `const struct drm_framebuffer_funcs *funcs`: vtable to be used for the new framebuffer object

**Description**

This function can be used to set [`drm_framebuffer_funcs`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_framebuffer_funcs) for drivers that need
custom framebuffer callbacks. Use [`drm_gem_fb_create()`](#c-drm_gem_fb_create) if you don't need to
change [`drm_framebuffer_funcs`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_framebuffer_funcs). The function does buffer size validation.
The buffer size validation is for a general case, though, so users should
pay attention to the checks being appropriate for them or, at least,
non-conflicting.

**Return**

Zero or a negative error code.

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

```c
struct drm_framebuffer * drm_gem_fb_create_with_funcs(struct drm_device *dev, struct drm_file *file, const struct drm_format_info *info, const struct drm_mode_fb_cmd2 *mode_cmd, const struct drm_framebuffer_funcs *funcs)
```

Helper function for the [`drm_mode_config_funcs.fb_create`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_mode_config_funcs) callback

**Parameters**

- `struct drm_device *dev`: DRM device
- `struct drm_file *file`: DRM file that holds the GEM handle(s) backing the framebuffer
- `const struct drm_format_info *info`: pixel format information
- `const struct drm_mode_fb_cmd2 *mode_cmd`: Metadata from the userspace framebuffer creation request
- `const struct drm_framebuffer_funcs *funcs`: vtable to be used for the new framebuffer object

**Description**

This function can be used to set [`drm_framebuffer_funcs`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_framebuffer_funcs) for drivers that need
custom framebuffer callbacks. Use [`drm_gem_fb_create()`](#c-drm_gem_fb_create) if you don't need to
change [`drm_framebuffer_funcs`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_framebuffer_funcs). The function does buffer size validation.

**Return**

Pointer to a [`drm_framebuffer`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_framebuffer) on success or an error pointer on failure.

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

```c
struct drm_framebuffer * drm_gem_fb_create(struct drm_device *dev, struct drm_file *file, const struct drm_format_info *info, const struct drm_mode_fb_cmd2 *mode_cmd)
```

Helper function for the [`drm_mode_config_funcs.fb_create`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_mode_config_funcs) callback

**Parameters**

- `struct drm_device *dev`: DRM device
- `struct drm_file *file`: DRM file that holds the GEM handle(s) backing the framebuffer
- `const struct drm_format_info *info`: pixel format information
- `const struct drm_mode_fb_cmd2 *mode_cmd`: Metadata from the userspace framebuffer creation request

**Description**

This function creates a new framebuffer object described by
[`drm_mode_fb_cmd2`](/kernel/hardware/gpu/drm-uapi.md#c-struct-drm_mode_fb_cmd2). This description includes handles for the buffer(s)
backing the framebuffer.

If your hardware has special alignment or pitch requirements these should be
checked before calling this function. The function does buffer size
validation. Use [`drm_gem_fb_create_with_dirty()`](#c-drm_gem_fb_create_with_dirty) if you need framebuffer
flushing.

Drivers can use this as their [`drm_mode_config_funcs.fb_create`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_mode_config_funcs) callback.
The ADDFB2 IOCTL calls into this callback.

**Return**

Pointer to a [`drm_framebuffer`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_framebuffer) on success or an error pointer on failure.

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

```c
struct drm_framebuffer * drm_gem_fb_create_with_dirty(struct drm_device *dev, struct drm_file *file, const struct drm_format_info *info, const struct drm_mode_fb_cmd2 *mode_cmd)
```

Helper function for the [`drm_mode_config_funcs.fb_create`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_mode_config_funcs) callback

**Parameters**

- `struct drm_device *dev`: DRM device
- `struct drm_file *file`: DRM file that holds the GEM handle(s) backing the framebuffer
- `const struct drm_format_info *info`: pixel format information
- `const struct drm_mode_fb_cmd2 *mode_cmd`: Metadata from the userspace framebuffer creation request

**Description**

This function creates a new framebuffer object described by
[`drm_mode_fb_cmd2`](/kernel/hardware/gpu/drm-uapi.md#c-struct-drm_mode_fb_cmd2). This description includes handles for the buffer(s)
backing the framebuffer. [`drm_atomic_helper_dirtyfb()`](/kernel/hardware/gpu/drm-kms.md#c-drm_atomic_helper_dirtyfb) is used for the dirty
callback giving framebuffer flushing through the atomic machinery. Use
[`drm_gem_fb_create()`](#c-drm_gem_fb_create) if you don't need the dirty callback.
The function does buffer size validation.

Drivers should also call [`drm_plane_enable_fb_damage_clips()`](/kernel/hardware/gpu/drm-kms.md#c-drm_plane_enable_fb_damage_clips) on all planes
to enable userspace to use damage clips also with the ATOMIC IOCTL.

Drivers can use this as their [`drm_mode_config_funcs.fb_create`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_mode_config_funcs) callback.
The ADDFB2 IOCTL calls into this callback.

**Return**

Pointer to a [`drm_framebuffer`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_framebuffer) on success or an error pointer on failure.

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

```c
int drm_gem_fb_vmap(struct drm_framebuffer *fb, struct iosys_map *map, struct iosys_map *data)
```

maps all framebuffer BOs into kernel address space

**Parameters**

- `struct drm_framebuffer *fb`: the framebuffer
- `struct iosys_map *map`: returns the mapping's address for each BO
- `struct iosys_map *data`: returns the data address for each BO, can be NULL

**Description**

This function maps all buffer objects of the given framebuffer into
kernel address space and stores them in struct iosys_map. If the
mapping operation fails for one of the BOs, the function unmaps the
already established mappings automatically.

Callers that want to access a BO's stored data should pass **data**.
The argument returns the addresses of the data stored in each BO. This
is different from **map** if the framebuffer's offsets field is non-zero.

Both, **map** and **data**, must each refer to arrays with at least
fb->format->num_planes elements.

See [`drm_gem_fb_vunmap()`](#c-drm_gem_fb_vunmap) for unmapping.

**Return**

0 on success, or a negative errno code otherwise.

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

```c
void drm_gem_fb_vunmap(struct drm_framebuffer *fb, struct iosys_map *map)
```

unmaps framebuffer BOs from kernel address space

**Parameters**

- `struct drm_framebuffer *fb`: the framebuffer
- `struct iosys_map *map`: mapping addresses as returned by [`drm_gem_fb_vmap()`](#c-drm_gem_fb_vmap)

**Description**

This function unmaps all buffer objects of the given framebuffer.

See [`drm_gem_fb_vmap()`](#c-drm_gem_fb_vmap) for more information.

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

```c
int drm_gem_fb_begin_cpu_access(struct drm_framebuffer *fb, enum dma_data_direction dir)
```

prepares GEM buffer objects for CPU access

**Parameters**

- `struct drm_framebuffer *fb`: the framebuffer
- `enum dma_data_direction dir`: access mode

**Description**

Prepares a framebuffer's GEM buffer objects for CPU access. This function
must be called before accessing the BO data within the kernel. For imported
BOs, the function calls [`dma_buf_begin_cpu_access()`](/kernel/hardware/driver-api/io-and-dma/dma-buf.md#c-dma_buf_begin_cpu_access).

See [`drm_gem_fb_end_cpu_access()`](#c-drm_gem_fb_end_cpu_access) for signalling the end of CPU access.

**Return**

0 on success, or a negative errno code otherwise.

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

```c
void drm_gem_fb_end_cpu_access(struct drm_framebuffer *fb, enum dma_data_direction dir)
```

signals end of CPU access to GEM buffer objects

**Parameters**

- `struct drm_framebuffer *fb`: the framebuffer
- `enum dma_data_direction dir`: access mode

**Description**

Signals the end of CPU access to the given framebuffer's GEM buffer objects. This
function must be paired with a corresponding call to [`drm_gem_fb_begin_cpu_access()`](#c-drm_gem_fb_begin_cpu_access).
For imported BOs, the function calls [`dma_buf_end_cpu_access()`](/kernel/hardware/driver-api/io-and-dma/dma-buf.md#c-dma_buf_end_cpu_access).

See also [`drm_gem_fb_begin_cpu_access()`](#c-drm_gem_fb_begin_cpu_access).

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

```c
int drm_gem_fb_afbc_init(struct drm_device *dev, const struct drm_format_info *info, const struct drm_mode_fb_cmd2 *mode_cmd, struct drm_afbc_framebuffer *afbc_fb)
```

Helper function for drivers using afbc to fill and validate all the afbc-specific struct drm_afbc_framebuffer members

**Parameters**

- `struct drm_device *dev`: DRM device
- `const struct drm_format_info *info`: pixel format information
- `const struct drm_mode_fb_cmd2 *mode_cmd`: Metadata from the userspace framebuffer creation request
- `struct drm_afbc_framebuffer *afbc_fb`: afbc framebuffer

**Description**

This function can be used by drivers which support afbc to complete
the preparation of struct drm_afbc_framebuffer. It must be called after
allocating the said struct and calling [`drm_gem_fb_init_with_funcs()`](#c-drm_gem_fb_init_with_funcs).
It is caller's responsibility to put afbc_fb->base.obj objects in case
the call is unsuccessful.

**Return**

Zero on success or a negative error value on failure.


<a id="rst-bridges"></a>
<a id="rst-drm-bridges"></a>

## Bridges

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

### Overview


[`struct drm_bridge`](#c-struct-drm_bridge) represents a device that hangs on to an encoder. These are
handy when a regular [`drm_encoder`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_encoder) entity isn't enough to represent the entire
encoder chain.

A bridge is always attached to a single [`drm_encoder`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_encoder) at a time, but can be
either connected to it directly, or through a chain of bridges:

```text
[ CRTC ---> ] Encoder ---> Bridge A ---> Bridge B
```

Here, the output of the encoder feeds to bridge A, and that furthers feeds to
bridge B. Bridge chains can be arbitrarily long, and shall be fully linear:
Chaining multiple bridges to the output of a bridge, or the same bridge to
the output of different bridges, is not supported.

[`drm_bridge`](#c-struct-drm_bridge), like [`drm_panel`](#c-struct-drm_panel), aren't [`drm_mode_object`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_mode_object) entities like planes,
CRTCs, encoders or connectors and hence are not visible to userspace. They
just provide additional hooks to get the desired output at the end of the
encoder chain.


<a id="rst-display-driver-integration"></a>

### Display Driver Integration


Display drivers are responsible for linking encoders with the first bridge
in the chains. This is done by acquiring the appropriate bridge with
[`devm_drm_of_get_bridge()`](#c-devm_drm_of_get_bridge). Once acquired, the bridge shall be attached to the
encoder with a call to [`drm_bridge_attach()`](#c-drm_bridge_attach).

Bridges are responsible for linking themselves with the next bridge in the
chain, if any. This is done the same way as for encoders, with the call to
[`drm_bridge_attach()`](#c-drm_bridge_attach) occurring in the [`drm_bridge_funcs.attach`](#c-struct-drm_bridge_funcs) operation.

Once these links are created, the bridges can participate along with encoder
functions to perform mode validation and fixup (through
[`drm_bridge_chain_mode_valid()`](#c-drm_bridge_chain_mode_valid) and [`drm_atomic_bridge_chain_check()`](#c-drm_atomic_bridge_chain_check)), mode
setting (through [`drm_bridge_chain_mode_set()`](#c-drm_bridge_chain_mode_set)), enable (through
[`drm_atomic_bridge_chain_pre_enable()`](#c-drm_atomic_bridge_chain_pre_enable) and [`drm_atomic_bridge_chain_enable()`](#c-drm_atomic_bridge_chain_enable))
and disable (through [`drm_atomic_bridge_chain_disable()`](#c-drm_atomic_bridge_chain_disable) and
[`drm_atomic_bridge_chain_post_disable()`](#c-drm_atomic_bridge_chain_post_disable)). Those functions call the
corresponding operations provided in [`drm_bridge_funcs`](#c-struct-drm_bridge_funcs) in sequence for all
bridges in the chain.

For display drivers that use the atomic helpers
[`drm_atomic_helper_check_modeset()`](#c-drm_atomic_helper_check_modeset),
[`drm_atomic_helper_commit_modeset_enables()`](#c-drm_atomic_helper_commit_modeset_enables) and
[`drm_atomic_helper_commit_modeset_disables()`](#c-drm_atomic_helper_commit_modeset_disables) (either directly in hand-rolled
commit check and commit tail handlers, or through the higher-level
[`drm_atomic_helper_check()`](#c-drm_atomic_helper_check) and [`drm_atomic_helper_commit_tail()`](#c-drm_atomic_helper_commit_tail) or
[`drm_atomic_helper_commit_tail_rpm()`](#c-drm_atomic_helper_commit_tail_rpm) helpers), this is done transparently and
requires no intervention from the driver. For other drivers, the relevant
DRM bridge chain functions shall be called manually.

Bridges also participate in implementing the [`drm_connector`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_connector) at the end of
the bridge chain. Display drivers may use the [`drm_bridge_connector_init()`](#c-drm_bridge_connector_init)
helper to create the [`drm_connector`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_connector), or implement it manually on top of the
connector-related operations exposed by the bridge (see the overview
documentation of bridge operations for more details).


<a id="rst-special-care-with-mipi-dsi-bridges"></a>

### Special Care with MIPI-DSI bridges


The interaction between the bridges and other frameworks involved in
the probing of the upstream driver and the bridge driver can be
challenging. Indeed, there's multiple cases that needs to be
considered:

- The upstream driver doesn't use the component framework and isn't a
  MIPI-DSI host. In this case, the bridge driver will probe at some
  point and the upstream driver should try to probe again by returning
  EPROBE_DEFER as long as the bridge driver hasn't probed.

- The upstream driver doesn't use the component framework, but is a
  MIPI-DSI host. The bridge device uses the MIPI-DCS commands to be
  controlled. In this case, the bridge device is a child of the
  display device and when it will probe it's assured that the display
  device (and MIPI-DSI host) is present. The upstream driver will be
  assured that the bridge driver is connected between the
  [`mipi_dsi_host_ops.attach`](#c-struct-mipi_dsi_host_ops) and [`mipi_dsi_host_ops.detach`](#c-struct-mipi_dsi_host_ops) operations.
  Therefore, it must run `mipi_dsi_host_register()` in its probe
  function, and then run [`drm_bridge_attach()`](#c-drm_bridge_attach) in its
  [`mipi_dsi_host_ops.attach`](#c-struct-mipi_dsi_host_ops) hook.

- The upstream driver uses the component framework and is a MIPI-DSI
  host. The bridge device uses the MIPI-DCS commands to be
  controlled. This is the same situation than above, and can run
  `mipi_dsi_host_register()` in either its probe or bind hooks.

- The upstream driver uses the component framework and is a MIPI-DSI
  host. The bridge device uses a separate bus (such as I2C) to be
  controlled. In this case, there's no correlation between the probe
  of the bridge and upstream drivers, so care must be taken to avoid
  an endless EPROBE_DEFER loop, with each driver waiting for the
  other to probe.

The ideal pattern to cover the last item (and all the others in the
MIPI-DSI host driver case) is to split the operations like this:

- The MIPI-DSI host driver must run `mipi_dsi_host_register()` in its
  probe hook. It will make sure that the MIPI-DSI host sticks around,
  and that the driver's bind can be called.

- In its probe hook, the bridge driver must try to find its MIPI-DSI
  host, register as a MIPI-DSI device and attach the MIPI-DSI device
  to its host. The bridge driver is now functional.

- In its [`struct mipi_dsi_host_ops`](#c-struct-mipi_dsi_host_ops).attach hook, the MIPI-DSI host can
  now add its component. Its bind hook will now be called and since
  the bridge driver is attached and registered, we can now look for
  and attach it.

At this point, we're now certain that both the upstream driver and
the bridge driver are functional and we can't have a deadlock-like
situation when probing.


<a id="rst-bridge-operations"></a>

### Bridge Operations


Bridge drivers expose operations through the [`drm_bridge_funcs`](#c-struct-drm_bridge_funcs) structure.
The DRM internals (atomic and CRTC helpers) use the helpers defined in
drm_bridge.c to call bridge operations. Those operations are divided in
three big categories to support different parts of the bridge usage.

- The encoder-related operations support control of the bridges in the
  chain, and are roughly counterparts to the [`drm_encoder_helper_funcs`](#c-struct-drm_encoder_helper_funcs)
  operations. They are used by the legacy CRTC and the atomic modeset
  helpers to perform mode validation, fixup and setting, and enable and
  disable the bridge automatically.

  The enable and disable operations are split in
  [`drm_bridge_funcs.pre_enable`](#c-struct-drm_bridge_funcs), [`drm_bridge_funcs.enable`](#c-struct-drm_bridge_funcs),
  [`drm_bridge_funcs.disable`](#c-struct-drm_bridge_funcs) and [`drm_bridge_funcs.post_disable`](#c-struct-drm_bridge_funcs) to provide
  finer-grained control.

  Bridge drivers may implement the legacy version of those operations, or
  the atomic version (prefixed with atomic\_), in which case they shall also
  implement the atomic state bookkeeping operations
  ([`drm_bridge_funcs.atomic_duplicate_state`](#c-struct-drm_bridge_funcs),
  [`drm_bridge_funcs.atomic_destroy_state`](#c-struct-drm_bridge_funcs) and [`drm_bridge_funcs.reset`](#c-struct-drm_bridge_funcs)).
  Mixing atomic and non-atomic versions of the operations is not supported.

- The bus format negotiation operations
  [`drm_bridge_funcs.atomic_get_output_bus_fmts`](#c-struct-drm_bridge_funcs) and
  [`drm_bridge_funcs.atomic_get_input_bus_fmts`](#c-struct-drm_bridge_funcs) allow bridge drivers to
  negotiate the formats transmitted between bridges in the chain when
  multiple formats are supported. Negotiation for formats is performed
  transparently for display drivers by the atomic modeset helpers. Only
  atomic versions of those operations exist, bridge drivers that need to
  implement them shall thus also implement the atomic version of the
  encoder-related operations. This feature is not supported by the legacy
  CRTC helpers.

- The connector-related operations support implementing a [`drm_connector`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_connector)
  based on a chain of bridges. DRM bridges traditionally create a
  [`drm_connector`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_connector) for bridges meant to be used at the end of the chain. This
  puts additional burden on bridge drivers, especially for bridges that may
  be used in the middle of a chain or at the end of it. Furthermore, it
  requires all operations of the [`drm_connector`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_connector) to be handled by a single
  bridge, which doesn't always match the hardware architecture.

  To simplify bridge drivers and make the connector implementation more
  flexible, a new model allows bridges to unconditionally skip creation of
  [`drm_connector`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_connector) and instead expose [`drm_bridge_funcs`](#c-struct-drm_bridge_funcs) operations to support
  an externally-implemented [`drm_connector`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_connector). Those operations are
  [`drm_bridge_funcs.detect`](#c-struct-drm_bridge_funcs), [`drm_bridge_funcs.get_modes`](#c-struct-drm_bridge_funcs),
  [`drm_bridge_funcs.get_edid`](#c-struct-drm_bridge_funcs), [`drm_bridge_funcs.hpd_notify`](#c-struct-drm_bridge_funcs),
  [`drm_bridge_funcs.hpd_enable`](#c-struct-drm_bridge_funcs) and [`drm_bridge_funcs.hpd_disable`](#c-struct-drm_bridge_funcs). When
  implemented, display drivers shall create a [`drm_connector`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_connector) instance for
  each chain of bridges, and implement those connector instances based on
  the bridge connector operations.

  Bridge drivers shall implement the connector-related operations for all
  the features that the bridge hardware support. For instance, if a bridge
  supports reading EDID, the [`drm_bridge_funcs.get_edid`](#c-struct-drm_bridge_funcs) shall be
  implemented. This however doesn't mean that the DDC lines are wired to the
  bridge on a particular platform, as they could also be connected to an I2C
  controller of the SoC. Support for the connector-related operations on the
  running platform is reported through the [`drm_bridge.ops`](#c-struct-drm_bridge) flags. Bridge
  drivers shall detect which operations they can support on the platform
  (usually this information is provided by ACPI or DT), and set the
  [`drm_bridge.ops`](#c-struct-drm_bridge) flags for all supported operations. A flag shall only be
  set if the corresponding [`drm_bridge_funcs`](#c-struct-drm_bridge_funcs) operation is implemented, but
  an implemented operation doesn't necessarily imply that the corresponding
  flag will be set. Display drivers shall use the [`drm_bridge.ops`](#c-struct-drm_bridge) flags to
  decide which bridge to delegate a connector operation to. This mechanism
  allows providing a single static const [`drm_bridge_funcs`](#c-struct-drm_bridge_funcs) instance in
  bridge drivers, improving security by storing function pointers in
  read-only memory.

  In order to ease transition, bridge drivers may support both the old and
  new models by making connector creation optional and implementing the
  connected-related bridge operations. Connector creation is then controlled
  by the flags argument to the [`drm_bridge_attach()`](#c-drm_bridge_attach) function. Display drivers
  that support the new model and create connectors themselves shall set the
  `DRM_BRIDGE_ATTACH_NO_CONNECTOR` flag, and bridge drivers shall then skip
  connector creation. For intermediate bridges in the chain, the flag shall
  be passed to the [`drm_bridge_attach()`](#c-drm_bridge_attach) call for the downstream bridge.
  Bridge drivers that implement the new model only shall return an error
  from their [`drm_bridge_funcs.attach`](#c-struct-drm_bridge_funcs) handler when the
  `DRM_BRIDGE_ATTACH_NO_CONNECTOR` flag is not set. New display drivers
  should use the new model, and convert the bridge drivers they use if
  needed, in order to gradually transition to the new model.


<a id="rst-bridge-connector-helper"></a>

### Bridge Connector Helper


The DRM bridge connector helper object provides a DRM connector
implementation that wraps a chain of [`struct drm_bridge`](#c-struct-drm_bridge). The connector
operations are fully implemented based on the operations of the bridges in
the chain, and don't require any intervention from the display controller
driver at runtime.

To use the helper, display controller drivers create a bridge connector with
a call to [`drm_bridge_connector_init()`](#c-drm_bridge_connector_init). This associates the newly created
connector with the chain of bridges passed to the function and registers it
with the DRM device. At that point the connector becomes fully usable, no
further operation is needed.

The DRM bridge connector operations are implemented based on the operations
provided by the bridges in the chain. Each connector operation is delegated
to the bridge closest to the connector (at the end of the chain) that
provides the relevant functionality.

To make use of this helper, all bridges in the chain shall report bridge
operation flags ([`drm_bridge->ops`](#c-struct-drm_bridge)) and bridge output type
([`drm_bridge->type`](#c-struct-drm_bridge)), as well as the DRM_BRIDGE_ATTACH_NO_CONNECTOR attach
flag (none of the bridges shall create a DRM connector directly).


<a id="rst-bridge-helper-reference"></a>

### Bridge Helper Reference


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

Flags for [`drm_bridge_funcs.attach`](#c-struct-drm_bridge_funcs)

**Constants**

- `DRM_BRIDGE_ATTACH_NO_CONNECTOR`: When this flag is set the bridge
  shall not create a drm_connector.

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

drm_bridge control functions

**Definition**

```c
struct drm_bridge_funcs {
    int (*attach)(struct drm_bridge *bridge, struct drm_encoder *encoder, enum drm_bridge_attach_flags flags);
    void (*destroy)(struct drm_bridge *bridge);
    void (*detach)(struct drm_bridge *bridge);
    enum drm_mode_status (*mode_valid)(struct drm_bridge *bridge, const struct drm_display_info *info, const struct drm_display_mode *mode);
    bool (*mode_fixup)(struct drm_bridge *bridge, const struct drm_display_mode *mode, struct drm_display_mode *adjusted_mode);
    void (*disable)(struct drm_bridge *bridge);
    void (*post_disable)(struct drm_bridge *bridge);
    void (*mode_set)(struct drm_bridge *bridge, const struct drm_display_mode *mode, const struct drm_display_mode *adjusted_mode);
    void (*pre_enable)(struct drm_bridge *bridge);
    void (*enable)(struct drm_bridge *bridge);
    void (*atomic_pre_enable)(struct drm_bridge *bridge, struct drm_atomic_state *state);
    void (*atomic_enable)(struct drm_bridge *bridge, struct drm_atomic_state *state);
    void (*atomic_disable)(struct drm_bridge *bridge, struct drm_atomic_state *state);
    void (*atomic_post_disable)(struct drm_bridge *bridge, struct drm_atomic_state *state);
    struct drm_bridge_state *(*atomic_duplicate_state)(struct drm_bridge *bridge);
    void (*atomic_destroy_state)(struct drm_bridge *bridge, struct drm_bridge_state *state);
    u32 *(*atomic_get_output_bus_fmts)(struct drm_bridge *bridge, struct drm_bridge_state *bridge_state, struct drm_crtc_state *crtc_state, struct drm_connector_state *conn_state, unsigned int *num_output_fmts);
    u32 *(*atomic_get_input_bus_fmts)(struct drm_bridge *bridge, struct drm_bridge_state *bridge_state, struct drm_crtc_state *crtc_state, struct drm_connector_state *conn_state, u32 output_fmt, unsigned int *num_input_fmts);
    int (*atomic_check)(struct drm_bridge *bridge, struct drm_bridge_state *bridge_state, struct drm_crtc_state *crtc_state, struct drm_connector_state *conn_state);
    struct drm_bridge_state *(*atomic_reset)(struct drm_bridge *bridge);
    enum drm_connector_status (*detect)(struct drm_bridge *bridge, struct drm_connector *connector);
    int (*get_modes)(struct drm_bridge *bridge, struct drm_connector *connector);
    const struct drm_edid *(*edid_read)(struct drm_bridge *bridge, struct drm_connector *connector);
    void (*hpd_notify)(struct drm_bridge *bridge, struct drm_connector *connector, enum drm_connector_status status);
    void (*hpd_enable)(struct drm_bridge *bridge);
    void (*hpd_disable)(struct drm_bridge *bridge);
    enum drm_mode_status (*hdmi_tmds_char_rate_valid)(const struct drm_bridge *bridge, const struct drm_display_mode *mode, unsigned long long tmds_rate);
    int (*hdmi_clear_avi_infoframe)(struct drm_bridge *bridge);
    int (*hdmi_write_avi_infoframe)(struct drm_bridge *bridge, const u8 *buffer, size_t len);
    int (*hdmi_clear_hdmi_infoframe)(struct drm_bridge *bridge);
    int (*hdmi_write_hdmi_infoframe)(struct drm_bridge *bridge, const u8 *buffer, size_t len);
    int (*hdmi_clear_hdr_drm_infoframe)(struct drm_bridge *bridge);
    int (*hdmi_write_hdr_drm_infoframe)(struct drm_bridge *bridge, const u8 *buffer, size_t len);
    int (*hdmi_clear_spd_infoframe)(struct drm_bridge *bridge);
    int (*hdmi_write_spd_infoframe)(struct drm_bridge *bridge, const u8 *buffer, size_t len);
    int (*hdmi_clear_audio_infoframe)(struct drm_bridge *bridge);
    int (*hdmi_write_audio_infoframe)(struct drm_bridge *bridge, const u8 *buffer, size_t len);
    int (*hdmi_audio_startup)(struct drm_bridge *bridge, struct drm_connector *connector);
    int (*hdmi_audio_prepare)(struct drm_bridge *bridge, struct drm_connector *connector, struct hdmi_codec_daifmt *fmt, struct hdmi_codec_params *hparms);
    void (*hdmi_audio_shutdown)(struct drm_bridge *bridge, struct drm_connector *connector);
    int (*hdmi_audio_mute_stream)(struct drm_bridge *bridge, struct drm_connector *connector, bool enable, int direction);
    int (*hdmi_cec_init)(struct drm_bridge *bridge, struct drm_connector *connector);
    int (*hdmi_cec_enable)(struct drm_bridge *bridge, bool enable);
    int (*hdmi_cec_log_addr)(struct drm_bridge *bridge, u8 logical_addr);
    int (*hdmi_cec_transmit)(struct drm_bridge *bridge, u8 attempts, u32 signal_free_time, struct cec_msg *msg);
    int (*dp_audio_startup)(struct drm_bridge *bridge, struct drm_connector *connector);
    int (*dp_audio_prepare)(struct drm_bridge *bridge, struct drm_connector *connector, struct hdmi_codec_daifmt *fmt, struct hdmi_codec_params *hparms);
    void (*dp_audio_shutdown)(struct drm_bridge *bridge, struct drm_connector *connector);
    int (*dp_audio_mute_stream)(struct drm_bridge *bridge, struct drm_connector *connector, bool enable, int direction);
    void (*debugfs_init)(struct drm_bridge *bridge, struct dentry *root);
};
```

**Members**

- `attach`: This callback is invoked whenever our bridge is being attached to a
  [`drm_encoder`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_encoder). The flags argument tunes the behaviour of the attach
  operation (see DRM_BRIDGE_ATTACH_*).

  The **attach** callback is optional.

  RETURNS:

  Zero on success, error code on failure.
- `destroy`: This callback is invoked when the bridge is about to be
  deallocated.

  The **destroy** callback is optional.
- `detach`: This callback is invoked whenever our bridge is being detached from a
  [`drm_encoder`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_encoder).

  The **detach** callback is optional.
- `mode_valid`: This callback is used to check if a specific mode is valid in this
  bridge. This should be implemented if the bridge has some sort of
  restriction in the modes it can display. For example, a given bridge
  may be responsible to set a clock value. If the clock can not
  produce all the values for the available modes then this callback
  can be used to restrict the number of modes to only the ones that
  can be displayed.

  This hook is used by the probe helpers to filter the mode list in
  [`drm_helper_probe_single_connector_modes()`](#c-drm_helper_probe_single_connector_modes), and it is used by the
  atomic helpers to validate modes supplied by userspace in
  [`drm_atomic_helper_check_modeset()`](#c-drm_atomic_helper_check_modeset).

  The **mode_valid** callback is optional.

  NOTE:

  Since this function is both called from the check phase of an atomic
  commit, and the mode validation in the probe paths it is not allowed
  to look at anything else but the passed-in mode, and validate it
  against configuration-invariant hardware constraints. Any further
  limits which depend upon the configuration can only be checked in
  **mode_fixup**.

  RETURNS:

  drm_mode_status Enum
- `mode_fixup`: This callback is used to validate and adjust a mode. The parameter
  mode is the display mode that should be fed to the next element in
  the display chain, either the final [`drm_connector`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_connector) or the next
  [`drm_bridge`](#c-struct-drm_bridge). The parameter adjusted_mode is the input mode the bridge
  requires. It can be modified by this callback and does not need to
  match mode. See also [`drm_crtc_state.adjusted_mode`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_crtc_state) for more details.

  This is the only hook that allows a bridge to reject a modeset. If
  this function passes all other callbacks must succeed for this
  configuration.

  The mode_fixup callback is optional. [`drm_bridge_funcs.mode_fixup()`](#c-struct-drm_bridge_funcs)
  is not called when [`drm_bridge_funcs.atomic_check()`](#c-struct-drm_bridge_funcs) is implemented,
  so only one of them should be provided.

  NOTE:

  This function is called in the check phase of atomic modesets, which
  can be aborted for any reason (including on userspace's request to
  just check whether a configuration would be possible). Drivers MUST
  NOT touch any persistent state (hardware or software) or data
  structures except the passed in **state** parameter.

  Also beware that userspace can request its own custom modes, neither
  core nor helpers filter modes to the list of probe modes reported by
  the GETCONNECTOR IOCTL and stored in [`drm_connector.modes`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_connector). To ensure
  that modes are filtered consistently put any bridge constraints and
  limits checks into **mode_valid**.

  RETURNS:

  True if an acceptable configuration is possible, false if the modeset
  operation should be rejected.
- `disable`: This callback should disable the bridge. It is called right before
  the preceding element in the display pipe is disabled. If the
  preceding element is a bridge this means it's called before that
  bridge's **disable** vfunc. If the preceding element is a [`drm_encoder`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_encoder)
  it's called right before the [`drm_encoder_helper_funcs.disable`](#c-struct-drm_encoder_helper_funcs),
  [`drm_encoder_helper_funcs.prepare`](#c-struct-drm_encoder_helper_funcs) or [`drm_encoder_helper_funcs.dpms`](#c-struct-drm_encoder_helper_funcs)
  hook.

  The bridge can assume that the display pipe (i.e. clocks and timing
  signals) feeding it is still running when this callback is called.

  The **disable** callback is optional.

  NOTE:

  This is deprecated, do not use!
  New drivers shall use [`drm_bridge_funcs.atomic_disable`](#c-struct-drm_bridge_funcs).
- `post_disable`: This callback should disable the bridge. It is called right after the
  preceding element in the display pipe is disabled. If the preceding
  element is a bridge this means it's called after that bridge's
  **post_disable** function. If the preceding element is a [`drm_encoder`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_encoder)
  it's called right after the encoder's
  [`drm_encoder_helper_funcs.disable`](#c-struct-drm_encoder_helper_funcs), [`drm_encoder_helper_funcs.prepare`](#c-struct-drm_encoder_helper_funcs)
  or [`drm_encoder_helper_funcs.dpms`](#c-struct-drm_encoder_helper_funcs) hook.

  The bridge must assume that the display pipe (i.e. clocks and timing
  signals) feeding it is no longer running when this callback is
  called.

  The **post_disable** callback is optional.

  NOTE:

  This is deprecated, do not use!
  New drivers shall use [`drm_bridge_funcs.atomic_post_disable`](#c-struct-drm_bridge_funcs).
- `mode_set`: This callback should set the given mode on the bridge. It is called
  after the **mode_set** callback for the preceding element in the display
  pipeline has been called already. If the bridge is the first element
  then this would be [`drm_encoder_helper_funcs.mode_set`](#c-struct-drm_encoder_helper_funcs). The display
  pipe (i.e.  clocks and timing signals) is off when this function is
  called.

  The adjusted_mode parameter is the mode output by the CRTC for the
  first bridge in the chain. It can be different from the mode
  parameter that contains the desired mode for the connector at the end
  of the bridges chain, for instance when the first bridge in the chain
  performs scaling. The adjusted mode is mostly useful for the first
  bridge in the chain and is likely irrelevant for the other bridges.

  For atomic drivers the adjusted_mode is the mode stored in
  [`drm_crtc_state.adjusted_mode`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_crtc_state).

  NOTE:

  This is deprecated, do not use!
  New drivers shall set their mode in the
  [`drm_bridge_funcs.atomic_enable`](#c-struct-drm_bridge_funcs) operation.
- `pre_enable`: This callback should enable the bridge. It is called right before
  the preceding element in the display pipe is enabled. If the
  preceding element is a bridge this means it's called before that
  bridge's **pre_enable** function. If the preceding element is a
  [`drm_encoder`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_encoder) it's called right before the encoder's
  [`drm_encoder_helper_funcs.enable`](#c-struct-drm_encoder_helper_funcs), [`drm_encoder_helper_funcs.commit`](#c-struct-drm_encoder_helper_funcs) or
  [`drm_encoder_helper_funcs.dpms`](#c-struct-drm_encoder_helper_funcs) hook.

  The display pipe (i.e. clocks and timing signals) feeding this bridge
  will not yet be running when this callback is called. The bridge must
  not enable the display link feeding the next bridge in the chain (if
  there is one) when this callback is called.

  The **pre_enable** callback is optional.

  NOTE:

  This is deprecated, do not use!
  New drivers shall use [`drm_bridge_funcs.atomic_pre_enable`](#c-struct-drm_bridge_funcs).
- `enable`: This callback should enable the bridge. It is called right after
  the preceding element in the display pipe is enabled. If the
  preceding element is a bridge this means it's called after that
  bridge's **enable** function. If the preceding element is a
  [`drm_encoder`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_encoder) it's called right after the encoder's
  [`drm_encoder_helper_funcs.enable`](#c-struct-drm_encoder_helper_funcs), [`drm_encoder_helper_funcs.commit`](#c-struct-drm_encoder_helper_funcs) or
  [`drm_encoder_helper_funcs.dpms`](#c-struct-drm_encoder_helper_funcs) hook.

  The bridge can assume that the display pipe (i.e. clocks and timing
  signals) feeding it is running when this callback is called. This
  callback must enable the display link feeding the next bridge in the
  chain if there is one.

  The **enable** callback is optional.

  NOTE:

  This is deprecated, do not use!
  New drivers shall use [`drm_bridge_funcs.atomic_enable`](#c-struct-drm_bridge_funcs).
- `atomic_pre_enable`: This callback should enable the bridge. It is called right before
  the preceding element in the display pipe is enabled. If the
  preceding element is a bridge this means it's called before that
  bridge's **atomic_pre_enable** or **pre_enable** function. If the preceding
  element is a [`drm_encoder`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_encoder) it's called right before the encoder's
  [`drm_encoder_helper_funcs.atomic_enable`](#c-struct-drm_encoder_helper_funcs) hook.

  The display pipe (i.e. clocks and timing signals) feeding this bridge
  will not yet be running when this callback is called. The bridge must
  not enable the display link feeding the next bridge in the chain (if
  there is one) when this callback is called.

  The **atomic_pre_enable** callback is optional.
- `atomic_enable`: This callback should enable the bridge. It is called right after
  the preceding element in the display pipe is enabled. If the
  preceding element is a bridge this means it's called after that
  bridge's **atomic_enable** or **enable** function. If the preceding element
  is a [`drm_encoder`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_encoder) it's called right after the encoder's
  [`drm_encoder_helper_funcs.atomic_enable`](#c-struct-drm_encoder_helper_funcs) hook.

  The bridge can assume that the display pipe (i.e. clocks and timing
  signals) feeding it is running when this callback is called. This
  callback must enable the display link feeding the next bridge in the
  chain if there is one.

  The **atomic_enable** callback is optional.
- `atomic_disable`: This callback should disable the bridge. It is called right before
  the preceding element in the display pipe is disabled. If the
  preceding element is a bridge this means it's called before that
  bridge's **atomic_disable** or **disable** vfunc. If the preceding element
  is a [`drm_encoder`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_encoder) it's called right before the
  [`drm_encoder_helper_funcs.atomic_disable`](#c-struct-drm_encoder_helper_funcs) hook.

  The bridge can assume that the display pipe (i.e. clocks and timing
  signals) feeding it is still running when this callback is called.

  The **atomic_disable** callback is optional.
- `atomic_post_disable`: This callback should disable the bridge. It is called right after the
  preceding element in the display pipe is disabled. If the preceding
  element is a bridge this means it's called after that bridge's
  **atomic_post_disable** or **post_disable** function. If the preceding
  element is a [`drm_encoder`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_encoder) it's called right after the encoder's
  [`drm_encoder_helper_funcs.atomic_disable`](#c-struct-drm_encoder_helper_funcs) hook.

  The bridge must assume that the display pipe (i.e. clocks and timing
  signals) feeding it is no longer running when this callback is
  called.

  The **atomic_post_disable** callback is optional.
- `atomic_duplicate_state`: Duplicate the current bridge state object (which is guaranteed to be
  non-NULL).

  The atomic_duplicate_state hook is mandatory if the bridge
  implements any of the atomic hooks, and should be left unassigned
  otherwise. For bridges that don't subclass [`drm_bridge_state`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_bridge_state), the
  [`drm_atomic_helper_bridge_duplicate_state()`](#c-drm_atomic_helper_bridge_duplicate_state) helper function shall be
  used to implement this hook.

  RETURNS:
  A valid drm_bridge_state object or NULL if the allocation fails.
- `atomic_destroy_state`: Destroy a bridge state object previously allocated by
  [`drm_bridge_funcs.atomic_duplicate_state()`](#c-struct-drm_bridge_funcs).

  The atomic_destroy_state hook is mandatory if the bridge implements
  any of the atomic hooks, and should be left unassigned otherwise.
  For bridges that don't subclass [`drm_bridge_state`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_bridge_state), the
  [`drm_atomic_helper_bridge_destroy_state()`](#c-drm_atomic_helper_bridge_destroy_state) helper function shall be
  used to implement this hook.
- `atomic_get_output_bus_fmts`: Return the supported bus formats on the output end of a bridge.
  The returned array must be allocated with [`kmalloc()`](/kernel/internals/core-api/mm-api.md#c-kmalloc) and will be
  freed by the caller. If the allocation fails, NULL should be
  returned. num_output_fmts must be set to the returned array size.
  Formats listed in the returned array should be listed in decreasing
  preference order (the core will try all formats until it finds one
  that works).

  This method is only called on the last element of the bridge chain
  as part of the bus format negotiation process that happens in
  `drm_atomic_bridge_chain_select_bus_fmts`().
  This method is optional. When not implemented, the core will
  fall back to [`drm_connector.display_info`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_connector).bus_formats\[0\] if
  [`drm_connector.display_info`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_connector).num_bus_formats > 0,
  or to MEDIA_BUS_FMT_FIXED otherwise.
- `atomic_get_input_bus_fmts`: Return the supported bus formats on the input end of a bridge for
  a specific output bus format.

  The returned array must be allocated with [`kmalloc()`](/kernel/internals/core-api/mm-api.md#c-kmalloc) and will be
  freed by the caller. If the allocation fails, NULL should be
  returned. num_input_fmts must be set to the returned array size.
  Formats listed in the returned array should be listed in decreasing
  preference order (the core will try all formats until it finds one
  that works). When the format is not supported NULL should be
  returned and num_input_fmts should be set to 0.

  This method is called on all elements of the bridge chain as part of
  the bus format negotiation process that happens in
  `drm_atomic_bridge_chain_select_bus_fmts()`.
  This method is optional. When not implemented, the core will bypass
  bus format negotiation on this element of the bridge without
  failing, and the previous element in the chain will be passed
  MEDIA_BUS_FMT_FIXED as its output bus format.

  Bridge drivers that need to support being linked to bridges that are
  not supporting bus format negotiation should handle the
  output_fmt == MEDIA_BUS_FMT_FIXED case appropriately, by selecting a
  sensible default value or extracting this information from somewhere
  else (FW property, [`drm_display_mode`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_display_mode), [`drm_display_info`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_display_info), ...)

  Note: Even if input format selection on the first bridge has no
  impact on the negotiation process (bus format negotiation stops once
  we reach the first element of the chain), drivers are expected to
  return accurate input formats as the input format may be used to
  configure the CRTC output appropriately.
- `atomic_check`: This method is responsible for checking bridge state correctness.
  It can also check the state of the surrounding components in chain
  to make sure the whole pipeline can work properly.

  [`drm_bridge_funcs.atomic_check()`](#c-struct-drm_bridge_funcs) hooks are called in reverse
  order (from the last to the first bridge).

  This method is optional. [`drm_bridge_funcs.mode_fixup()`](#c-struct-drm_bridge_funcs) is not
  called when [`drm_bridge_funcs.atomic_check()`](#c-struct-drm_bridge_funcs) is implemented, so only
  one of them should be provided.

  If drivers need to tweak [`drm_bridge_state.input_bus_cfg`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_bridge_state).flags or
  [`drm_bridge_state.output_bus_cfg`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_bridge_state).flags it should happen in
  this function. By default the [`drm_bridge_state.output_bus_cfg`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_bridge_state).flags
  field is set to the next bridge
  [`drm_bridge_state.input_bus_cfg`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_bridge_state).flags value or
  [`drm_connector.display_info`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_connector).bus_flags if the bridge is the last
  element in the chain.

  RETURNS:
  zero if the check passed, a negative error code otherwise.
- `atomic_reset`: Reset the bridge to a predefined state (or retrieve its current
  state) and return a [`drm_bridge_state`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_bridge_state) object matching this state.
  This function is called at attach time.

  The atomic_reset hook is mandatory if the bridge implements any of
  the atomic hooks, and should be left unassigned otherwise. For
  bridges that don't subclass [`drm_bridge_state`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_bridge_state), the
  [`drm_atomic_helper_bridge_reset()`](#c-drm_atomic_helper_bridge_reset) helper function shall be used to
  implement this hook.

  Note that the `atomic_reset()` semantics is not exactly matching the
  `reset()` semantics found on other components (connector, plane, ...).

  1. The reset operation happens when the bridge is attached, not when
     [`drm_mode_config_reset()`](/kernel/hardware/gpu/drm-kms.md#c-drm_mode_config_reset) is called
  2. It's meant to be used exclusively on bridges that have been
     converted to the ATOMIC API

  RETURNS:
  A valid drm_bridge_state object in case of success, an [`ERR_PTR()`](/kernel/internals/core-api/kernel-api.md#c-ERR_PTR)
  giving the reason of the failure otherwise.
- `detect`: Check if anything is attached to the bridge output.

  This callback is optional, if not implemented the bridge will be
  considered as always having a component attached to its output.
  Bridges that implement this callback shall set the
  DRM_BRIDGE_OP_DETECT flag in their [`drm_bridge->ops`](#c-struct-drm_bridge).

  RETURNS:

  drm_connector_status indicating the bridge output status.
- `get_modes`: Fill all modes currently valid for the sink into the [`drm_connector`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_connector)
  with [`drm_mode_probed_add()`](/kernel/hardware/gpu/drm-kms.md#c-drm_mode_probed_add).

  The **get_modes** callback is mostly intended to support non-probeable
  displays such as many fixed panels. Bridges that support reading
  EDID shall leave **get_modes** unimplemented and implement the
  [`drm_bridge_funcs->edid_read`](#c-struct-drm_bridge_funcs) callback instead.

  This callback is optional. Bridges that implement it shall set the
  DRM_BRIDGE_OP_MODES flag in their [`drm_bridge->ops`](#c-struct-drm_bridge).

  The connector parameter shall be used for the sole purpose of
  filling modes, and shall not be stored internally by bridge drivers
  for future usage.

  RETURNS:

  The number of modes added by calling [`drm_mode_probed_add()`](/kernel/hardware/gpu/drm-kms.md#c-drm_mode_probed_add).
- `edid_read`: Read the EDID data of the connected display.

  The **edid_read** callback is the preferred way of reporting mode
  information for a display connected to the bridge output. Bridges
  that support reading EDID shall implement this callback and leave
  the **get_modes** callback unimplemented.

  The caller of this operation shall first verify the output
  connection status and refrain from reading EDID from a disconnected
  output.

  This callback is optional. Bridges that implement it shall set the
  DRM_BRIDGE_OP_EDID flag in their [`drm_bridge->ops`](#c-struct-drm_bridge).

  The connector parameter shall be used for the sole purpose of EDID
  retrieval, and shall not be stored internally by bridge drivers for
  future usage.

  RETURNS:

  An edid structure newly allocated with [`drm_edid_alloc()`](#c-drm_edid_alloc) or returned
  from [`drm_edid_read()`](#c-drm_edid_read) family of functions on success, or NULL
  otherwise. The caller is responsible for freeing the returned edid
  structure with [`drm_edid_free()`](#c-drm_edid_free).
- `hpd_notify`: Notify the bridge of hot plug detection.

  This callback is optional, it may be implemented by bridges that
  need to be notified of display connection or disconnection for
  internal reasons. One use case is to reset the internal state of CEC
  controllers for HDMI bridges.
- `hpd_enable`: Enable hot plug detection. From now on the bridge shall call
  [`drm_bridge_hpd_notify()`](#c-drm_bridge_hpd_notify) each time a change is detected in the output
  connection status, until hot plug detection gets disabled with
  **hpd_disable**.

  This callback is optional and shall only be implemented by bridges
  that support hot-plug notification without polling. Bridges that
  implement it shall also implement the **hpd_disable** callback and set
  the DRM_BRIDGE_OP_HPD flag in their [`drm_bridge->ops`](#c-struct-drm_bridge).
- `hpd_disable`: Disable hot plug detection. Once this function returns the bridge
  shall not call [`drm_bridge_hpd_notify()`](#c-drm_bridge_hpd_notify) when a change in the output
  connection status occurs.

  This callback is optional and shall only be implemented by bridges
  that support hot-plug notification without polling. Bridges that
  implement it shall also implement the **hpd_enable** callback and set
  the DRM_BRIDGE_OP_HPD flag in their [`drm_bridge->ops`](#c-struct-drm_bridge).
- `hdmi_tmds_char_rate_valid`: Check whether a particular TMDS character rate is supported by the
  driver.

  This callback is optional and should only be implemented by the
  bridges that take part in the HDMI connector implementation. Bridges
  that implement it shall set the DRM_BRIDGE_OP_HDMI flag in their
  [`drm_bridge->ops`](#c-struct-drm_bridge).

  Returns:

  Either [`drm_mode_status.MODE_OK`](/kernel/hardware/gpu/drm-kms.md#c-enum-drm_mode_status) or one of the failure reasons
  in [`enum drm_mode_status`](/kernel/hardware/gpu/drm-kms.md#c-enum-drm_mode_status).
- `hdmi_clear_avi_infoframe`: This callback clears the infoframes in the hardware during commit.

  This callback is optional but it must be implemented by bridges that
  set the DRM_BRIDGE_OP_HDMI flag in their [`drm_bridge->ops`](#c-struct-drm_bridge).
- `hdmi_write_avi_infoframe`: Program the infoframe into the hardware.

  This callback is optional but it must be implemented by bridges that
  set the DRM_BRIDGE_OP_HDMI flag in their [`drm_bridge->ops`](#c-struct-drm_bridge).
- `hdmi_clear_hdmi_infoframe`: This callback clears the infoframes in the hardware during commit.

  This callback is optional but it must be implemented by bridges that
  set the DRM_BRIDGE_OP_HDMI flag in their [`drm_bridge->ops`](#c-struct-drm_bridge).
- `hdmi_write_hdmi_infoframe`: Program the infoframe into the hardware.

  This callback is optional but it must be implemented by bridges that
  set the DRM_BRIDGE_OP_HDMI flag in their [`drm_bridge->ops`](#c-struct-drm_bridge).
- `hdmi_clear_hdr_drm_infoframe`: This callback clears the infoframes in the hardware during commit.

  This callback is optional but it must be implemented by bridges that
  set the DRM_BRIDGE_OP_HDMI_HDR_DRM_INFOFRAME flag in their
  [`drm_bridge->ops`](#c-struct-drm_bridge).
- `hdmi_write_hdr_drm_infoframe`: Program the infoframe into the hardware.

  This callback is optional but it must be implemented by bridges that
  set the DRM_BRIDGE_OP_HDMI_HDR_DRM_INFOFRAME flag in their
  [`drm_bridge->ops`](#c-struct-drm_bridge).
- `hdmi_clear_spd_infoframe`: This callback clears the infoframes in the hardware during commit.

  This callback is optional but it must be implemented by bridges that
  set the DRM_BRIDGE_OP_HDMI_SPD_INFOFRAME flag in their
  [`drm_bridge->ops`](#c-struct-drm_bridge).
- `hdmi_write_spd_infoframe`: Program the infoframe into the hardware.

  This callback is optional but it must be implemented by bridges that
  set the DRM_BRIDGE_OP_HDMI_SPD_INFOFRAME flag in their
  [`drm_bridge->ops`](#c-struct-drm_bridge).
- `hdmi_clear_audio_infoframe`: This callback clears the infoframes in the hardware during commit.

  This callback is optional but it must be implemented by bridges that
  set the DRM_BRIDGE_OP_HDMI_AUDIO flag in their [`drm_bridge->ops`](#c-struct-drm_bridge).
- `hdmi_write_audio_infoframe`: Program the infoframe into the hardware.

  This callback is optional but it must be implemented by bridges that
  set the DRM_BRIDGE_OP_HDMI_AUDIO flag in their [`drm_bridge->ops`](#c-struct-drm_bridge).
- `hdmi_audio_startup`: Called when ASoC starts an audio stream setup.

  This callback is optional, it can be implemented by bridges that
  set the **DRM_BRIDGE_OP_HDMI_AUDIO** flag in their [`drm_bridge->ops`](#c-struct-drm_bridge).

  Returns:
  0 on success, a negative error code otherwise
- `hdmi_audio_prepare`: Configures HDMI-encoder for audio stream. Can be called multiple
  times for each setup.

  This callback is optional but it must be implemented by bridges that
  set the **DRM_BRIDGE_OP_HDMI_AUDIO** flag in their [`drm_bridge->ops`](#c-struct-drm_bridge).

  Returns:
  0 on success, a negative error code otherwise
- `hdmi_audio_shutdown`: Shut down the audio stream.

  This callback is optional but it must be implemented by bridges that
  set the **DRM_BRIDGE_OP_HDMI_AUDIO** flag in their [`drm_bridge->ops`](#c-struct-drm_bridge).

  Returns:
  0 on success, a negative error code otherwise
- `hdmi_audio_mute_stream`: Mute/unmute HDMI audio stream.

  This callback is optional, it can be implemented by bridges that
  set the **DRM_BRIDGE_OP_HDMI_AUDIO** flag in their [`drm_bridge->ops`](#c-struct-drm_bridge).

  Returns:
  0 on success, a negative error code otherwise
- `hdmi_cec_init`: Initialize CEC part of the bridge.

  This callback is optional, it can be implemented by bridges that
  set the **DRM_BRIDGE_OP_HDMI_CEC_ADAPTER** flag in their
  [`drm_bridge->ops`](#c-struct-drm_bridge).

  Returns:
  0 on success, a negative error code otherwise
- `hdmi_cec_enable`: Enable or disable the CEC adapter inside the bridge.

  This callback is optional, it can be implemented by bridges that
  set the **DRM_BRIDGE_OP_HDMI_CEC_ADAPTER** flag in their
  [`drm_bridge->ops`](#c-struct-drm_bridge).

  Returns:
  0 on success, a negative error code otherwise
- `hdmi_cec_log_addr`: Set the logical address of the CEC adapter inside the bridge.

  This callback is optional, it can be implemented by bridges that
  set the **DRM_BRIDGE_OP_HDMI_CEC_ADAPTER** flag in their
  [`drm_bridge->ops`](#c-struct-drm_bridge).

  Returns:
  0 on success, a negative error code otherwise
- `hdmi_cec_transmit`: Transmit the message using the CEC adapter inside the bridge.

  This callback is optional, it can be implemented by bridges that
  set the **DRM_BRIDGE_OP_HDMI_CEC_ADAPTER** flag in their
  [`drm_bridge->ops`](#c-struct-drm_bridge).

  Returns:
  0 on success, a negative error code otherwise
- `dp_audio_startup`: Called when ASoC starts a DisplayPort audio stream setup.

  This callback is optional, it can be implemented by bridges that
  set the **DRM_BRIDGE_OP_DP_AUDIO** flag in their [`drm_bridge->ops`](#c-struct-drm_bridge).

  Returns:
  0 on success, a negative error code otherwise
- `dp_audio_prepare`: Configures DisplayPort audio stream. Can be called multiple
  times for each setup.

  This callback is optional but it must be implemented by bridges that
  set the **DRM_BRIDGE_OP_DP_AUDIO** flag in their [`drm_bridge->ops`](#c-struct-drm_bridge).

  Returns:
  0 on success, a negative error code otherwise
- `dp_audio_shutdown`: Shut down the DisplayPort audio stream.

  This callback is optional but it must be implemented by bridges that
  set the **DRM_BRIDGE_OP_DP_AUDIO** flag in their [`drm_bridge->ops`](#c-struct-drm_bridge).

  Returns:
  0 on success, a negative error code otherwise
- `dp_audio_mute_stream`: Mute/unmute DisplayPort audio stream.

  This callback is optional, it can be implemented by bridges that
  set the **DRM_BRIDGE_OP_DP_AUDIO** flag in their [`drm_bridge->ops`](#c-struct-drm_bridge).

  Returns:
  0 on success, a negative error code otherwise
- `debugfs_init`: Allows bridges to create bridge-specific debugfs files.

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

timing information for the bridge

**Definition**

```c
struct drm_bridge_timings {
    u32 input_bus_flags;
    u32 setup_time_ps;
    u32 hold_time_ps;
    bool dual_link;
};
```

**Members**

- `input_bus_flags`: Tells what additional settings for the pixel data on the bus
  this bridge requires (like pixel signal polarity). See also
  [`drm_display_info->bus_flags`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_display_info).
- `setup_time_ps`: Defines the time in picoseconds the input data lines must be
  stable before the clock edge.
- `hold_time_ps`: Defines the time in picoseconds taken for the bridge to sample the
  input signal after the clock edge.
- `dual_link`: True if the bus operates in dual-link mode. The exact meaning is
  dependent on the bus type. For LVDS buses, this indicates that even-
  and odd-numbered pixels are received on separate links.

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

Bitmask of operations supported by the bridge

**Constants**

- `DRM_BRIDGE_OP_DETECT`: The bridge can detect displays connected to
  its output. Bridges that set this flag shall implement the
  [`drm_bridge_funcs->detect`](#c-struct-drm_bridge_funcs) callback.
- `DRM_BRIDGE_OP_EDID`: The bridge can retrieve the EDID of the display
  connected to its output. Bridges that set this flag shall implement
  the [`drm_bridge_funcs->edid_read`](#c-struct-drm_bridge_funcs) callback.
- `DRM_BRIDGE_OP_HPD`: The bridge can detect hot-plug and hot-unplug
  without requiring polling. Bridges that set this flag shall
  implement the [`drm_bridge_funcs->hpd_enable`](#c-struct-drm_bridge_funcs) and
  [`drm_bridge_funcs->hpd_disable`](#c-struct-drm_bridge_funcs) callbacks if they support enabling
  and disabling hot-plug detection dynamically.
- `DRM_BRIDGE_OP_MODES`: The bridge can retrieve the modes supported
  by the display at its output. This does not include reading EDID
  which is separately covered by **DRM_BRIDGE_OP_EDID**. Bridges that set
  this flag shall implement the [`drm_bridge_funcs->get_modes`](#c-struct-drm_bridge_funcs) callback.
- `DRM_BRIDGE_OP_HDMI`: The bridge provides HDMI connector operations,
  including infoframes support. Bridges that set this flag must
  provide HDMI-related information and implement the
  [`drm_bridge_funcs->clear_avi_infoframe`](#c-struct-drm_bridge_funcs),
  [`drm_bridge_funcs->write_avi_infoframe`](#c-struct-drm_bridge_funcs),
  [`drm_bridge_funcs->clear_hdmi_infoframe`](#c-struct-drm_bridge_funcs) and
  [`drm_bridge_funcs->write_hdmi_infoframe`](#c-struct-drm_bridge_funcs) callbacks.

  Note: currently there can be at most one bridge in a chain that sets
  this bit. This is to simplify corresponding glue code in connector
  drivers.
- `DRM_BRIDGE_OP_HDMI_AUDIO`: The bridge provides HDMI audio operations.
  Bridges that set this flag must implement the
  [`drm_bridge_funcs->hdmi_audio_prepare`](#c-struct-drm_bridge_funcs) and
  [`drm_bridge_funcs->hdmi_audio_shutdown`](#c-struct-drm_bridge_funcs) callbacks.
  If the bridge implements **DRM_BRIDGE_OP_HDMI**, it also must implement
  [`drm_bridge_funcs->hdmi_write_audio_infoframe`](#c-struct-drm_bridge_funcs) and
  [`drm_bridge_funcs->hdmi_cleaer_audio_infoframe`](#c-struct-drm_bridge_funcs) callbacks.

  Note: currently there can be at most one bridge in a chain that sets
  this bit. This is to simplify corresponding glue code in connector
  drivers. Also it is not possible to have a bridge in the chain that
  sets **DRM_BRIDGE_OP_DP_AUDIO** if there is a bridge that sets this
  flag.
- `DRM_BRIDGE_OP_DP_AUDIO`: The bridge provides DisplayPort audio operations.
  Bridges that set this flag must implement the
  [`drm_bridge_funcs->dp_audio_prepare`](#c-struct-drm_bridge_funcs) and
  [`drm_bridge_funcs->dp_audio_shutdown`](#c-struct-drm_bridge_funcs) callbacks.

  Note: currently there can be at most one bridge in a chain that sets
  this bit. This is to simplify corresponding glue code in connector
  drivers. Also it is not possible to have a bridge in the chain that
  sets **DRM_BRIDGE_OP_HDMI_AUDIO** if there is a bridge that sets this
  flag.
- `DRM_BRIDGE_OP_HDMI_CEC_NOTIFIER`: The bridge requires CEC notifier
  to be present.
- `DRM_BRIDGE_OP_HDMI_CEC_ADAPTER`: The bridge requires CEC adapter
  to be present.
- `DRM_BRIDGE_OP_HDMI_HDR_DRM_INFOFRAME`: The bridge supports
  [`drm_bridge_funcs->hdmi_write_hdr_drm_infoframe`](#c-struct-drm_bridge_funcs) and
  [`drm_bridge_funcs->hdmi_clear_hdr_drm_infoframe`](#c-struct-drm_bridge_funcs) callbacks.
- `DRM_BRIDGE_OP_HDMI_SPD_INFOFRAME`: The bridge supports
  [`drm_bridge_funcs->hdmi_write_spd_infoframe`](#c-struct-drm_bridge_funcs) and
  [`drm_bridge_funcs->hdmi_clear_spd_infoframe`](#c-struct-drm_bridge_funcs) callbacks.

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

central DRM bridge control structure

**Definition**

```c
struct drm_bridge {
    struct drm_private_obj base;
    struct drm_device *dev;
    struct drm_encoder *encoder;
    struct list_head chain_node;
    struct device_node *of_node;
    struct list_head list;
    const struct drm_bridge_timings *timings;
    const struct drm_bridge_funcs *funcs;
    void *container;
    struct kref refcount;
    bool unplugged;
    void *driver_private;
    enum drm_bridge_ops ops;
    int type;
    bool interlace_allowed;
    bool ycbcr_420_allowed;
    bool pre_enable_prev_first;
    bool support_hdcp;
    struct i2c_adapter *ddc;
    const char *vendor;
    const char *product;
    unsigned int supported_formats;
    unsigned int max_bpc;
    struct device *hdmi_cec_dev;
    struct device *hdmi_audio_dev;
    int hdmi_audio_max_i2s_playback_channels;
    u64 hdmi_audio_i2s_formats;
    unsigned int hdmi_audio_spdif_playback : 1;
    int hdmi_audio_dai_port;
    const char *hdmi_cec_adapter_name;
    u8 hdmi_cec_available_las;
    struct mutex hpd_mutex;
    void (*hpd_cb)(void *data, enum drm_connector_status status);
    void *hpd_data;
    struct drm_bridge *next_bridge;
};
```

**Members**

- `base`: inherit from `drm_private_object`
- `dev`: DRM device this bridge belongs to
- `encoder`: encoder to which this bridge is connected
- `chain_node`: used to form a bridge chain
- `of_node`: device node pointer to the bridge
- `list`: to keep track of all added bridges
- `timings`: the timing specification for the bridge, if any (may be NULL)
- `funcs`: control functions
- `container`: Pointer to the private driver struct embedding this
  **struct** drm_bridge.
- `refcount`: reference count of users referencing this bridge.
- `unplugged`: Flag to tell if the bridge has been unplugged.
  See [`drm_bridge_enter()`](#c-drm_bridge_enter) and [`drm_bridge_unplug()`](#c-drm_bridge_unplug).
- `driver_private`: pointer to the bridge driver's internal context
- `ops`: bitmask of operations supported by the bridge
- `type`: Type of the connection at the bridge output
  (DRM_MODE_CONNECTOR_*). For bridges at the end of this chain this
  identifies the type of connected display.
- `interlace_allowed`: Indicate that the bridge can handle interlaced
  modes.
- `ycbcr_420_allowed`: Indicate that the bridge can handle YCbCr 420
  output.
- `pre_enable_prev_first`: The bridge requires that the prev
  bridge **pre_enable** function is called before its **pre_enable**,
  and conversely for post_disable. This is most frequently a
  requirement for DSI devices which need the host to be initialised
  before the peripheral.
- `support_hdcp`: Indicate that the bridge supports HDCP.
- `ddc`: Associated I2C adapter for DDC access, if any.
- `vendor`: Vendor of the product to be used for the SPD InfoFrame
  generation. This is required if **DRM_BRIDGE_OP_HDMI** is set.
- `product`: Name of the product to be used for the SPD InfoFrame
  generation. This is required if **DRM_BRIDGE_OP_HDMI** is set.
- `supported_formats`: Bitmask of **hdmi_colorspace** listing supported
  output formats. This is only relevant if **DRM_BRIDGE_OP_HDMI** is set.
- `max_bpc`: Maximum bits per char the HDMI bridge supports. Allowed
  values are 8, 10 and 12. This is only relevant if
  **DRM_BRIDGE_OP_HDMI** is set.
- `hdmi_cec_dev`: device to be used as a containing device for CEC
  functions.
- `hdmi_audio_dev`: device to be used as a parent for the HDMI Codec if
  either of **DRM_BRIDGE_OP_HDMI_AUDIO** or **DRM_BRIDGE_OP_DP_AUDIO** is set.
- `hdmi_audio_max_i2s_playback_channels`: maximum number of playback
  I2S channels for the **DRM_BRIDGE_OP_HDMI_AUDIO** or
  **DRM_BRIDGE_OP_DP_AUDIO**.
- `hdmi_audio_i2s_formats`: supported I2S formats, optional. The
  default is to allow all formats supported by the corresponding I2S
  bus driver. This is only used for bridges setting
  **DRM_BRIDGE_OP_HDMI_AUDIO** or **DRM_BRIDGE_OP_DP_AUDIO**.
- `hdmi_audio_spdif_playback`: set if this bridge has S/PDIF playback
  port for **DRM_BRIDGE_OP_HDMI_AUDIO** or **DRM_BRIDGE_OP_DP_AUDIO**.
- `hdmi_audio_dai_port`: sound DAI port for either of
  **DRM_BRIDGE_OP_HDMI_AUDIO** and **DRM_BRIDGE_OP_DP_AUDIO**, -1 if it is
  not used.
- `hdmi_cec_adapter_name`: the name of the adapter to register
- `hdmi_cec_available_las`: number of logical addresses, CEC_MAX_LOG_ADDRS if unset
- `hpd_mutex`: Protects the **hpd_cb** and **hpd_data** fields.
- `hpd_cb`: Hot plug detection callback, registered with
  [`drm_bridge_hpd_enable()`](#c-drm_bridge_hpd_enable).
- `hpd_data`: Private data passed to the Hot plug detection callback
  **hpd_cb**.
- `next_bridge`: Pointer to the following bridge, automatically put
  when this bridge is freed (i.e. at destroy time). This is for
  drivers needing to store a pointer to the next bridge in the
  chain, and ensures any code still holding a reference to this
  bridge after its removal cannot use-after-free the next
  bridge. Any other bridge pointers stored by the driver must be
  put in the .destroy callback by driver code.

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

```c
devm_drm_bridge_alloc(dev, type, member, funcs)
```

Allocate and initialize a bridge

**Parameters**

- `dev`: struct device of the bridge device
- `type`: the type of the struct which contains struct [`drm_bridge`](#c-struct-drm_bridge)
- `member`: the name of the [`drm_bridge`](#c-struct-drm_bridge) within **type**
- `funcs`: callbacks for this bridge

**Description**

The reference count of the returned bridge is initialized to 1. This
reference will be automatically dropped via devm (by calling
[`drm_bridge_put()`](#c-drm_bridge_put)) when **dev** is removed.

**Return**

Pointer to new bridge, or ERR_PTR on failure.

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

```c
struct drm_bridge_state * drm_bridge_get_current_state(struct drm_bridge *bridge)
```

Get the current bridge state

**Parameters**

- `struct drm_bridge *bridge`: bridge object

**Description**

This function must be called with the modeset lock held.

The current bridge state, or NULL if there is none.

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

```c
struct drm_bridge * drm_bridge_get_next_bridge(struct drm_bridge *bridge)
```

Get the next bridge in the chain

**Parameters**

- `struct drm_bridge *bridge`: bridge object

**Description**

The caller is responsible of having a reference to **bridge** via
[`drm_bridge_get()`](#c-drm_bridge_get) or equivalent. This function leaves the refcount of
**bridge** unmodified.

The refcount of the returned bridge is incremented. Use [`drm_bridge_put()`](#c-drm_bridge_put)
when done with it.

**Return**

the next bridge in the chain after **bridge**, or NULL if **bridge** is the last.

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

```c
struct drm_bridge * drm_bridge_get_prev_bridge(struct drm_bridge *bridge)
```

Get the previous bridge in the chain

**Parameters**

- `struct drm_bridge *bridge`: bridge object

**Description**

The caller is responsible of having a reference to **bridge** via
[`drm_bridge_get()`](#c-drm_bridge_get) or equivalent. This function leaves the refcount of
**bridge** unmodified.

The refcount of the returned bridge is incremented. Use [`drm_bridge_put()`](#c-drm_bridge_put)
when done with it.

**Return**

the previous bridge in the chain, or NULL if **bridge** is the first.

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

```c
struct drm_bridge * drm_bridge_chain_get_first_bridge(struct drm_encoder *encoder)
```

Get the first bridge in the chain

**Parameters**

- `struct drm_encoder *encoder`: encoder object

**Description**

The refcount of the returned bridge is incremented. Use [`drm_bridge_put()`](#c-drm_bridge_put)
when done with it.

**Return**

the first bridge in the chain, or NULL if **encoder** has no bridge attached
to it.

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

```c
struct drm_bridge * drm_bridge_chain_get_last_bridge(struct drm_encoder *encoder)
```

Get the last bridge in the chain

**Parameters**

- `struct drm_encoder *encoder`: encoder object

**Description**

The refcount of the returned bridge is incremented. Use [`drm_bridge_put()`](#c-drm_bridge_put)
when done with it.

**Return**

the last bridge in the chain, or NULL if **encoder** has no bridge attached
to it.

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

```c
struct drm_bridge * drm_bridge_get_next_bridge_and_put(struct drm_bridge *bridge)
```

Get the next bridge in the chain and put the previous

**Parameters**

- `struct drm_bridge *bridge`: bridge object

**Description**

Same as [`drm_bridge_get_next_bridge()`](#c-drm_bridge_get_next_bridge) but additionally puts the **bridge**.

**Return**

the next bridge in the chain after **bridge**, or NULL if **bridge** is the last.

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

```c
drm_for_each_bridge_in_chain_scoped(encoder, bridge)
```

iterate over all bridges attached to an encoder

**Parameters**

- `encoder`: the encoder to iterate bridges on
- `bridge`: a bridge pointer updated to point to the current bridge at each
  iteration

**Description**

Iterate over all bridges present in the bridge chain attached to **encoder**.

Automatically gets/puts the bridge reference while iterating, and puts
the reference even if returning or breaking in the middle of the loop.

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

```c
drm_for_each_bridge_in_chain_from(first_bridge, bridge)
```

iterate over all bridges starting from the given bridge

**Parameters**

- `first_bridge`: the bridge to start from
- `bridge`: a bridge pointer updated to point to the current bridge at each
  iteration

**Description**

Iterate over all bridges in the encoder chain starting from
**first_bridge**, included.

Automatically gets/puts the bridge reference while iterating, and puts
the reference even if returning or breaking in the middle of the loop.



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

```c
bool drm_bridge_enter(struct drm_bridge *bridge, int *idx)
```

Enter DRM bridge critical section

**Parameters**

- `struct drm_bridge *bridge`: DRM bridge
- `int *idx`: Pointer to index that will be passed to the matching [`drm_bridge_exit()`](#c-drm_bridge_exit)

**Description**

This function marks and protects the beginning of a section that should not
be entered after the bridge has been unplugged. The section end is marked
with [`drm_bridge_exit()`](#c-drm_bridge_exit). Calls to this function can be nested.

**Return**

True if it is OK to enter the section, false otherwise.

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

```c
void drm_bridge_exit(int idx)
```

Exit DRM bridge critical section

**Parameters**

- `int idx`: index returned by [`drm_bridge_enter()`](#c-drm_bridge_enter)

**Description**

This function marks the end of a section that should not be entered after
the bridge has been unplugged.

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

```c
void drm_bridge_unplug(struct drm_bridge *bridge)
```

declare a DRM bridge was unplugged and remove it

**Parameters**

- `struct drm_bridge *bridge`: DRM bridge

**Description**

This tells the bridge has been physically unplugged and no operations on
device resources must be done anymore. Entry-points can use
[`drm_bridge_enter()`](#c-drm_bridge_enter) and [`drm_bridge_exit()`](#c-drm_bridge_exit) to protect device resources in
a race free manner.

Also unregisters the bridge.

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

```c
struct drm_bridge * drm_bridge_get(struct drm_bridge *bridge)
```

Acquire a bridge reference

**Parameters**

- `struct drm_bridge *bridge`: DRM bridge

**Description**

This function increments the bridge's refcount.

**Return**

Pointer to **bridge**.

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

```c
void drm_bridge_put(struct drm_bridge *bridge)
```

Release a bridge reference

**Parameters**

- `struct drm_bridge *bridge`: DRM bridge

**Description**

This function decrements the bridge's reference count and frees the
object if the reference count drops to zero.

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

```c
void drm_bridge_add(struct drm_bridge *bridge)
```

register a bridge

**Parameters**

- `struct drm_bridge *bridge`: bridge control structure

**Description**

Add the given bridge to the global list of bridges, where they can be
found by users via [`of_drm_find_and_get_bridge()`](#c-of_drm_find_and_get_bridge).

The bridge to be added must have been allocated by
[`devm_drm_bridge_alloc()`](#c-devm_drm_bridge_alloc).

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

```c
int devm_drm_bridge_add(struct device *dev, struct drm_bridge *bridge)
```

devm managed version of [`drm_bridge_add()`](#c-drm_bridge_add)

**Parameters**

- `struct device *dev`: device to tie the bridge lifetime to
- `struct drm_bridge *bridge`: bridge control structure

**Description**

This is the managed version of [`drm_bridge_add()`](#c-drm_bridge_add) which automatically
calls [`drm_bridge_remove()`](#c-drm_bridge_remove) when **dev** is unbound.

**Return**

0 if no error or negative error code.

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

```c
void drm_bridge_remove(struct drm_bridge *bridge)
```

unregister a bridge

**Parameters**

- `struct drm_bridge *bridge`: bridge control structure

**Description**

Remove the given bridge from the global list of registered bridges, so
it won't be found by users via [`of_drm_find_and_get_bridge()`](#c-of_drm_find_and_get_bridge), and add it
to the lingering bridge list, to keep track of it until its allocated
memory is eventually freed.

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

```c
int drm_bridge_attach(struct drm_encoder *encoder, struct drm_bridge *bridge, struct drm_bridge *previous, enum drm_bridge_attach_flags flags)
```

attach the bridge to an encoder's chain

**Parameters**

- `struct drm_encoder *encoder`: DRM encoder
- `struct drm_bridge *bridge`: bridge to attach
- `struct drm_bridge *previous`: previous bridge in the chain (optional)
- `enum drm_bridge_attach_flags flags`: DRM_BRIDGE_ATTACH_* flags

**Description**

Called by a kms driver to link the bridge to an encoder's chain. The previous
argument specifies the previous bridge in the chain. If NULL, the bridge is
linked directly at the encoder's output. Otherwise it is linked at the
previous bridge's output.

If non-NULL the previous bridge must be already attached by a call to this
function.

The bridge to be attached must have been previously added by
[`drm_bridge_add()`](#c-drm_bridge_add).

Note that bridges attached to encoders are auto-detached during encoder
cleanup in [`drm_encoder_cleanup()`](/kernel/hardware/gpu/drm-kms.md#c-drm_encoder_cleanup), so [`drm_bridge_attach()`](#c-drm_bridge_attach) should generally
*not* be balanced with a `drm_bridge_detach()` in driver code.

**Return**

Zero on success, error code on failure

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

```c
enum drm_mode_status drm_bridge_chain_mode_valid(struct drm_bridge *bridge, const struct drm_display_info *info, const struct drm_display_mode *mode)
```

validate the mode against all bridges in the encoder chain.

**Parameters**

- `struct drm_bridge *bridge`: bridge control structure
- `const struct drm_display_info *info`: display info against which the mode shall be validated
- `const struct drm_display_mode *mode`: desired mode to be validated

**Description**

Calls [`drm_bridge_funcs.mode_valid`](#c-struct-drm_bridge_funcs) for all the bridges in the encoder
chain, starting from the first bridge to the last. If at least one bridge
does not accept the mode the function returns the error code.

**Note**

the bridge passed should be the one closest to the encoder.

**Return**

MODE_OK on success, drm_mode_status Enum error code on failure

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

```c
void drm_bridge_chain_mode_set(struct drm_bridge *bridge, const struct drm_display_mode *mode, const struct drm_display_mode *adjusted_mode)
```

set proposed mode for all bridges in the encoder chain

**Parameters**

- `struct drm_bridge *bridge`: bridge control structure
- `const struct drm_display_mode *mode`: desired mode to be set for the encoder chain
- `const struct drm_display_mode *adjusted_mode`: updated mode that works for this encoder chain

**Description**

Calls [`drm_bridge_funcs.mode_set`](#c-struct-drm_bridge_funcs) op for all the bridges in the
encoder chain, starting from the first bridge to the last.

**Note**

the bridge passed should be the one closest to the encoder

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

```c
void drm_atomic_bridge_chain_disable(struct drm_bridge *bridge, struct drm_atomic_state *state)
```

disables all bridges in the encoder chain

**Parameters**

- `struct drm_bridge *bridge`: bridge control structure
- `struct drm_atomic_state *state`: atomic state being committed

**Description**

Calls [`drm_bridge_funcs.atomic_disable`](#c-struct-drm_bridge_funcs) (falls back on
[`drm_bridge_funcs.disable`](#c-struct-drm_bridge_funcs)) op for all the bridges in the encoder chain,
starting from the last bridge to the first. These are called before calling
[`drm_encoder_helper_funcs.atomic_disable`](#c-struct-drm_encoder_helper_funcs)

**Note**

the bridge passed should be the one closest to the encoder

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

```c
void drm_atomic_bridge_chain_post_disable(struct drm_bridge *bridge, struct drm_atomic_state *state)
```

cleans up after disabling all bridges in the encoder chain

**Parameters**

- `struct drm_bridge *bridge`: bridge control structure
- `struct drm_atomic_state *state`: atomic state being committed

**Description**

Calls [`drm_bridge_funcs.atomic_post_disable`](#c-struct-drm_bridge_funcs) (falls back on
[`drm_bridge_funcs.post_disable`](#c-struct-drm_bridge_funcs)) op for all the bridges in the encoder chain,
starting from the first bridge to the last. These are called after completing
[`drm_encoder_helper_funcs.atomic_disable`](#c-struct-drm_encoder_helper_funcs)

If a bridge sets **pre_enable_prev_first**, then the **post_disable** for that
bridge will be called before the previous one to reverse the **pre_enable**
calling direction.

**Example**

Bridge A ---> Bridge B ---> Bridge C ---> Bridge D ---> Bridge E

With pre_enable_prev_first flag enable in Bridge B, D, E then the resulting
**post_disable** order would be,
Bridge B, Bridge A, Bridge E, Bridge D, Bridge C.

**Note**

the bridge passed should be the one closest to the encoder

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

```c
void drm_atomic_bridge_chain_pre_enable(struct drm_bridge *bridge, struct drm_atomic_state *state)
```

prepares for enabling all bridges in the encoder chain

**Parameters**

- `struct drm_bridge *bridge`: bridge control structure
- `struct drm_atomic_state *state`: atomic state being committed

**Description**

Calls [`drm_bridge_funcs.atomic_pre_enable`](#c-struct-drm_bridge_funcs) (falls back on
[`drm_bridge_funcs.pre_enable`](#c-struct-drm_bridge_funcs)) op for all the bridges in the encoder chain,
starting from the last bridge to the first. These are called before calling
[`drm_encoder_helper_funcs.atomic_enable`](#c-struct-drm_encoder_helper_funcs)

If a bridge sets **pre_enable_prev_first**, then the pre_enable for the
prev bridge will be called before pre_enable of this bridge.

**Example**

Bridge A ---> Bridge B ---> Bridge C ---> Bridge D ---> Bridge E

With pre_enable_prev_first flag enable in Bridge B, D, E then the resulting
**pre_enable** order would be,
Bridge C, Bridge D, Bridge E, Bridge A, Bridge B.

**Note**

the bridge passed should be the one closest to the encoder

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

```c
void drm_atomic_bridge_chain_enable(struct drm_bridge *bridge, struct drm_atomic_state *state)
```

enables all bridges in the encoder chain

**Parameters**

- `struct drm_bridge *bridge`: bridge control structure
- `struct drm_atomic_state *state`: atomic state being committed

**Description**

Calls [`drm_bridge_funcs.atomic_enable`](#c-struct-drm_bridge_funcs) (falls back on
[`drm_bridge_funcs.enable`](#c-struct-drm_bridge_funcs)) op for all the bridges in the encoder chain,
starting from the first bridge to the last. These are called after completing
[`drm_encoder_helper_funcs.atomic_enable`](#c-struct-drm_encoder_helper_funcs)

**Note**

the bridge passed should be the one closest to the encoder

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

```c
int drm_atomic_bridge_chain_check(struct drm_bridge *bridge, struct drm_crtc_state *crtc_state, struct drm_connector_state *conn_state)
```

Do an atomic check on the bridge chain

**Parameters**

- `struct drm_bridge *bridge`: bridge control structure
- `struct drm_crtc_state *crtc_state`: new CRTC state
- `struct drm_connector_state *conn_state`: new connector state

**Description**

First trigger a bus format negotiation before calling
[`drm_bridge_funcs.atomic_check()`](#c-struct-drm_bridge_funcs) (falls back on
[`drm_bridge_funcs.mode_fixup()`](#c-struct-drm_bridge_funcs)) op for all the bridges in the encoder chain,
starting from the last bridge to the first. These are called before calling
[`drm_encoder_helper_funcs.atomic_check()`](#c-struct-drm_encoder_helper_funcs)

**Return**

0 on success, a negative error code on failure

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

```c
enum drm_connector_status drm_bridge_detect(struct drm_bridge *bridge, struct drm_connector *connector)
```

check if anything is attached to the bridge output

**Parameters**

- `struct drm_bridge *bridge`: bridge control structure
- `struct drm_connector *connector`: attached connector

**Description**

If the bridge supports output detection, as reported by the
DRM_BRIDGE_OP_DETECT bridge ops flag, call [`drm_bridge_funcs.detect`](#c-struct-drm_bridge_funcs) for the
bridge and return the connection status. Otherwise return
connector_status_unknown.

**Return**

The detection status on success, or connector_status_unknown if the bridge
doesn't support output detection.

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

```c
int drm_bridge_get_modes(struct drm_bridge *bridge, struct drm_connector *connector)
```

fill all modes currently valid for the sink into the **connector**

**Parameters**

- `struct drm_bridge *bridge`: bridge control structure
- `struct drm_connector *connector`: the connector to fill with modes

**Description**

If the bridge supports output modes retrieval, as reported by the
DRM_BRIDGE_OP_MODES bridge ops flag, call [`drm_bridge_funcs.get_modes`](#c-struct-drm_bridge_funcs) to
fill the connector with all valid modes and return the number of modes
added. Otherwise return 0.

**Return**

The number of modes added to the connector.

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

```c
const struct drm_edid * drm_bridge_edid_read(struct drm_bridge *bridge, struct drm_connector *connector)
```

read the EDID data of the connected display

**Parameters**

- `struct drm_bridge *bridge`: bridge control structure
- `struct drm_connector *connector`: the connector to read EDID for

**Description**

If the bridge supports output EDID retrieval, as reported by the
DRM_BRIDGE_OP_EDID bridge ops flag, call [`drm_bridge_funcs.edid_read`](#c-struct-drm_bridge_funcs) to get
the EDID and return it. Otherwise return NULL.

**Return**

The retrieved EDID on success, or NULL otherwise.

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

```c
void drm_bridge_hpd_enable(struct drm_bridge *bridge, void (*cb)(void *data, enum drm_connector_status status), void *data)
```

enable hot plug detection for the bridge

**Parameters**

- `struct drm_bridge *bridge`: bridge control structure
- `void (*cb)(void *data, enum drm_connector_status status)`: hot-plug detection callback
- `void *data`: data to be passed to the hot-plug detection callback

**Description**

Call [`drm_bridge_funcs.hpd_enable`](#c-struct-drm_bridge_funcs) if implemented and register the given **cb**
and **data** as hot plug notification callback. From now on the **cb** will be
called with **data** when an output status change is detected by the bridge,
until hot plug notification gets disabled with [`drm_bridge_hpd_disable()`](#c-drm_bridge_hpd_disable).

Hot plug detection is supported only if the DRM_BRIDGE_OP_HPD flag is set in
bridge->ops. This function shall not be called when the flag is not set.

Only one hot plug detection callback can be registered at a time, it is an
error to call this function when hot plug detection is already enabled for
the bridge.

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

```c
void drm_bridge_hpd_disable(struct drm_bridge *bridge)
```

disable hot plug detection for the bridge

**Parameters**

- `struct drm_bridge *bridge`: bridge control structure

**Description**

Call [`drm_bridge_funcs.hpd_disable`](#c-struct-drm_bridge_funcs) if implemented and unregister the hot
plug detection callback previously registered with [`drm_bridge_hpd_enable()`](#c-drm_bridge_hpd_enable).
Once this function returns the callback will not be called by the bridge
when an output status change occurs.

Hot plug detection is supported only if the DRM_BRIDGE_OP_HPD flag is set in
bridge->ops. This function shall not be called when the flag is not set.

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

```c
void drm_bridge_hpd_notify(struct drm_bridge *bridge, enum drm_connector_status status)
```

notify hot plug detection events

**Parameters**

- `struct drm_bridge *bridge`: bridge control structure
- `enum drm_connector_status status`: output connection status

**Description**

Bridge drivers shall call this function to report hot plug events when they
detect a change in the output status, when hot plug detection has been
enabled by [`drm_bridge_hpd_enable()`](#c-drm_bridge_hpd_enable).

This function shall be called in a context that can sleep.

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

```c
struct drm_bridge * of_drm_find_and_get_bridge(struct device_node *np)
```

find the bridge corresponding to the device node in the global bridge list

**Parameters**

- `struct device_node *np`: device node

**Description**

The refcount of the returned bridge is incremented. Use [`drm_bridge_put()`](#c-drm_bridge_put)
when done with it.

**Return**

drm_bridge control struct on success, NULL on failure

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

```c
struct drm_bridge * of_drm_find_bridge(struct device_node *np)
```

find the bridge corresponding to the device node in the global bridge list

**Parameters**

- `struct device_node *np`: device node

**Description**

This function is deprecated. Convert to [`of_drm_find_and_get_bridge()`](#c-of_drm_find_and_get_bridge)
instead for proper refcounting.

The bridge returned by this function is not refcounted. This is
dangerous because the bridge might be deallocated even before the caller
has a chance to use it. To use this function you have to do one of:

- get a reference with [`drm_bridge_get()`](#c-drm_bridge_get) as soon as possible to
  minimize the race window, and then [`drm_bridge_put()`](#c-drm_bridge_put) when no longer
  using the pointer

- not call [`drm_bridge_get()`](#c-drm_bridge_get) or [`drm_bridge_put()`](#c-drm_bridge_put) at all, which used to
  be the correct practice before dynamic bridge lifetime was introduced

- again, convert to [`of_drm_find_and_get_bridge()`](#c-of_drm_find_and_get_bridge), which is the only safe
  thing to do

**Return**

drm_bridge control struct on success, NULL on failure

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

```c
void devm_drm_put_bridge(struct device *dev, struct drm_bridge *bridge)
```

Release a bridge reference obtained via devm

**Parameters**

- `struct device *dev`: device that got the bridge via devm
- `struct drm_bridge *bridge`: pointer to a struct drm_bridge obtained via devm

**Description**

Same as [`drm_bridge_put()`](#c-drm_bridge_put) for bridge pointers obtained via devm functions
such as [`devm_drm_bridge_alloc()`](#c-devm_drm_bridge_alloc).

This function is a temporary workaround and MUST NOT be used. Manual
handling of bridge lifetime is inherently unsafe.


<a id="rst-mipi-dsi-bridge-operation"></a>

### MIPI-DSI bridge operation


DSI host interfaces are expected to be implemented as bridges rather than
encoders, however there are a few aspects of their operation that need to
be defined in order to provide a consistent interface.

A DSI host should keep the PHY powered down until the pre_enable operation is
called. All lanes are in an undefined idle state up to this point, and it
must not be assumed that it is LP-11.
pre_enable should initialise the PHY, set the data lanes to LP-11, and the
clock lane to either LP-11 or HS depending on the mode_flag
`MIPI_DSI_CLOCK_NON_CONTINUOUS`.

Ordinarily the downstream bridge DSI peripheral pre_enable will have been
called before the DSI host. If the DSI peripheral requires LP-11 and/or
the clock lane to be in HS mode prior to pre_enable, then it can set the
`pre_enable_prev_first` flag to request the pre_enable (and
post_disable) order to be altered to enable the DSI host first.

Either the CRTC being enabled, or the DSI host enable operation should switch
the host to actively transmitting video on the data lanes.

The reverse also applies. The DSI host disable operation or stopping the CRTC
should stop transmitting video, and the data lanes should return to the LP-11
state. The DSI host `post_disable` operation should disable the PHY.
If the `pre_enable_prev_first` flag is set, then the DSI peripheral's
bridge `post_disable` will be called before the DSI host's post_disable.

Whilst it is valid to call `host_transfer` prior to pre_enable or after
post_disable, the exact state of the lanes is undefined at this point. The
DSI host should initialise the interface, transmit the data, and then disable
the interface again.

Ultra Low Power State (ULPS) is not explicitly supported by DRM. If
implemented, it therefore needs to be handled entirely within the DSI Host
driver.


<a id="rst-bridge-connector-helper-reference"></a>

### Bridge Connector Helper Reference


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

```c
struct drm_connector * drm_bridge_connector_init(struct drm_device *drm, struct drm_encoder *encoder)
```

Initialise a connector for a chain of bridges

**Parameters**

- `struct drm_device *drm`: the DRM device
- `struct drm_encoder *encoder`: the encoder where the bridge chain starts

**Description**

Allocate, initialise and register a `drm_bridge_connector` with the **drm**
device. The connector is associated with a chain of bridges that starts at
the **encoder**. All bridges in the chain shall report bridge operation flags
([`drm_bridge->ops`](#c-struct-drm_bridge)) and bridge output type ([`drm_bridge->type`](#c-struct-drm_bridge)), and none of
them may create a DRM connector directly.

Returns a pointer to the new connector on success, or a negative error
pointer otherwise.


<a id="rst-panel-bridge-helper-reference"></a>

### Panel-Bridge Helper Reference


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

```c
bool drm_bridge_is_panel(const struct drm_bridge *bridge)
```

Checks if a drm_bridge is a panel_bridge.

**Parameters**

- `const struct drm_bridge *bridge`: The drm_bridge to be checked.

**Description**

Returns true if the bridge is a panel bridge, or false otherwise.

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

```c
struct drm_bridge * drm_panel_bridge_add(struct drm_panel *panel)
```

Creates a [`drm_bridge`](#c-struct-drm_bridge) and [`drm_connector`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_connector) that just calls the appropriate functions from [`drm_panel`](#c-struct-drm_panel).

**Parameters**

- `struct drm_panel *panel`: The drm_panel being wrapped.  Must be non-NULL.

**Description**

For drivers converting from directly using drm_panel: The expected
usage pattern is that during either encoder module probe or DSI
host attach, a drm_panel will be looked up through
[`drm_of_find_panel_or_bridge()`](#c-drm_of_find_panel_or_bridge).  [`drm_panel_bridge_add()`](#c-drm_panel_bridge_add) is used to
wrap that panel in the new bridge, and the result can then be
passed to [`drm_bridge_attach()`](#c-drm_bridge_attach).  The [`drm_panel_prepare()`](#c-drm_panel_prepare) and related
functions can be dropped from the encoder driver (they're now
called by the KMS helpers before calling into the encoder), along
with connector creation.  When done with the bridge (after
[`drm_mode_config_cleanup()`](/kernel/hardware/gpu/drm-kms.md#c-drm_mode_config_cleanup) if the bridge has already been attached), then
[`drm_panel_bridge_remove()`](#c-drm_panel_bridge_remove) to free it.

The connector type is set to **panel->connector_type**, which must be set to a
known type. Calling this function with a panel whose connector type is
DRM_MODE_CONNECTOR_Unknown will return ERR_PTR(-EINVAL).

See [`devm_drm_panel_bridge_add()`](#c-devm_drm_panel_bridge_add) for an automatically managed version of this
function.

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

```c
struct drm_bridge * drm_panel_bridge_add_typed(struct drm_panel *panel, u32 connector_type)
```

Creates a [`drm_bridge`](#c-struct-drm_bridge) and [`drm_connector`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_connector) with an explicit connector type.

**Parameters**

- `struct drm_panel *panel`: The drm_panel being wrapped.  Must be non-NULL.
- `u32 connector_type`: The connector type (DRM_MODE_CONNECTOR_*)

**Description**

This is just like [`drm_panel_bridge_add()`](#c-drm_panel_bridge_add), but forces the connector type to
**connector_type** instead of infering it from the panel.

This function is deprecated and should not be used in new drivers. Use
[`drm_panel_bridge_add()`](#c-drm_panel_bridge_add) instead, and fix panel drivers as necessary if they
don't report a connector type.

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

```c
void drm_panel_bridge_remove(struct drm_bridge *bridge)
```

Unregisters and frees a drm_bridge created by [`drm_panel_bridge_add()`](#c-drm_panel_bridge_add).

**Parameters**

- `struct drm_bridge *bridge`: The drm_bridge being freed.

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

```c
int drm_panel_bridge_set_orientation(struct drm_connector *connector, struct drm_bridge *bridge)
```

Set the connector's panel orientation from the bridge that can be transformed to panel bridge.

**Parameters**

- `struct drm_connector *connector`: The connector to be set panel orientation.
- `struct drm_bridge *bridge`: The drm_bridge to be transformed to panel bridge.

**Description**

Returns 0 on success, negative errno on failure.

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

```c
struct drm_bridge * devm_drm_panel_bridge_add(struct device *dev, struct drm_panel *panel)
```

Creates a managed [`drm_bridge`](#c-struct-drm_bridge) and [`drm_connector`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_connector) that just calls the appropriate functions from [`drm_panel`](#c-struct-drm_panel).

**Parameters**

- `struct device *dev`: device to tie the bridge lifetime to
- `struct drm_panel *panel`: The drm_panel being wrapped.  Must be non-NULL.

**Description**

This is the managed version of [`drm_panel_bridge_add()`](#c-drm_panel_bridge_add) which automatically
calls [`drm_panel_bridge_remove()`](#c-drm_panel_bridge_remove) when **dev** is unbound.

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

```c
struct drm_bridge * devm_drm_panel_bridge_add_typed(struct device *dev, struct drm_panel *panel, u32 connector_type)
```

Creates a managed [`drm_bridge`](#c-struct-drm_bridge) and [`drm_connector`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_connector) with an explicit connector type.

**Parameters**

- `struct device *dev`: device to tie the bridge lifetime to
- `struct drm_panel *panel`: The drm_panel being wrapped.  Must be non-NULL.
- `u32 connector_type`: The connector type (DRM_MODE_CONNECTOR_*)

**Description**

This is just like [`devm_drm_panel_bridge_add()`](#c-devm_drm_panel_bridge_add), but forces the connector type
to **connector_type** instead of infering it from the panel.

This function is deprecated and should not be used in new drivers. Use
[`devm_drm_panel_bridge_add()`](#c-devm_drm_panel_bridge_add) instead, and fix panel drivers as necessary if
they don't report a connector type.

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

```c
struct drm_bridge * drmm_panel_bridge_add(struct drm_device *drm, struct drm_panel *panel)
```

Creates a DRM-managed [`drm_bridge`](#c-struct-drm_bridge) and [`drm_connector`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_connector) that just calls the appropriate functions from [`drm_panel`](#c-struct-drm_panel).

**Parameters**

- `struct drm_device *drm`: DRM device to tie the bridge lifetime to
- `struct drm_panel *panel`: The drm_panel being wrapped.  Must be non-NULL.

**Description**

This is the DRM-managed version of [`drm_panel_bridge_add()`](#c-drm_panel_bridge_add) which
automatically calls [`drm_panel_bridge_remove()`](#c-drm_panel_bridge_remove) when **dev** is cleaned
up.

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

```c
struct drm_connector * drm_panel_bridge_connector(struct drm_bridge *bridge)
```

return the connector for the panel bridge

**Parameters**

- `struct drm_bridge *bridge`: The drm_bridge.

**Description**

drm_panel_bridge creates the connector.
This function gives external access to the connector.

**Return**

Pointer to drm_connector

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

```c
struct drm_bridge * devm_drm_of_get_bridge(struct device *dev, struct device_node *np, u32 port, u32 endpoint)
```

Return next bridge in the chain

**Parameters**

- `struct device *dev`: device to tie the bridge lifetime to
- `struct device_node *np`: device tree node containing encoder output ports
- `u32 port`: port in the device tree node
- `u32 endpoint`: endpoint in the device tree node

**Description**

Given a DT node's port and endpoint number, finds the connected node
and returns the associated bridge if any, or creates and returns a
drm panel bridge instance if a panel is connected.

Returns a pointer to the bridge if successful, or an error pointer
otherwise.

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

```c
struct drm_bridge * drmm_of_get_bridge(struct drm_device *drm, struct device_node *np, u32 port, u32 endpoint)
```

Return next bridge in the chain

**Parameters**

- `struct drm_device *drm`: device to tie the bridge lifetime to
- `struct device_node *np`: device tree node containing encoder output ports
- `u32 port`: port in the device tree node
- `u32 endpoint`: endpoint in the device tree node

**Description**

Given a DT node's port and endpoint number, finds the connected node
and returns the associated bridge if any, or creates and returns a
drm panel bridge instance if a panel is connected.

Returns a drmm managed pointer to the bridge if successful, or an error
pointer otherwise.


<a id="rst-panel-helper-reference"></a>
<a id="rst-drm-panel-helper"></a>

## Panel Helper Reference


The DRM panel helpers allow drivers to register panel objects with a
central registry and provide functions to retrieve those panels in display
drivers.

For easy integration into drivers using the [`drm_bridge`](#c-struct-drm_bridge) infrastructure please
take look at [`drm_panel_bridge_add()`](#c-drm_panel_bridge_add) and [`devm_drm_panel_bridge_add()`](#c-devm_drm_panel_bridge_add).



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

perform operations on a given panel

**Definition**

```c
struct drm_panel_funcs {
    int (*prepare)(struct drm_panel *panel);
    int (*enable)(struct drm_panel *panel);
    int (*disable)(struct drm_panel *panel);
    int (*unprepare)(struct drm_panel *panel);
    int (*get_modes)(struct drm_panel *panel, struct drm_connector *connector);
    enum drm_panel_orientation (*get_orientation)(struct drm_panel *panel);
    int (*get_timings)(struct drm_panel *panel, unsigned int num_timings, struct display_timing *timings);
    void (*debugfs_init)(struct drm_panel *panel, struct dentry *root);
};
```

**Members**

- `prepare`: Turn on panel and perform set up.

  This function is optional.
- `enable`: Enable panel (turn on back light, etc.).

  This function is optional.
- `disable`: Disable panel (turn off back light, etc.).

  This function is optional.
- `unprepare`: Turn off panel.

  This function is optional.
- `get_modes`: Add modes to the connector that the panel is attached to
  and returns the number of modes added.

  This function is mandatory.
- `get_orientation`: Return the panel orientation set by device tree or EDID.

  This function is optional.
- `get_timings`: Copy display timings into the provided array and return
  the number of display timings available.

  This function is optional.
- `debugfs_init`: Allows panels to create panels-specific debugfs files.

**Description**

The .`prepare()` function is typically called before the display controller
starts to transmit video data. Panel drivers can use this to turn the panel
on and wait for it to become ready. If additional configuration is required
(via a control bus such as I2C, SPI or DSI for example) this is a good time
to do that.

After the display controller has started transmitting video data, it's safe
to call the .`enable()` function. This will typically enable the backlight to
make the image on screen visible. Some panels require a certain amount of
time or frames before the image is displayed. This function is responsible
for taking this into account before enabling the backlight to avoid visual
glitches.

Before stopping video transmission from the display controller it can be
necessary to turn off the panel to avoid visual glitches. This is done in
the .`disable()` function. Analogously to .`enable()` this typically involves
turning off the backlight and waiting for some time to make sure no image
is visible on the panel. It is then safe for the display controller to
cease transmission of video data.

To save power when no video data is transmitted, a driver can power down
the panel. This is the job of the .`unprepare()` function.

Backlight can be handled automatically if configured using
[`drm_panel_of_backlight()`](#c-drm_panel_of_backlight) or [`drm_panel_dp_aux_backlight()`](#c-drm_panel_dp_aux_backlight). Then the driver
does not need to implement the functionality to enable/disable backlight.

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

DRM panel object

**Definition**

```c
struct drm_panel {
    struct device *dev;
    struct backlight_device *backlight;
    const struct drm_panel_funcs *funcs;
    int connector_type;
    struct list_head list;
    struct list_head followers;
    struct mutex follower_lock;
    bool prepare_prev_first;
    bool prepared;
    bool enabled;
    void *container;
    struct kref refcount;
};
```

**Members**

- `dev`: Parent device of the panel.
- `backlight`: Backlight device, used to turn on backlight after the call
  to `enable()`, and to turn off backlight before the call to
  `disable()`.
  backlight is set by [`drm_panel_of_backlight()`](#c-drm_panel_of_backlight) or
  [`drm_panel_dp_aux_backlight()`](#c-drm_panel_dp_aux_backlight) and drivers shall not assign it.
- `funcs`: Operations that can be performed on the panel.
- `connector_type`: Type of the panel as a DRM_MODE_CONNECTOR_* value. This is used to
  initialise the drm_connector corresponding to the panel with the
  correct connector type.
- `list`: Panel entry in registry.
- `followers`: A list of struct drm_panel_follower dependent on this panel.
- `follower_lock`: Lock for followers list.
- `prepare_prev_first`: The previous controller should be prepared first, before the prepare
  for the panel is called. This is largely required for DSI panels
  where the DSI host controller should be initialised to LP-11 before
  the panel is powered up.
- `prepared`: If true then the panel has been prepared.
- `enabled`: If true then the panel has been enabled.
- `container`: Pointer to the private driver struct embedding this
  **struct** drm_panel.
- `refcount`: reference count of users referencing this panel.

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

```c
devm_drm_panel_alloc(dev, type, member, funcs, connector_type)
```

Allocate and initialize a refcounted panel.

**Parameters**

- `dev`: struct device of the panel device
- `type`: the type of the struct which contains struct [`drm_panel`](#c-struct-drm_panel)
- `member`: the name of the [`drm_panel`](#c-struct-drm_panel) within **type**
- `funcs`: callbacks for this panel
- `connector_type`: the connector type (DRM_MODE_CONNECTOR_*) corresponding to
  the panel interface

**Description**

The reference count of the returned panel is initialized to 1. This
reference will be automatically dropped via devm (by calling
[`drm_panel_put()`](#c-drm_panel_put)) when **dev** is removed.

**Return**

Pointer to container structure embedding the panel, ERR_PTR on failure.



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

```c
void drm_panel_init(struct drm_panel *panel, struct device *dev, const struct drm_panel_funcs *funcs, int connector_type)
```

initialize a panel

**Parameters**

- `struct drm_panel *panel`: DRM panel
- `struct device *dev`: parent device of the panel
- `const struct drm_panel_funcs *funcs`: panel operations
- `int connector_type`: the connector type (DRM_MODE_CONNECTOR_*) corresponding to
  the panel interface (must NOT be DRM_MODE_CONNECTOR_Unknown)

**Description**

Initialize the panel structure for subsequent registration with
[`drm_panel_add()`](#c-drm_panel_add).

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

```c
void drm_panel_add(struct drm_panel *panel)
```

add a panel to the global registry

**Parameters**

- `struct drm_panel *panel`: panel to add

**Description**

Add a panel to the global registry so that it can be looked
up by display drivers. The panel to be added must have been
allocated by [`devm_drm_panel_alloc()`](#c-devm_drm_panel_alloc).

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

```c
void drm_panel_remove(struct drm_panel *panel)
```

remove a panel from the global registry

**Parameters**

- `struct drm_panel *panel`: DRM panel

**Description**

Removes a panel from the global registry.

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

```c
void drm_panel_prepare(struct drm_panel *panel)
```

power on a panel

**Parameters**

- `struct drm_panel *panel`: DRM panel

**Description**

Calling this function will enable power and deassert any reset signals to
the panel. After this has completed it is possible to communicate with any
integrated circuitry via a command bus. This function cannot fail (as it is
called from the pre_enable call chain). There will always be a call to
[`drm_panel_disable()`](#c-drm_panel_disable) afterwards.

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

```c
void drm_panel_unprepare(struct drm_panel *panel)
```

power off a panel

**Parameters**

- `struct drm_panel *panel`: DRM panel

**Description**

Calling this function will completely power off a panel (assert the panel's
reset, turn off power supplies, ...). After this function has completed, it
is usually no longer possible to communicate with the panel until another
call to [`drm_panel_prepare()`](#c-drm_panel_prepare).

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

```c
void drm_panel_enable(struct drm_panel *panel)
```

enable a panel

**Parameters**

- `struct drm_panel *panel`: DRM panel

**Description**

Calling this function will cause the panel display drivers to be turned on
and the backlight to be enabled. Content will be visible on screen after
this call completes. This function cannot fail (as it is called from the
enable call chain). There will always be a call to [`drm_panel_disable()`](#c-drm_panel_disable)
afterwards.

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

```c
void drm_panel_disable(struct drm_panel *panel)
```

disable a panel

**Parameters**

- `struct drm_panel *panel`: DRM panel

**Description**

This will typically turn off the panel's backlight or disable the display
drivers. For smart panels it should still be possible to communicate with
the integrated circuitry via any command bus after this call.

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

```c
int drm_panel_get_modes(struct drm_panel *panel, struct drm_connector *connector)
```

probe the available display modes of a panel

**Parameters**

- `struct drm_panel *panel`: DRM panel
- `struct drm_connector *connector`: DRM connector

**Description**

The modes probed from the panel are automatically added to the connector
that the panel is attached to.

**Return**

The number of modes available from the panel on success, or 0 on
failure (no modes).

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

```c
struct drm_panel * drm_panel_get(struct drm_panel *panel)
```

Acquire a panel reference

**Parameters**

- `struct drm_panel *panel`: DRM panel

**Description**

This function increments the panel's refcount.

**Return**

Pointer to **panel**

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

```c
void drm_panel_put(struct drm_panel *panel)
```

Release a panel reference

**Parameters**

- `struct drm_panel *panel`: DRM panel

**Description**

This function decrements the panel's reference count and frees the
object if the reference count drops to zero.

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

```c
struct drm_panel * of_drm_find_panel(const struct device_node *np)
```

look up a panel using a device tree node

**Parameters**

- `const struct device_node *np`: device tree node of the panel

**Description**

Searches the set of registered panels for one that matches the given device
tree node. If a matching panel is found, return a pointer to it.

Possible error codes returned by this function:

- EPROBE_DEFER: the panel device has not been probed yet, and the caller
  should retry later
- ENODEV: the device is not available (status != "okay" or "ok")

**Return**

A pointer to the panel registered for the specified device tree
node or an [`ERR_PTR()`](/kernel/internals/core-api/kernel-api.md#c-ERR_PTR) if no panel matching the device tree node can be found.

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

```c
int of_drm_get_panel_orientation(const struct device_node *np, enum drm_panel_orientation *orientation)
```

look up the orientation of the panel through the "rotation" binding from a device tree node

**Parameters**

- `const struct device_node *np`: device tree node of the panel
- `enum drm_panel_orientation *orientation`: orientation enum to be filled in

**Description**

Looks up the rotation of a panel in the device tree. The orientation of the
panel is expressed as a property name "rotation" in the device tree. The
rotation in the device tree is counter clockwise.

**Return**

0 when a valid rotation value (0, 90, 180, or 270) is read or the
rotation property doesn't exist. Return a negative error code on failure.

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

```c
bool drm_is_panel_follower(struct device *dev)
```

Check if the device is a panel follower

**Parameters**

- `struct device *dev`: The 'struct device' to check

**Description**

This checks to see if a device needs to be power sequenced together with
a panel using the panel follower API.

The "panel" property of the follower points to the panel to be followed.

**Return**

true if we should be power sequenced with a panel; false otherwise.

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

```c
int drm_panel_add_follower(struct device *follower_dev, struct drm_panel_follower *follower)
```

Register something to follow panel state.

**Parameters**

- `struct device *follower_dev`: The 'struct device' for the follower.
- `struct drm_panel_follower *follower`: The panel follower descriptor for the follower.

**Description**

A panel follower is called right after preparing/enabling the panel and right
before unpreparing/disabling the panel. It's primary intention is to power on
an associated touchscreen, though it could be used for any similar devices.
Multiple devices are allowed the follow the same panel.

If a follower is added to a panel that's already been prepared/enabled, the
follower's prepared/enabled callback is called right away.

The "panel" property of the follower points to the panel to be followed.

**Return**

0 or an error code. Note that -ENODEV means that we detected that
follower_dev is not actually following a panel. The caller may
choose to ignore this return value if following a panel is optional.

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

```c
void drm_panel_remove_follower(struct drm_panel_follower *follower)
```

Reverse [`drm_panel_add_follower()`](#c-drm_panel_add_follower).

**Parameters**

- `struct drm_panel_follower *follower`: The panel follower descriptor for the follower.

**Description**

Undo [`drm_panel_add_follower()`](#c-drm_panel_add_follower). This includes calling the follower's
unpreparing/disabling function if we're removed from a panel that's currently
prepared/enabled.

**Return**

0 or an error code.

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

```c
int devm_drm_panel_add_follower(struct device *follower_dev, struct drm_panel_follower *follower)
```

devm version of [`drm_panel_add_follower()`](#c-drm_panel_add_follower)

**Parameters**

- `struct device *follower_dev`: The 'struct device' for the follower.
- `struct drm_panel_follower *follower`: The panel follower descriptor for the follower.

**Description**

Handles calling [`drm_panel_remove_follower()`](#c-drm_panel_remove_follower) using devm on the follower_dev.

**Return**

0 or an error code.

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

```c
int drm_panel_of_backlight(struct drm_panel *panel)
```

use backlight device node for backlight

**Parameters**

- `struct drm_panel *panel`: DRM panel

**Description**

Use this function to enable backlight handling if your panel
uses device tree and has a backlight phandle.

When the panel is enabled backlight will be enabled after a
successful call to [`drm_panel_funcs.enable()`](#c-struct-drm_panel_funcs)

When the panel is disabled backlight will be disabled before the
call to [`drm_panel_funcs.disable()`](#c-struct-drm_panel_funcs).

A typical implementation for a panel driver supporting device tree
will call this function at probe time. Backlight will then be handled
transparently without requiring any intervention from the driver.
[`drm_panel_of_backlight()`](#c-drm_panel_of_backlight) must be called after the call to [`drm_panel_init()`](#c-drm_panel_init).

**Return**

0 on success or a negative error code on failure.



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

```c
int drm_get_panel_orientation_quirk(int width, int height)
```

Check for panel orientation quirks

**Parameters**

- `int width`: width in pixels of the panel
- `int height`: height in pixels of the panel

**Description**

This function checks for platform specific (e.g. DMI based) quirks
providing info on panel_orientation for systems where this cannot be
probed from the hard-/firm-ware. To avoid false-positive this function
takes the panel resolution as argument and checks that against the
resolution expected by the quirk-table entry.

Note this function is also used outside of the drm-subsys, by for example
the efifb code. Because of this this function gets compiled into its own
kernel-module when built as a module.

**Return**

A DRM_MODE_PANEL_ORIENTATION_* value if there is a quirk for this system,
or DRM_MODE_PANEL_ORIENTATION_UNKNOWN if there is no quirk.



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

```c
const struct drm_panel_backlight_quirk * drm_get_panel_backlight_quirk(const struct drm_edid *edid)
```

Get backlight quirks for a panel

**Parameters**

- `const struct drm_edid *edid`: EDID of the panel to check

**Description**

This function checks for platform specific (e.g. DMI based) quirks
providing info on the minimum backlight brightness for systems where this
cannot be probed correctly from the hard-/firm-ware and other sources.

**Return**

a drm_panel_backlight_quirk struct if a quirk was found, otherwise an
error pointer.


<a id="rst-panel-self-refresh-helper-reference"></a>

## Panel Self Refresh Helper Reference


This helper library provides an easy way for drivers to leverage the atomic
framework to implement panel self refresh (SR) support. Drivers are
responsible for initializing and cleaning up the SR helpers on load/unload
(see [`drm_self_refresh_helper_init`](#c-drm_self_refresh_helper_init)/[`drm_self_refresh_helper_cleanup`](#c-drm_self_refresh_helper_cleanup)).
The connector is responsible for setting
[`drm_connector_state.self_refresh_aware`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_connector_state) to true at runtime if it is SR-aware
(meaning it knows how to initiate self refresh on the panel).

Once a crtc has enabled SR using [`drm_self_refresh_helper_init`](#c-drm_self_refresh_helper_init), the
helpers will monitor activity and call back into the driver to enable/disable
SR as appropriate. The best way to think about this is that it's a DPMS
on/off request with [`drm_crtc_state.self_refresh_active`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_crtc_state) set in crtc state
that tells you to disable/enable SR on the panel instead of power-cycling it.

During SR, drivers may choose to fully disable their crtc/encoder/bridge
hardware (in which case no driver changes are necessary), or they can inspect
[`drm_crtc_state.self_refresh_active`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_crtc_state) if they want to enter low power mode
without full disable (in case full disable/enable is too slow).

SR will be deactivated if there are any atomic updates affecting the
pipe that is in SR mode. If a crtc is driving multiple connectors, all
connectors must be SR aware and all will enter/exit SR mode at the same time.

If the crtc and connector are SR aware, but the panel connected does not
support it (or is otherwise unable to enter SR), the driver should fail
atomic_check when [`drm_crtc_state.self_refresh_active`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_crtc_state) is true.



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

```c
void drm_self_refresh_helper_update_avg_times(struct drm_atomic_state *state, unsigned int commit_time_ms, unsigned int new_self_refresh_mask)
```

Updates a crtc's SR time averages

**Parameters**

- `struct drm_atomic_state *state`: the state which has just been applied to hardware
- `unsigned int commit_time_ms`: the amount of time in ms that this commit took to complete
- `unsigned int new_self_refresh_mask`: bitmask of crtc's that have self_refresh_active in
  new state

**Description**

Called after [`drm_mode_config_funcs.atomic_commit_tail`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_mode_config_funcs), this function will
update the average entry/exit self refresh times on self refresh transitions.
These averages will be used when calculating how long to delay before
entering self refresh mode after activity.

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

```c
void drm_self_refresh_helper_alter_state(struct drm_atomic_state *state)
```

Alters the atomic state for SR exit

**Parameters**

- `struct drm_atomic_state *state`: the state currently being checked

**Description**

Called at the end of atomic check. This function checks the state for flags
incompatible with self refresh exit and changes them. This is a bit
disingenuous since userspace is expecting one thing and we're giving it
another. However in order to keep self refresh entirely hidden from
userspace, this is required.

At the end, we queue up the self refresh entry work so we can enter PSR after
the desired delay.

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

```c
int drm_self_refresh_helper_init(struct drm_crtc *crtc)
```

Initializes self refresh helpers for a crtc

**Parameters**

- `struct drm_crtc *crtc`: the crtc which supports self refresh supported displays

**Description**

Returns zero if successful or -errno on failure

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

```c
void drm_self_refresh_helper_cleanup(struct drm_crtc *crtc)
```

Cleans up self refresh helpers for a crtc

**Parameters**

- `struct drm_crtc *crtc`: the crtc to cleanup


<a id="rst-hdmi-atomic-state-helpers"></a>

## HDMI Atomic State Helpers

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

### Overview


These functions contain an implementation of the HDMI specification
in the form of KMS helpers.

It contains TMDS character rate computation, automatic selection of
output formats, infoframes generation, etc.

**Infoframes Compliance**

Drivers using the helpers will expose the various infoframes
generated according to the HDMI specification in debugfs.

Compliance can then be tested using `edid-decode` from the `v4l-utils` project
(https://git.linuxtv.org/v4l-utils.git/). A sample run would look like:

```bash
# edid-decode \
        -I /sys/kernel/debug/dri/1/HDMI-A-1/infoframes/audio \
        -I /sys/kernel/debug/dri/1/HDMI-A-1/infoframes/avi \
        -I /sys/kernel/debug/dri/1/HDMI-A-1/infoframes/hdmi \
        -I /sys/kernel/debug/dri/1/HDMI-A-1/infoframes/hdr_drm \
        -I /sys/kernel/debug/dri/1/HDMI-A-1/infoframes/spd \
        /sys/class/drm/card1-HDMI-A-1/edid \
        -c

edid-decode (hex):

00 ff ff ff ff ff ff 00 1e 6d f4 5b 1e ef 06 00
07 20 01 03 80 2f 34 78 ea 24 05 af 4f 42 ab 25
0f 50 54 21 08 00 d1 c0 61 40 45 40 01 01 01 01
01 01 01 01 01 01 98 d0 00 40 a1 40 d4 b0 30 20
3a 00 d1 0b 12 00 00 1a 00 00 00 fd 00 3b 3d 1e
b2 31 00 0a 20 20 20 20 20 20 00 00 00 fc 00 4c
47 20 53 44 51 48 44 0a 20 20 20 20 00 00 00 ff
00 32 30 37 4e 54 52 4c 44 43 34 33 30 0a 01 46

02 03 42 72 23 09 07 07 4d 01 03 04 90 12 13 1f
22 5d 5e 5f 60 61 83 01 00 00 6d 03 0c 00 10 00
b8 3c 20 00 60 01 02 03 67 d8 5d c4 01 78 80 03
e3 0f 00 18 e2 00 6a e3 05 c0 00 e6 06 05 01 52
52 51 11 5d 00 a0 a0 40 29 b0 30 20 3a 00 d1 0b
12 00 00 1a 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 c3

----------------

Block 0, Base EDID:
  EDID Structure Version & Revision: 1.3
  Vendor & Product Identification:
    Manufacturer: GSM
    Model: 23540
    Serial Number: 454430 (0x0006ef1e)
    Made in: week 7 of 2022
  Basic Display Parameters & Features:
    Digital display
    Maximum image size: 47 cm x 52 cm
    Gamma: 2.20
    DPMS levels: Standby Suspend Off
    RGB color display
    First detailed timing is the preferred timing
  Color Characteristics:
    Red  : 0.6835, 0.3105
    Green: 0.2587, 0.6679
    Blue : 0.1445, 0.0585
    White: 0.3134, 0.3291
  Established Timings I & II:
    DMT 0x04:   640x480    59.940476 Hz   4:3     31.469 kHz     25.175000 MHz
    DMT 0x09:   800x600    60.316541 Hz   4:3     37.879 kHz     40.000000 MHz
    DMT 0x10:  1024x768    60.003840 Hz   4:3     48.363 kHz     65.000000 MHz
  Standard Timings:
    DMT 0x52:  1920x1080   60.000000 Hz  16:9     67.500 kHz    148.500000 MHz
    DMT 0x10:  1024x768    60.003840 Hz   4:3     48.363 kHz     65.000000 MHz
    DMT 0x09:   800x600    60.316541 Hz   4:3     37.879 kHz     40.000000 MHz
  Detailed Timing Descriptors:
    DTD 1:  2560x2880   59.966580 Hz   8:9    185.417 kHz    534.000000 MHz (465 mm x 523 mm)
                 Hfront   48 Hsync  32 Hback  240 Hpol P
                 Vfront    3 Vsync  10 Vback  199 Vpol N
    Display Range Limits:
      Monitor ranges (GTF): 59-61 Hz V, 30-178 kHz H, max dotclock 490 MHz
    Display Product Name: 'LG SDQHD'
    Display Product Serial Number: '207NTRLDC430'
  Extension blocks: 1
Checksum: 0x46

----------------

Block 1, CTA-861 Extension Block:
  Revision: 3
  Basic audio support
  Supports YCbCr 4:4:4
  Supports YCbCr 4:2:2
  Native detailed modes: 2
  Audio Data Block:
    Linear PCM:
      Max channels: 2
      Supported sample rates (kHz): 48 44.1 32
      Supported sample sizes (bits): 24 20 16
  Video Data Block:
    VIC   1:   640x480    59.940476 Hz   4:3     31.469 kHz     25.175000 MHz
    VIC   3:   720x480    59.940060 Hz  16:9     31.469 kHz     27.000000 MHz
    VIC   4:  1280x720    60.000000 Hz  16:9     45.000 kHz     74.250000 MHz
    VIC  16:  1920x1080   60.000000 Hz  16:9     67.500 kHz    148.500000 MHz (native)
    VIC  18:   720x576    50.000000 Hz  16:9     31.250 kHz     27.000000 MHz
    VIC  19:  1280x720    50.000000 Hz  16:9     37.500 kHz     74.250000 MHz
    VIC  31:  1920x1080   50.000000 Hz  16:9     56.250 kHz    148.500000 MHz
    VIC  34:  1920x1080   30.000000 Hz  16:9     33.750 kHz     74.250000 MHz
    VIC  93:  3840x2160   24.000000 Hz  16:9     54.000 kHz    297.000000 MHz
    VIC  94:  3840x2160   25.000000 Hz  16:9     56.250 kHz    297.000000 MHz
    VIC  95:  3840x2160   30.000000 Hz  16:9     67.500 kHz    297.000000 MHz
    VIC  96:  3840x2160   50.000000 Hz  16:9    112.500 kHz    594.000000 MHz
    VIC  97:  3840x2160   60.000000 Hz  16:9    135.000 kHz    594.000000 MHz
  Speaker Allocation Data Block:
    FL/FR - Front Left/Right
  Vendor-Specific Data Block (HDMI), OUI 00-0C-03:
    Source physical address: 1.0.0.0
    Supports_AI
    DC_36bit
    DC_30bit
    DC_Y444
    Maximum TMDS clock: 300 MHz
    Extended HDMI video details:
      HDMI VICs:
        HDMI VIC 1:  3840x2160   30.000000 Hz  16:9     67.500 kHz    297.000000 MHz
        HDMI VIC 2:  3840x2160   25.000000 Hz  16:9     56.250 kHz    297.000000 MHz
        HDMI VIC 3:  3840x2160   24.000000 Hz  16:9     54.000 kHz    297.000000 MHz
  Vendor-Specific Data Block (HDMI Forum), OUI C4-5D-D8:
    Version: 1
    Maximum TMDS Character Rate: 600 MHz
    SCDC Present
    Supports 12-bits/component Deep Color 4:2:0 Pixel Encoding
    Supports 10-bits/component Deep Color 4:2:0 Pixel Encoding
  YCbCr 4:2:0 Capability Map Data Block:
    VIC  96:  3840x2160   50.000000 Hz  16:9    112.500 kHz    594.000000 MHz
    VIC  97:  3840x2160   60.000000 Hz  16:9    135.000 kHz    594.000000 MHz
  Video Capability Data Block:
    YCbCr quantization: No Data
    RGB quantization: Selectable (via AVI Q)
    PT scan behavior: Always Underscanned
    IT scan behavior: Always Underscanned
    CE scan behavior: Always Underscanned
  Colorimetry Data Block:
    BT2020YCC
    BT2020RGB
  HDR Static Metadata Data Block:
    Electro optical transfer functions:
      Traditional gamma - SDR luminance range
      SMPTE ST2084
    Supported static metadata descriptors:
      Static metadata type 1
    Desired content max luminance: 82 (295.365 cd/m^2)
    Desired content max frame-average luminance: 82 (295.365 cd/m^2)
    Desired content min luminance: 81 (0.298 cd/m^2)
  Detailed Timing Descriptors:
    DTD 2:  2560x2880   29.986961 Hz   8:9     87.592 kHz    238.250000 MHz (465 mm x 523 mm)
                 Hfront   48 Hsync  32 Hback   80 Hpol P
                 Vfront    3 Vsync  10 Vback   28 Vpol N
Checksum: 0xc3  Unused space in Extension Block: 43 bytes

----------------

edid-decode 1.29.0-5346
edid-decode SHA: c363e9aa6d70 2025-03-11 11:41:18

Warnings:

Block 1, CTA-861 Extension Block:
  IT Video Formats are overscanned by default, but normally this should be underscanned.
  Video Data Block: VIC 1 and the first DTD are not identical. Is this intended?
  Video Data Block: All VICs are in ascending order, and the first (preferred) VIC <= 4, is that intended?
  Video Capability Data Block: Set Selectable YCbCr Quantization to avoid interop issues.
  Video Capability Data Block: S_PT is equal to S_IT and S_CE, so should be set to 0 instead.
  Colorimetry Data Block: Set the sRGB colorimetry bit to avoid interop issues.
  Display Product Serial Number is set, so the Serial Number in the Base EDID should be 0.
EDID:
  Base EDID: Some timings are out of range of the Monitor Ranges:
    Vertical Freq: 24.000 - 60.317 Hz (Monitor: 59.000 - 61.000 Hz)
    Horizontal Freq: 31.250 - 185.416 kHz (Monitor: 30.000 - 178.000 kHz)
    Maximum Clock: 594.000 MHz (Monitor: 490.000 MHz)

Failures:

Block 1, CTA-861 Extension Block:
  Video Capability Data Block: IT video formats are always underscanned, but bit 7 of Byte 3 of the CTA-861 Extension header is set to overscanned.
EDID:
  CTA-861: Native progressive timings are a mix of several resolutions.

EDID conformity: FAIL

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

InfoFrame of '/sys/kernel/debug/dri/1/HDMI-A-1/infoframes/audio' was empty.

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

edid-decode InfoFrame (hex):

82 02 0d 31 12 28 04 00 00 00 00 00 00 00 00 00
00

----------------

HDMI InfoFrame Checksum: 0x31

AVI InfoFrame
  Version: 2
  Length: 13
  Y: Color Component Sample Format: RGB
  A: Active Format Information Present: Yes
  B: Bar Data Present: Bar Data not present
  S: Scan Information: Composed for an underscanned display
  C: Colorimetry: No Data
  M: Picture Aspect Ratio: 16:9
  R: Active Portion Aspect Ratio: 8
  ITC: IT Content: No Data
  EC: Extended Colorimetry: xvYCC601
  Q: RGB Quantization Range: Limited Range
  SC: Non-Uniform Picture Scaling: No Known non-uniform scaling
  YQ: YCC Quantization Range: Limited Range
  CN: IT Content Type: Graphics
  PR: Pixel Data Repetition Count: 0
  Line Number of End of Top Bar: 0
  Line Number of Start of Bottom Bar: 0
  Pixel Number of End of Left Bar: 0
  Pixel Number of Start of Right Bar: 0

----------------

AVI InfoFrame conformity: PASS

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

edid-decode InfoFrame (hex):

81 01 05 49 03 0c 00 20 01

----------------

HDMI InfoFrame Checksum: 0x49

Vendor-Specific InfoFrame (HDMI), OUI 00-0C-03
  Version: 1
  Length: 5
  HDMI Video Format: HDMI_VIC is present
  HDMI VIC 1:  3840x2160   30.000000 Hz  16:9     67.500 kHz    297.000000 MHz

----------------

Vendor-Specific InfoFrame (HDMI), OUI 00-0C-03 conformity: PASS

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

InfoFrame of '/sys/kernel/debug/dri/1/HDMI-A-1/infoframes/hdr_drm' was empty.

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

edid-decode InfoFrame (hex):

83 01 19 93 42 72 6f 61 64 63 6f 6d 56 69 64 65
6f 63 6f 72 65 00 00 00 00 00 00 00 09

----------------

HDMI InfoFrame Checksum: 0x93

Source Product Description InfoFrame
  Version: 1
  Length: 25
  Vendor Name: 'Broadcom'
  Product Description: 'Videocore'
  Source Information: PC general

----------------

Source Product Description InfoFrame conformity: PASS
```

**Testing**

The helpers have unit testing and can be tested using kunit with:

```bash
$ ./tools/testing/kunit/kunit.py run \
        --kunitconfig=drivers/gpu/drm/tests \
        drm_atomic_helper_connector_hdmi_*
```


<a id="rst-functions-reference"></a>

### Functions Reference


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

```c
void __drm_atomic_helper_connector_hdmi_reset(struct drm_connector *connector, struct drm_connector_state *new_conn_state)
```

Initializes all HDMI **drm_connector_state** resources

**Parameters**

- `struct drm_connector *connector`: DRM connector
- `struct drm_connector_state *new_conn_state`: connector state to reset

**Description**

Initializes all HDMI resources from a **drm_connector_state** without
actually allocating it. This is useful for HDMI drivers, in
combination with [`__drm_atomic_helper_connector_reset()`](#c-__drm_atomic_helper_connector_reset) or
[`drm_atomic_helper_connector_reset()`](#c-drm_atomic_helper_connector_reset).

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

```c
int drm_atomic_helper_connector_hdmi_check(struct drm_connector *connector, struct drm_atomic_state *state)
```

Helper to check HDMI connector atomic state

**Parameters**

- `struct drm_connector *connector`: DRM Connector
- `struct drm_atomic_state *state`: the DRM State object

**Description**

Provides a default connector state check handler for HDMI connectors.
Checks that a desired connector update is valid, and updates various
fields of derived state.

**Return**

Zero on success, or an errno code otherwise.

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

```c
enum drm_mode_status drm_hdmi_connector_mode_valid(struct drm_connector *connector, const struct drm_display_mode *mode)
```

Check if mode is valid for HDMI connector

**Parameters**

- `struct drm_connector *connector`: DRM connector to validate the mode
- `const struct drm_display_mode *mode`: Display mode to validate

**Description**

Generic .mode_valid implementation for HDMI connectors.

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

```c
int drm_atomic_helper_connector_hdmi_update_infoframes(struct drm_connector *connector, struct drm_atomic_state *state)
```

Update the Infoframes

**Parameters**

- `struct drm_connector *connector`: A pointer to the HDMI connector
- `struct drm_atomic_state *state`: The HDMI connector state to generate the infoframe from

**Description**

This function is meant for HDMI connector drivers to write their
infoframes. It will typically be used in a
**drm_connector_helper_funcs.atomic_enable** implementation.

**Return**

Zero on success, error code on failure.

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

```c
int drm_atomic_helper_connector_hdmi_update_audio_infoframe(struct drm_connector *connector, struct hdmi_audio_infoframe *frame)
```

Update the Audio Infoframe

**Parameters**

- `struct drm_connector *connector`: A pointer to the HDMI connector
- `struct hdmi_audio_infoframe *frame`: A pointer to the audio infoframe to write

**Description**

This function is meant for HDMI connector drivers to update their
audio infoframe. It will typically be used in one of the ALSA hooks
(most likely prepare).

**Return**

Zero on success, error code on failure.

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

```c
int drm_atomic_helper_connector_hdmi_clear_audio_infoframe(struct drm_connector *connector)
```

Stop sending the Audio Infoframe

**Parameters**

- `struct drm_connector *connector`: A pointer to the HDMI connector

**Description**

This function is meant for HDMI connector drivers to stop sending their
audio infoframe. It will typically be used in one of the ALSA hooks
(most likely shutdown).

**Return**

Zero on success, error code on failure.

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

```c
void drm_atomic_helper_connector_hdmi_hotplug(struct drm_connector *connector, enum drm_connector_status status)
```

Handle the hotplug event for the HDMI connector

**Parameters**

- `struct drm_connector *connector`: A pointer to the HDMI connector
- `enum drm_connector_status status`: Connection status

**Description**

This function should be called as a part of the .`detect()` / .`detect_ctx()`
callbacks for all status changes.

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

```c
void drm_atomic_helper_connector_hdmi_force(struct drm_connector *connector)
```

HDMI Connector implementation of the force callback

**Parameters**

- `struct drm_connector *connector`: A pointer to the HDMI connector

**Description**

This function implements the .`force()` callback for the HDMI connectors. It
can either be used directly as the callback or should be called from within
the .`force()` callback implementation to maintain the HDMI-specific
connector's data.


<a id="rst-hdcp-helper-functions-reference"></a>

## HDCP Helper Functions Reference


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

```c
int drm_hdcp_check_ksvs_revoked(struct drm_device *drm_dev, u8 *ksvs, u32 ksv_count)
```

Check the revoked status of the IDs

**Parameters**

- `struct drm_device *drm_dev`: drm_device for which HDCP revocation check is requested
- `u8 *ksvs`: List of KSVs (HDCP receiver IDs)
- `u32 ksv_count`: KSV count passed in through **ksvs**

**Description**

This function reads the HDCP System renewability Message(SRM Table)
from userspace as a firmware and parses it for the revoked HDCP
KSVs(Receiver IDs) detected by DCP LLC. Once the revoked KSVs are known,
revoked state of the KSVs in the list passed in by display drivers are
decided and response is sent.

SRM should be presented in the name of "display_hdcp_srm.bin".

Format of the SRM table, that userspace needs to write into the binary file,
is defined at:
1. Renewability chapter on 55th page of HDCP 1.4 specification
https://www.digital-cp.com/sites/default/files/specifications/HDCP`20Specification``20Rev1_4_Secure`.pdf
2. Renewability chapter on 63rd page of HDCP 2.2 specification
https://www.digital-cp.com/sites/default/files/specifications/HDCP`20on``20HDMI``20Specification``20Rev2_2_Final1`.pdf

**Return**

Count of the revoked KSVs or -ve error number in case of the failure.

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

```c
int drm_connector_attach_content_protection_property(struct drm_connector *connector, bool hdcp_content_type)
```

attach content protection property

**Parameters**

- `struct drm_connector *connector`: connector to attach CP property on.
- `bool hdcp_content_type`: is HDCP Content Type property needed for connector

**Description**

This is used to add support for content protection on select connectors.
Content Protection is intentionally vague to allow for different underlying
technologies, however it is most implemented by HDCP.

When hdcp_content_type is true enum property called HDCP Content Type is
created (if it is not already) and attached to the connector.

This property is used for sending the protected content's stream type
from userspace to kernel on selected connectors. Protected content provider
will decide their type of their content and declare the same to kernel.

Content type will be used during the HDCP 2.2 authentication.
Content type will be set to [`drm_connector_state.hdcp_content_type`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_connector_state).

The content protection will be set to [`drm_connector_state.content_protection`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_connector_state)

When kernel triggered content protection state change like DESIRED->ENABLED
and ENABLED->DESIRED, will use [`drm_hdcp_update_content_protection()`](#c-drm_hdcp_update_content_protection) to update
the content protection state of a connector.

**Return**

Zero on success, negative errno on failure.

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

```c
void drm_hdcp_update_content_protection(struct drm_connector *connector, u64 val)
```

Updates the content protection state of a connector

**Parameters**

- `struct drm_connector *connector`: drm_connector on which content protection state needs an update
- `u64 val`: New state of the content protection property

**Description**

This function can be used by display drivers, to update the kernel triggered
content protection state changes of a drm_connector such as DESIRED->ENABLED
and ENABLED->DESIRED. No uevent for DESIRED->UNDESIRED or ENABLED->UNDESIRED,
as userspace is triggering such state change and kernel performs it without
fail.This function update the new state of the property into the connector's
state and generate an uevent to notify the userspace.


<a id="rst-display-port-helper-functions-reference"></a>

## Display Port Helper Functions Reference


These functions contain some common logic and helpers at various abstraction
levels to deal with Display Port sink devices and related things like DP aux
channel transfers, EDID reading over DP aux channels, decoding certain DPCD
blocks, ...

The DisplayPort AUX channel is an abstraction to allow generic, driver-
independent access to AUX functionality. Drivers can take advantage of
this by filling in the fields of the drm_dp_aux structure.

Transactions are described using a hardware-independent drm_dp_aux_msg
structure, which is passed into a driver's .`transfer()` implementation.
Both native and I2C-over-AUX transactions are supported.



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

DP secondary data packet header

**Definition**

```c
struct dp_sdp_header {
    u8 HB0;
    u8 HB1;
    u8 HB2;
    u8 HB3;
};
```

**Members**

- `HB0`: Secondary Data Packet ID
- `HB1`: Secondary Data Packet Type
- `HB2`: Secondary Data Packet Specific header, Byte 0
- `HB3`: Secondary Data packet Specific header, Byte 1

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

DP secondary data packet

**Definition**

```c
struct dp_sdp {
    struct dp_sdp_header sdp_header;
    u8 db[32];
};
```

**Members**

- `sdp_header`: DP secondary data packet header
- `db`: DP secondaray data packet data blocks
  VSC SDP Payload for PSR
  db\[0\]: Stereo Interface
  db\[1\]: 0 - PSR State; 1 - Update RFB; 2 - CRC Valid
  db\[2\]: CRC value bits 7:0 of the R or Cr component
  db\[3\]: CRC value bits 15:8 of the R or Cr component
  db\[4\]: CRC value bits 7:0 of the G or Y component
  db\[5\]: CRC value bits 15:8 of the G or Y component
  db\[6\]: CRC value bits 7:0 of the B or Cb component
  db\[7\]: CRC value bits 15:8 of the B or Cb component
  db\[8\] - db\[31\]: Reserved
  VSC SDP Payload for Pixel Encoding/Colorimetry Format
  db\[0\] - db\[15\]: Reserved
  db\[16\]: Pixel Encoding and Colorimetry Formats
  db\[17\]: Dynamic Range and Component Bit Depth
  db\[18\]: Content Type
  db\[19\] - db\[31\]: Reserved

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

drm DP Pixel encoding formats

**Constants**

- `DP_PIXELFORMAT_RGB`: RGB pixel encoding format
- `DP_PIXELFORMAT_YUV444`: YCbCr 4:4:4 pixel encoding format
- `DP_PIXELFORMAT_YUV422`: YCbCr 4:2:2 pixel encoding format
- `DP_PIXELFORMAT_YUV420`: YCbCr 4:2:0 pixel encoding format
- `DP_PIXELFORMAT_Y_ONLY`: Y Only pixel encoding format
- `DP_PIXELFORMAT_RAW`: RAW pixel encoding format
- `DP_PIXELFORMAT_RESERVED`: Reserved pixel encoding format

**Description**

This enum is used to indicate DP VSC SDP Pixel encoding formats.
It is based on DP 1.4 spec \[Table 2-117: VSC SDP Payload for DB16 through
DB18\]

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

drm DP Colorimetry formats

**Constants**

- `DP_COLORIMETRY_DEFAULT`: sRGB (IEC 61966-2-1) or
  ITU-R BT.601 colorimetry format
- `DP_COLORIMETRY_RGB_WIDE_FIXED`: RGB wide gamut fixed point colorimetry format
- `DP_COLORIMETRY_BT709_YCC`: ITU-R BT.709 colorimetry format
- `DP_COLORIMETRY_RGB_WIDE_FLOAT`: RGB wide gamut floating point
  (scRGB (IEC 61966-2-2)) colorimetry format
- `DP_COLORIMETRY_XVYCC_601`: xvYCC601 colorimetry format
- `DP_COLORIMETRY_OPRGB`: OpRGB colorimetry format
- `DP_COLORIMETRY_XVYCC_709`: xvYCC709 colorimetry format
- `DP_COLORIMETRY_DCI_P3_RGB`: DCI-P3 (SMPTE RP 431-2) colorimetry format
- `DP_COLORIMETRY_SYCC_601`: sYCC601 colorimetry format
- `DP_COLORIMETRY_RGB_CUSTOM`: RGB Custom Color Profile colorimetry format
- `DP_COLORIMETRY_OPYCC_601`: opYCC601 colorimetry format
- `DP_COLORIMETRY_BT2020_RGB`: ITU-R BT.2020 R' G' B' colorimetry format
- `DP_COLORIMETRY_BT2020_CYCC`: ITU-R BT.2020 Y'c C'bc C'rc colorimetry format
- `DP_COLORIMETRY_BT2020_YCC`: ITU-R BT.2020 Y' C'b C'r colorimetry format

**Description**

This enum is used to indicate DP VSC SDP Colorimetry formats.
It is based on DP 1.4 spec \[Table 2-117: VSC SDP Payload for DB16 through
DB18\] and a name of enum member follows enum drm_colorimetry definition.

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

drm DP Dynamic Range

**Constants**

- `DP_DYNAMIC_RANGE_VESA`: VESA range
- `DP_DYNAMIC_RANGE_CTA`: CTA range

**Description**

This enum is used to indicate DP VSC SDP Dynamic Range.
It is based on DP 1.4 spec \[Table 2-117: VSC SDP Payload for DB16 through
DB18\]

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

drm DP Content Type

**Constants**

- `DP_CONTENT_TYPE_NOT_DEFINED`: Not defined type
- `DP_CONTENT_TYPE_GRAPHICS`: Graphics type
- `DP_CONTENT_TYPE_PHOTO`: Photo type
- `DP_CONTENT_TYPE_VIDEO`: Video type
- `DP_CONTENT_TYPE_GAME`: Game type

**Description**

This enum is used to indicate DP VSC SDP Content Types.
It is based on DP 1.4 spec \[Table 2-117: VSC SDP Payload for DB16 through
DB18\]
CTA-861-G defines content types and expected processing by a sink device



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

drm DP VSC SDP

**Definition**

```c
struct drm_dp_vsc_sdp {
    unsigned char sdp_type;
    unsigned char revision;
    unsigned char length;
    enum dp_pixelformat pixelformat;
    enum dp_colorimetry colorimetry;
    int bpc;
    enum dp_dynamic_range dynamic_range;
    enum dp_content_type content_type;
};
```

**Members**

- `sdp_type`: secondary-data packet type
- `revision`: revision number
- `length`: number of valid data bytes
- `pixelformat`: pixel encoding format
- `colorimetry`: colorimetry format
- `bpc`: bit per color
- `dynamic_range`: dynamic range information
- `content_type`: CTA-861-G defines content types and expected processing by a sink device

**Description**

This structure represents a DP VSC SDP of drm
It is based on DP 1.4 spec \[Table 2-116: VSC SDP Header Bytes\] and
\[Table 2-117: VSC SDP Payload for DB16 through DB18\]

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

drm DP Adaptive Sync SDP

**Definition**

```c
struct drm_dp_as_sdp {
    unsigned char sdp_type;
    unsigned char revision;
    unsigned char length;
    int vtotal;
    int target_rr;
    int duration_incr_ms;
    int duration_decr_ms;
    bool target_rr_divider;
    enum operation_mode mode;
};
```

**Members**

- `sdp_type`: Secondary-data packet type
- `revision`: Revision Number
- `length`: Number of valid data bytes
- `vtotal`: Minimum Vertical Vtotal
- `target_rr`: Target Refresh
- `duration_incr_ms`: Successive frame duration increase
- `duration_decr_ms`: Successive frame duration decrease
- `target_rr_divider`: Target refresh rate divider
- `mode`: Adaptive Sync Operation Mode

**Description**

This structure represents a DP AS SDP of drm
It is based on DP 2.1 spec \[Table 2-126:  Adaptive-Sync SDP Header Bytes\] and
\[Table 2-127: Adaptive-Sync SDP Payload for DB0 through DB8\]

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

```c
bool drm_dp_dsc_sink_supports_format(const u8 dsc_dpcd[DP_DSC_RECEIVER_CAP_SIZE], u8 output_format)
```

check if sink supports DSC with given output format

**Parameters**

- `const u8 dsc_dpcd[DP_DSC_RECEIVER_CAP_SIZE]`: DSC-capability DPCDs of the sink
- `u8 output_format`: output_format which is to be checked

**Description**

Returns true if the sink supports DSC with the given output_format, false otherwise.

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

```c
bool drm_edp_backlight_supported(const u8 edp_dpcd[EDP_DISPLAY_CTL_CAP_SIZE])
```

Check an eDP DPCD for VESA backlight support

**Parameters**

- `const u8 edp_dpcd[EDP_DISPLAY_CTL_CAP_SIZE]`: The DPCD to check

**Description**

Note that currently this function will return `false` for panels which support various DPCD
backlight features but which require the brightness be set through PWM, and don't support setting
the brightness level via the DPCD.

**Return**

`True` if **edp_dpcd** indicates that VESA backlight controls are supported, `false`
otherwise

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

```c
bool drm_dp_is_uhbr_rate(int link_rate)
```

Determine if a link rate is UHBR

**Parameters**

- `int link_rate`: link rate in 10kbits/s units

**Description**

Determine if the provided link rate is an UHBR rate.

**Return**

`True` if **link_rate** is an UHBR rate.

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

DisplayPort AUX channel transaction

**Definition**

```c
struct drm_dp_aux_msg {
    unsigned int address;
    u8 request;
    u8 reply;
    void *buffer;
    size_t size;
};
```

**Members**

- `address`: address of the (first) register to access
- `request`: contains the type of transaction (see DP_AUX_* macros)
- `reply`: upon completion, contains the reply type of the transaction
- `buffer`: pointer to a transmission or reception buffer
- `size`: size of **buffer**

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

DisplayPort CEC-Tunneling-over-AUX

**Definition**

```c
struct drm_dp_aux_cec {
    struct mutex lock;
    struct cec_adapter *adap;
    struct drm_connector *connector;
    struct delayed_work unregister_work;
};
```

**Members**

- `lock`: mutex protecting this struct
- `adap`: the CEC adapter for CEC-Tunneling-over-AUX support.
- `connector`: the connector this CEC adapter is associated with
- `unregister_work`: unregister the CEC adapter

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

DisplayPort AUX channel

**Definition**

```c
struct drm_dp_aux {
    const char *name;
    struct i2c_adapter ddc;
    struct device *dev;
    struct drm_device *drm_dev;
    struct drm_crtc *crtc;
    struct mutex hw_mutex;
    struct work_struct crc_work;
    u8 crc_count;
    ssize_t (*transfer)(struct drm_dp_aux *aux, struct drm_dp_aux_msg *msg);
    int (*wait_hpd_asserted)(struct drm_dp_aux *aux, unsigned long wait_us);
    unsigned i2c_nack_count;
    unsigned i2c_defer_count;
    struct drm_dp_aux_cec cec;
    bool is_remote;
    bool powered_down;
    bool no_zero_sized;
    bool dpcd_probe_disabled;
};
```

**Members**

- `name`: user-visible name of this AUX channel and the
  I2C-over-AUX adapter.

  It's also used to specify the name of the I2C adapter. If set
  to `NULL`, [`dev_name()`](/kernel/hardware/driver-api/fundamentals/infrastructure.md#c-dev_name) of **dev** will be used.
- `ddc`: I2C adapter that can be used for I2C-over-AUX
  communication
- `dev`: pointer to struct device that is the parent for this
  AUX channel.
- `drm_dev`: pointer to the [`drm_device`](/kernel/hardware/gpu/drm-internals.md#c-struct-drm_device) that owns this AUX channel.
  Beware, this may be `NULL` before [`drm_dp_aux_register()`](#c-drm_dp_aux_register) has been
  called.

  It should be set to the [`drm_device`](/kernel/hardware/gpu/drm-internals.md#c-struct-drm_device) that will be using this AUX
  channel as early as possible. For many graphics drivers this should
  happen before [`drm_dp_aux_init()`](#c-drm_dp_aux_init), however it's perfectly fine to set
  this field later so long as it's assigned before calling
  [`drm_dp_aux_register()`](#c-drm_dp_aux_register).
- `crtc`: backpointer to the crtc that is currently using this
  AUX channel
- `hw_mutex`: internal mutex used for locking transfers.

  Note that if the underlying hardware is shared among multiple
  channels, the driver needs to do additional locking to
  prevent concurrent access.
- `crc_work`: worker that captures CRCs for each frame
- `crc_count`: counter of captured frame CRCs
- `transfer`: transfers a message representing a single AUX
  transaction.

  This is a hardware-specific implementation of how
  transactions are executed that the drivers must provide.

  A pointer to a [`drm_dp_aux_msg`](#c-struct-drm_dp_aux_msg) structure describing the
  transaction is passed into this function. Upon success, the
  implementation should return the number of payload bytes that
  were transferred, or a negative error-code on failure.

  Helpers will propagate these errors, with the exception of
  the `-EBUSY` error, which causes a transaction to be retried.
  On a short, helpers will return `-EPROTO` to make it simpler
  to check for failure.

  The **transfer()** function must only modify the reply field of
  the [`drm_dp_aux_msg`](#c-struct-drm_dp_aux_msg) structure. The retry logic and i2c
  helpers assume this is the case.

  Also note that this callback can be called no matter the
  state **dev** is in and also no matter what state the panel is
  in. It's expected:

  - If the **dev** providing the AUX bus is currently unpowered then
    it will power itself up for the transfer.

  - If we're on eDP (using a drm_panel) and the panel is not in a
    state where it can respond (it's not powered or it's in a
    low power state) then this function may return an error, but
    not crash. It's up to the caller of this code to make sure that
    the panel is powered on if getting an error back is not OK. If a
    drm_panel driver is initiating a DP AUX transfer it may power
    itself up however it wants. All other code should ensure that
    the `pre_enable()` bridge chain (which eventually calls the
    drm_panel prepare function) has powered the panel.
- `wait_hpd_asserted`: wait for HPD to be asserted

  This is mainly useful for eDP panels drivers to wait for an eDP
  panel to finish powering on. It is optional for DP AUX controllers
  to implement this function. It is required for DP AUX endpoints
  (panel drivers) to call this function after powering up but before
  doing AUX transfers unless the DP AUX endpoint driver knows that
  we're not using the AUX controller's HPD. One example of the panel
  driver not needing to call this is if HPD is hooked up to a GPIO
  that the panel driver can read directly.

  If a DP AUX controller does not implement this function then it
  may still support eDP panels that use the AUX controller's built-in
  HPD signal by implementing a long wait for HPD in the `transfer()`
  callback, though this is deprecated.

  This function will efficiently wait for the HPD signal to be
  asserted. The `wait_us` parameter that is passed in says that we
  know that the HPD signal is expected to be asserted within `wait_us`
  microseconds. This function could wait for longer than `wait_us` if
  the logic in the DP controller has a long debouncing time. The
  important thing is that if this function returns success that the
  DP controller is ready to send AUX transactions.

  This function returns 0 if HPD was asserted or -ETIMEDOUT if time
  expired and HPD wasn't asserted. This function should not print
  timeout errors to the log.

  The semantics of this function are designed to match the
  `readx_poll_timeout()` function. That means a `wait_us` of 0 means
  to wait forever. Like `readx_poll_timeout()`, this function may sleep.

  NOTE: this function specifically reports the state of the HPD pin
  that's associated with the DP AUX channel. This is different from
  the HPD concept in much of the rest of DRM which is more about
  physical presence of a display. For eDP, for instance, a display is
  assumed always present even if the HPD pin is deasserted.
- `i2c_nack_count`: Counts I2C NACKs, used for DP validation.
- `i2c_defer_count`: Counts I2C DEFERs, used for DP validation.
- `cec`: struct containing fields used for CEC-Tunneling-over-AUX.
- `is_remote`: Is this AUX CH actually using sideband messaging.
- `powered_down`: If true then the remote endpoint is powered down.
- `no_zero_sized`: If the hw can't use zero sized transfers (NVIDIA)
- `dpcd_probe_disabled`: If probing before a DPCD access is disabled.

**Description**

An AUX channel can also be used to transport I2C messages to a sink. A
typical application of that is to access an EDID that's present in the sink
device. The **transfer()** function can also be used to execute such
transactions. The [`drm_dp_aux_register()`](#c-drm_dp_aux_register) function registers an I2C adapter
that can be passed to [`drm_probe_ddc()`](#c-drm_probe_ddc). Upon removal, drivers should call
[`drm_dp_aux_unregister()`](#c-drm_dp_aux_unregister) to remove the I2C adapter. The I2C adapter uses long
transfers by default; if a partial response is received, the adapter will
drop down to the size given by the partial response for this transaction
only.

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

```c
ssize_t drm_dp_dpcd_readb(struct drm_dp_aux *aux, unsigned int offset, u8 *valuep)
```

read a single byte from the DPCD

**Parameters**

- `struct drm_dp_aux *aux`: DisplayPort AUX channel
- `unsigned int offset`: address of the register to read
- `u8 *valuep`: location where the value of the register will be stored

**Description**

Returns the number of bytes transferred (1) on success, or a negative
error code on failure. In most of the cases you should be using
[`drm_dp_dpcd_read_byte()`](#c-drm_dp_dpcd_read_byte) instead.

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

```c
int drm_dp_dpcd_read_data(struct drm_dp_aux *aux, unsigned int offset, void *buffer, size_t size)
```

read a series of bytes from the DPCD

**Parameters**

- `struct drm_dp_aux *aux`: DisplayPort AUX channel (SST or MST)
- `unsigned int offset`: address of the (first) register to read
- `void *buffer`: buffer to store the register values
- `size_t size`: number of bytes in **buffer**

**Description**

Returns zero (0) on success, or a negative error
code on failure. -EIO is returned if the request was NAKed by the sink or
if the retry count was exceeded. If not all bytes were transferred, this
function returns -EPROTO. Errors from the underlying AUX channel transfer
function, with the exception of -EBUSY (which causes the transaction to
be retried), are propagated to the caller.

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

```c
int drm_dp_dpcd_write_data(struct drm_dp_aux *aux, unsigned int offset, void *buffer, size_t size)
```

write a series of bytes to the DPCD

**Parameters**

- `struct drm_dp_aux *aux`: DisplayPort AUX channel (SST or MST)
- `unsigned int offset`: address of the (first) register to write
- `void *buffer`: buffer containing the values to write
- `size_t size`: number of bytes in **buffer**

**Description**

Returns zero (0) on success, or a negative error
code on failure. -EIO is returned if the request was NAKed by the sink or
if the retry count was exceeded. If not all bytes were transferred, this
function returns -EPROTO. Errors from the underlying AUX channel transfer
function, with the exception of -EBUSY (which causes the transaction to
be retried), are propagated to the caller.

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

```c
ssize_t drm_dp_dpcd_writeb(struct drm_dp_aux *aux, unsigned int offset, u8 value)
```

write a single byte to the DPCD

**Parameters**

- `struct drm_dp_aux *aux`: DisplayPort AUX channel
- `unsigned int offset`: address of the register to write
- `u8 value`: value to write to the register

**Description**

Returns the number of bytes transferred (1) on success, or a negative
error code on failure. In most of the cases you should be using
[`drm_dp_dpcd_write_byte()`](#c-drm_dp_dpcd_write_byte) instead.

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

```c
int drm_dp_dpcd_read_byte(struct drm_dp_aux *aux, unsigned int offset, u8 *valuep)
```

read a single byte from the DPCD

**Parameters**

- `struct drm_dp_aux *aux`: DisplayPort AUX channel
- `unsigned int offset`: address of the register to read
- `u8 *valuep`: location where the value of the register will be stored

**Description**

Returns zero (0) on success, or a negative error code on failure.

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

```c
int drm_dp_dpcd_write_byte(struct drm_dp_aux *aux, unsigned int offset, u8 value)
```

write a single byte to the DPCD

**Parameters**

- `struct drm_dp_aux *aux`: DisplayPort AUX channel
- `unsigned int offset`: address of the register to write
- `u8 value`: value to write to the register

**Description**

Returns zero (0) on success, or a negative error code on failure.

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

DP branch/sink device descriptor

**Definition**

```c
struct drm_dp_desc {
    struct drm_dp_dpcd_ident ident;
    u32 quirks;
};
```

**Members**

- `ident`: DP device identification from DPCD 0x400 (sink) or 0x500 (branch).
- `quirks`: Quirks; use [`drm_dp_has_quirk()`](#c-drm_dp_has_quirk) to query for the quirks.

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

Display Port sink/branch device specific quirks

**Constants**

- `DP_DPCD_QUIRK_CONSTANT_N`: The device requires main link attributes Mvid and Nvid to be limited
  to 16 bits. So will give a constant value (0x8000) for compatability.
- `DP_DPCD_QUIRK_NO_PSR`: The device does not support PSR even if reports that it supports or
  driver still need to implement proper handling for such device.
- `DP_DPCD_QUIRK_NO_SINK_COUNT`: The device does not set SINK_COUNT to a non-zero value.
  The driver should ignore SINK_COUNT during detection. Note that
  [`drm_dp_read_sink_count_cap()`](#c-drm_dp_read_sink_count_cap) automatically checks for this quirk.
- `DP_DPCD_QUIRK_DSC_WITHOUT_VIRTUAL_DPCD`: The device supports MST DSC despite not supporting Virtual DPCD.
  The DSC caps can be read from the physical aux instead.
- `DP_DPCD_QUIRK_CAN_DO_MAX_LINK_RATE_3_24_GBPS`: The device supports a link rate of 3.24 Gbps (multiplier 0xc) despite
  the DP_MAX_LINK_RATE register reporting a lower max multiplier.
- `DP_DPCD_QUIRK_HBLANK_EXPANSION_REQUIRES_DSC`: The device applies HBLANK expansion for some modes, but this
  requires enabling DSC.
- `DP_DPCD_QUIRK_DSC_THROUGHPUT_BPP_LIMIT`: The device doesn't support DSC decompression at the maximum DSC
  pixel throughput and compressed bpp it indicates via its DPCD DSC
  capabilities. The compressed bpp must be limited above a device
  specific DSC pixel throughput.

**Description**

Display Port sink and branch devices in the wild have a variety of bugs, try
to collect them here. The quirks are shared, but it's up to the drivers to
implement workarounds for them.

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

```c
bool drm_dp_has_quirk(const struct drm_dp_desc *desc, enum drm_dp_quirk quirk)
```

does the DP device have a specific quirk

**Parameters**

- `const struct drm_dp_desc *desc`: Device descriptor filled by [`drm_dp_read_desc()`](#c-drm_dp_read_desc)
- `enum drm_dp_quirk quirk`: Quirk to query for

**Description**

Return true if DP device identified by **desc** has **quirk**.

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

Probed eDP backlight info struct

**Definition**

```c
struct drm_edp_backlight_info {
    u8 pwmgen_bit_count;
    u8 pwm_freq_pre_divider;
    u32 max;
    bool lsb_reg_used : 1;
    bool aux_enable : 1;
    bool aux_set : 1;
    bool luminance_set : 1;
};
```

**Members**

- `pwmgen_bit_count`: The pwmgen bit count
- `pwm_freq_pre_divider`: The PWM frequency pre-divider value being used for this backlight, if any
- `max`: The maximum backlight level that may be set
- `lsb_reg_used`: Do we also write values to the DP_EDP_BACKLIGHT_BRIGHTNESS_LSB register?
- `aux_enable`: Does the panel support the AUX enable cap?
- `aux_set`: Does the panel support setting the brightness through AUX?
- `luminance_set`: Does the panel support setting the brightness through AUX using luminance values?

**Description**

This structure contains various data about an eDP backlight, which can be populated by using
[`drm_edp_backlight_init()`](#c-drm_edp_backlight_init).

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

DP Phy Compliance parameters

**Definition**

```c
struct drm_dp_phy_test_params {
    int link_rate;
    u8 num_lanes;
    u8 phy_pattern;
    u8 hbr2_reset[2];
    u8 custom80[10];
    bool enhanced_frame_cap;
};
```

**Members**

- `link_rate`: Requested Link rate from DPCD 0x219
- `num_lanes`: Number of lanes requested by sing through DPCD 0x220
- `phy_pattern`: DP Phy test pattern from DPCD 0x248
- `hbr2_reset`: DP HBR2_COMPLIANCE_SCRAMBLER_RESET from DCPD 0x24A and 0x24B
- `custom80`: DP Test_80BIT_CUSTOM_PATTERN from DPCDs 0x250 through 0x259
- `enhanced_frame_cap`: flag for enhanced frame capability.



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

```c
const char * drm_dp_phy_name(enum drm_dp_phy dp_phy)
```

Get the name of the given DP PHY

**Parameters**

- `enum drm_dp_phy dp_phy`: The DP PHY identifier

**Description**

Given the **dp_phy**, get a user friendly name of the DP PHY, either "DPRX" or
"LTTPR \<N>", or "\<INVALID DP PHY>" on errors. The returned string is always
non-NULL and valid.

**Return**

Name of the DP PHY.

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

```c
void drm_dp_lttpr_wake_timeout_setup(struct drm_dp_aux *aux, bool transparent_mode)
```

Grant extended time for sink to wake up

**Parameters**

- `struct drm_dp_aux *aux`: The DP AUX channel to use
- `bool transparent_mode`: This is true if lttpr is in transparent mode

**Description**

This function checks if the sink needs any extended wake time, if it does
it grants this request. Post this setup the source device can keep trying
the Aux transaction till the granted wake timeout.
If this function is not called all Aux transactions are expected to take
a default of 1ms before they throw an error.

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

```c
int drm_dp_dpcd_probe(struct drm_dp_aux *aux, unsigned int offset)
```

probe a given DPCD address with a 1-byte read access

**Parameters**

- `struct drm_dp_aux *aux`: DisplayPort AUX channel (SST)
- `unsigned int offset`: address of the register to probe

**Description**

Probe the provided DPCD address by reading 1 byte from it. The function can
be used to trigger some side-effect the read access has, like waking up the
sink, without the need for the read-out value.

Returns 0 if the read access suceeded, or a negative error code on failure.

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

```c
void drm_dp_dpcd_set_powered(struct drm_dp_aux *aux, bool powered)
```

Set whether the DP device is powered

**Parameters**

- `struct drm_dp_aux *aux`: DisplayPort AUX channel; for convenience it's OK to pass NULL here
  and the function will be a no-op.
- `bool powered`: true if powered; false if not

**Description**

If the endpoint device on the DP AUX bus is known to be powered down
then this function can be called to make future transfers fail immediately
instead of needing to time out.

If this function is never called then a device defaults to being powered.

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

```c
void drm_dp_dpcd_set_probe(struct drm_dp_aux *aux, bool enable)
```

Set whether a probing before DPCD access is done

**Parameters**

- `struct drm_dp_aux *aux`: DisplayPort AUX channel
- `bool enable`: Enable the probing if required

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

```c
ssize_t drm_dp_dpcd_read(struct drm_dp_aux *aux, unsigned int offset, void *buffer, size_t size)
```

read a series of bytes from the DPCD

**Parameters**

- `struct drm_dp_aux *aux`: DisplayPort AUX channel (SST or MST)
- `unsigned int offset`: address of the (first) register to read
- `void *buffer`: buffer to store the register values
- `size_t size`: number of bytes in **buffer**

**Description**

Returns the number of bytes transferred on success, or a negative error
code on failure. -EIO is returned if the request was NAKed by the sink or
if the retry count was exceeded. If not all bytes were transferred, this
function returns -EPROTO. Errors from the underlying AUX channel transfer
function, with the exception of -EBUSY (which causes the transaction to
be retried), are propagated to the caller.

In most of the cases you want to use [`drm_dp_dpcd_read_data()`](#c-drm_dp_dpcd_read_data) instead.

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

```c
ssize_t drm_dp_dpcd_write(struct drm_dp_aux *aux, unsigned int offset, void *buffer, size_t size)
```

write a series of bytes to the DPCD

**Parameters**

- `struct drm_dp_aux *aux`: DisplayPort AUX channel (SST or MST)
- `unsigned int offset`: address of the (first) register to write
- `void *buffer`: buffer containing the values to write
- `size_t size`: number of bytes in **buffer**

**Description**

Returns the number of bytes transferred on success, or a negative error
code on failure. -EIO is returned if the request was NAKed by the sink or
if the retry count was exceeded. If not all bytes were transferred, this
function returns -EPROTO. Errors from the underlying AUX channel transfer
function, with the exception of -EBUSY (which causes the transaction to
be retried), are propagated to the caller.

In most of the cases you want to use [`drm_dp_dpcd_write_data()`](#c-drm_dp_dpcd_write_data) instead.

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

```c
int drm_dp_dpcd_read_link_status(struct drm_dp_aux *aux, u8 status[DP_LINK_STATUS_SIZE])
```

read DPCD link status (bytes 0x202-0x207)

**Parameters**

- `struct drm_dp_aux *aux`: DisplayPort AUX channel
- `u8 status[DP_LINK_STATUS_SIZE]`: buffer to store the link status in (must be at least 6 bytes)

**Description**

Returns a negative error code on failure or 0 on success.

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

```c
int drm_dp_dpcd_read_phy_link_status(struct drm_dp_aux *aux, enum drm_dp_phy dp_phy, u8 link_status[DP_LINK_STATUS_SIZE])
```

get the link status information for a DP PHY

**Parameters**

- `struct drm_dp_aux *aux`: DisplayPort AUX channel
- `enum drm_dp_phy dp_phy`: the DP PHY to get the link status for
- `u8 link_status[DP_LINK_STATUS_SIZE]`: buffer to return the status in

**Description**

Fetch the AUX DPCD registers for the DPRX or an LTTPR PHY link status. The
layout of the returned **link_status** matches the DPCD register layout of the
DPRX PHY link status.

Returns 0 if the information was read successfully or a negative error code
on failure.

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

```c
int drm_dp_link_power_up(struct drm_dp_aux *aux, unsigned char revision)
```

power up a DisplayPort link

**Parameters**

- `struct drm_dp_aux *aux`: DisplayPort AUX channel
- `unsigned char revision`: DPCD revision supported on the link

**Description**

Returns 0 on success or a negative error code on failure.

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

```c
int drm_dp_link_power_down(struct drm_dp_aux *aux, unsigned char revision)
```

power down a DisplayPort link

**Parameters**

- `struct drm_dp_aux *aux`: DisplayPort AUX channel
- `unsigned char revision`: DPCD revision supported on the link

**Description**

Returns 0 on success or a negative error code on failure.

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

```c
int drm_dp_dpcd_write_payload(struct drm_dp_aux *aux, int vcpid, u8 start_time_slot, u8 time_slot_count)
```

Write Virtual Channel information to payload table

**Parameters**

- `struct drm_dp_aux *aux`: DisplayPort AUX channel
- `int vcpid`: Virtual Channel Payload ID
- `u8 start_time_slot`: Starting time slot
- `u8 time_slot_count`: Time slot count

**Description**

Write the Virtual Channel payload allocation table, checking the payload
update status and retrying as necessary.

**Return**

0 on success, negative error otherwise

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

```c
int drm_dp_dpcd_clear_payload(struct drm_dp_aux *aux)
```

Clear the entire VC Payload ID table

**Parameters**

- `struct drm_dp_aux *aux`: DisplayPort AUX channel

**Description**

Clear the entire VC Payload ID table.

**Return**

0 on success, negative error code on errors.

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

```c
int drm_dp_dpcd_poll_act_handled(struct drm_dp_aux *aux, int timeout_ms)
```

Poll for ACT handled status

**Parameters**

- `struct drm_dp_aux *aux`: DisplayPort AUX channel
- `int timeout_ms`: Timeout in ms

**Description**

Try waiting for the sink to finish updating its payload table by polling for
the ACT handled bit of DP_PAYLOAD_TABLE_UPDATE_STATUS for up to **timeout_ms**
milliseconds, defaulting to 3000 ms if 0.

**Return**

0 if the ACT was handled in time, negative error code on failure.

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

```c
bool drm_dp_downstream_is_type(const u8 dpcd[DP_RECEIVER_CAP_SIZE], const u8 port_cap[4], u8 type)
```

is the downstream facing port of certain type?

**Parameters**

- `const u8 dpcd[DP_RECEIVER_CAP_SIZE]`: DisplayPort configuration data
- `const u8 port_cap[4]`: port capabilities
- `u8 type`: port type to be checked. Can be:
  `DP_DS_PORT_TYPE_DP`, `DP_DS_PORT_TYPE_VGA`, `DP_DS_PORT_TYPE_DVI`,
  `DP_DS_PORT_TYPE_HDMI`, `DP_DS_PORT_TYPE_NON_EDID`,
  `DP_DS_PORT_TYPE_DP_DUALMODE` or `DP_DS_PORT_TYPE_WIRELESS`.

**Description**

Caveat: Only works with DPCD 1.1+ port caps.

**Return**

whether the downstream facing port matches the type.

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

```c
bool drm_dp_downstream_is_tmds(const u8 dpcd[DP_RECEIVER_CAP_SIZE], const u8 port_cap[4], const struct drm_edid *drm_edid)
```

is the downstream facing port TMDS?

**Parameters**

- `const u8 dpcd[DP_RECEIVER_CAP_SIZE]`: DisplayPort configuration data
- `const u8 port_cap[4]`: port capabilities
- `const struct drm_edid *drm_edid`: EDID

**Return**

whether the downstream facing port is TMDS (HDMI/DVI).

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

```c
bool drm_dp_send_real_edid_checksum(struct drm_dp_aux *aux, u8 real_edid_checksum)
```

send back real edid checksum value

**Parameters**

- `struct drm_dp_aux *aux`: DisplayPort AUX channel
- `u8 real_edid_checksum`: real edid checksum for the last block

**Return**

True on success

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

```c
int drm_dp_read_dpcd_caps(struct drm_dp_aux *aux, u8 dpcd[DP_RECEIVER_CAP_SIZE])
```

read DPCD caps and extended DPCD caps if available

**Parameters**

- `struct drm_dp_aux *aux`: DisplayPort AUX channel
- `u8 dpcd[DP_RECEIVER_CAP_SIZE]`: Buffer to store the resulting DPCD in

**Description**

Attempts to read the base DPCD caps for **aux**. Additionally, this function
checks for and reads the extended DPRX caps (`DP_DP13_DPCD_REV`) if
present.

**Return**

`0` if the DPCD was read successfully, negative error code
otherwise.

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

```c
int drm_dp_read_downstream_info(struct drm_dp_aux *aux, const u8 dpcd[DP_RECEIVER_CAP_SIZE], u8 downstream_ports[DP_MAX_DOWNSTREAM_PORTS])
```

read DPCD downstream port info if available

**Parameters**

- `struct drm_dp_aux *aux`: DisplayPort AUX channel
- `const u8 dpcd[DP_RECEIVER_CAP_SIZE]`: A cached copy of the port's DPCD
- `u8 downstream_ports[DP_MAX_DOWNSTREAM_PORTS]`: buffer to store the downstream port info in

**Description**

See also:
`drm_dp_downstream_max_clock()`
[`drm_dp_downstream_max_bpc()`](#c-drm_dp_downstream_max_bpc)

**Return**

0 if either the downstream port info was read successfully or
there was no downstream info to read, or a negative error code otherwise.

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

```c
int drm_dp_downstream_max_dotclock(const u8 dpcd[DP_RECEIVER_CAP_SIZE], const u8 port_cap[4])
```

extract downstream facing port max dot clock

**Parameters**

- `const u8 dpcd[DP_RECEIVER_CAP_SIZE]`: DisplayPort configuration data
- `const u8 port_cap[4]`: port capabilities

**Return**

Downstream facing port max dot clock in kHz on success,
or 0 if max clock not defined

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

```c
int drm_dp_downstream_max_tmds_clock(const u8 dpcd[DP_RECEIVER_CAP_SIZE], const u8 port_cap[4], const struct drm_edid *drm_edid)
```

extract downstream facing port max TMDS clock

**Parameters**

- `const u8 dpcd[DP_RECEIVER_CAP_SIZE]`: DisplayPort configuration data
- `const u8 port_cap[4]`: port capabilities
- `const struct drm_edid *drm_edid`: EDID

**Return**

HDMI/DVI downstream facing port max TMDS clock in kHz on success,
or 0 if max TMDS clock not defined

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

```c
int drm_dp_downstream_min_tmds_clock(const u8 dpcd[DP_RECEIVER_CAP_SIZE], const u8 port_cap[4], const struct drm_edid *drm_edid)
```

extract downstream facing port min TMDS clock

**Parameters**

- `const u8 dpcd[DP_RECEIVER_CAP_SIZE]`: DisplayPort configuration data
- `const u8 port_cap[4]`: port capabilities
- `const struct drm_edid *drm_edid`: EDID

**Return**

HDMI/DVI downstream facing port min TMDS clock in kHz on success,
or 0 if max TMDS clock not defined

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

```c
int drm_dp_downstream_max_bpc(const u8 dpcd[DP_RECEIVER_CAP_SIZE], const u8 port_cap[4], const struct drm_edid *drm_edid)
```

extract downstream facing port max bits per component

**Parameters**

- `const u8 dpcd[DP_RECEIVER_CAP_SIZE]`: DisplayPort configuration data
- `const u8 port_cap[4]`: downstream facing port capabilities
- `const struct drm_edid *drm_edid`: EDID

**Return**

Max bpc on success or 0 if max bpc not defined

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

```c
bool drm_dp_downstream_420_passthrough(const u8 dpcd[DP_RECEIVER_CAP_SIZE], const u8 port_cap[4])
```

determine downstream facing port YCbCr 4:2:0 pass-through capability

**Parameters**

- `const u8 dpcd[DP_RECEIVER_CAP_SIZE]`: DisplayPort configuration data
- `const u8 port_cap[4]`: downstream facing port capabilities

**Return**

whether the downstream facing port can pass through YCbCr 4:2:0

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

```c
bool drm_dp_downstream_444_to_420_conversion(const u8 dpcd[DP_RECEIVER_CAP_SIZE], const u8 port_cap[4])
```

determine downstream facing port YCbCr 4:4:4->4:2:0 conversion capability

**Parameters**

- `const u8 dpcd[DP_RECEIVER_CAP_SIZE]`: DisplayPort configuration data
- `const u8 port_cap[4]`: downstream facing port capabilities

**Return**

whether the downstream facing port can convert YCbCr 4:4:4 to 4:2:0

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

```c
bool drm_dp_downstream_rgb_to_ycbcr_conversion(const u8 dpcd[DP_RECEIVER_CAP_SIZE], const u8 port_cap[4], u8 color_spc)
```

determine downstream facing port RGB->YCbCr conversion capability

**Parameters**

- `const u8 dpcd[DP_RECEIVER_CAP_SIZE]`: DisplayPort configuration data
- `const u8 port_cap[4]`: downstream facing port capabilities
- `u8 color_spc`: Colorspace for which conversion cap is sought

**Return**

whether the downstream facing port can convert RGB->YCbCr for a given
colorspace.

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

```c
struct drm_display_mode * drm_dp_downstream_mode(struct drm_device *dev, const u8 dpcd[DP_RECEIVER_CAP_SIZE], const u8 port_cap[4])
```

return a mode for downstream facing port

**Parameters**

- `struct drm_device *dev`: DRM device
- `const u8 dpcd[DP_RECEIVER_CAP_SIZE]`: DisplayPort configuration data
- `const u8 port_cap[4]`: port capabilities

**Description**

Provides a suitable mode for downstream facing ports without EDID.

**Return**

A new drm_display_mode on success or NULL on failure

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

```c
int drm_dp_downstream_id(struct drm_dp_aux *aux, char id[6])
```

identify branch device

**Parameters**

- `struct drm_dp_aux *aux`: DisplayPort AUX channel
- `char id[6]`: DisplayPort branch device id

**Description**

Returns branch device id on success or NULL on failure

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

```c
void drm_dp_downstream_debug(struct seq_file *m, const u8 dpcd[DP_RECEIVER_CAP_SIZE], const u8 port_cap[4], const struct drm_edid *drm_edid, struct drm_dp_aux *aux)
```

debug DP branch devices

**Parameters**

- `struct seq_file *m`: pointer for debugfs file
- `const u8 dpcd[DP_RECEIVER_CAP_SIZE]`: DisplayPort configuration data
- `const u8 port_cap[4]`: port capabilities
- `const struct drm_edid *drm_edid`: EDID
- `struct drm_dp_aux *aux`: DisplayPort AUX channel

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

```c
enum drm_mode_subconnector drm_dp_subconnector_type(const u8 dpcd[DP_RECEIVER_CAP_SIZE], const u8 port_cap[4])
```

get DP branch device type

**Parameters**

- `const u8 dpcd[DP_RECEIVER_CAP_SIZE]`: DisplayPort configuration data
- `const u8 port_cap[4]`: port capabilities

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

```c
void drm_dp_set_subconnector_property(struct drm_connector *connector, enum drm_connector_status status, const u8 *dpcd, const u8 port_cap[4])
```

set subconnector for DP connector

**Parameters**

- `struct drm_connector *connector`: connector to set property on
- `enum drm_connector_status status`: connector status
- `const u8 *dpcd`: DisplayPort configuration data
- `const u8 port_cap[4]`: port capabilities

**Description**

Called by a driver on every detect event.

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

```c
bool drm_dp_read_sink_count_cap(struct drm_connector *connector, const u8 dpcd[DP_RECEIVER_CAP_SIZE], const struct drm_dp_desc *desc)
```

Check whether a given connector has a valid sink count

**Parameters**

- `struct drm_connector *connector`: The DRM connector to check
- `const u8 dpcd[DP_RECEIVER_CAP_SIZE]`: A cached copy of the connector's DPCD RX capabilities
- `const struct drm_dp_desc *desc`: A cached copy of the connector's DP descriptor

**Description**

See also: [`drm_dp_read_sink_count()`](#c-drm_dp_read_sink_count)

**Return**

`True` if the (e)DP connector has a valid sink count that should
be probed, `false` otherwise.

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

```c
int drm_dp_read_sink_count(struct drm_dp_aux *aux)
```

Retrieve the sink count for a given sink

**Parameters**

- `struct drm_dp_aux *aux`: The DP AUX channel to use

**Description**

See also: [`drm_dp_read_sink_count_cap()`](#c-drm_dp_read_sink_count_cap)

**Return**

The current sink count reported by **aux**, or a negative error code
otherwise.

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

```c
void drm_dp_remote_aux_init(struct drm_dp_aux *aux)
```

minimally initialise a remote aux channel

**Parameters**

- `struct drm_dp_aux *aux`: DisplayPort AUX channel

**Description**

Used for remote aux channel in general. Merely initialize the crc work
struct.

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

```c
void drm_dp_aux_init(struct drm_dp_aux *aux)
```

minimally initialise an aux channel

**Parameters**

- `struct drm_dp_aux *aux`: DisplayPort AUX channel

**Description**

If you need to use the drm_dp_aux's i2c adapter prior to registering it with
the outside world, call [`drm_dp_aux_init()`](#c-drm_dp_aux_init) first. For drivers which are
grandparents to their AUX adapters (e.g. the AUX adapter is parented by a
[`drm_connector`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_connector)), you must still call [`drm_dp_aux_register()`](#c-drm_dp_aux_register) once the connector
has been registered to allow userspace access to the auxiliary DP channel.
Likewise, for such drivers you should also assign [`drm_dp_aux.drm_dev`](#c-struct-drm_dp_aux) as
early as possible so that the [`drm_device`](/kernel/hardware/gpu/drm-internals.md#c-struct-drm_device) that corresponds to the AUX adapter
may be mentioned in debugging output from the DRM DP helpers.

For devices which use a separate platform device for their AUX adapters, this
may be called as early as required by the driver.

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

```c
int drm_dp_aux_register(struct drm_dp_aux *aux)
```

initialise and register aux channel

**Parameters**

- `struct drm_dp_aux *aux`: DisplayPort AUX channel

**Description**

Automatically calls [`drm_dp_aux_init()`](#c-drm_dp_aux_init) if this hasn't been done yet. This
should only be called once the parent of **aux**, [`drm_dp_aux.dev`](#c-struct-drm_dp_aux), is
initialized. For devices which are grandparents of their AUX channels,
[`drm_dp_aux.dev`](#c-struct-drm_dp_aux) will typically be the [`drm_connector`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_connector) [`device`](/kernel/hardware/driver-api/fundamentals/infrastructure.md#c-struct-device) which
corresponds to **aux**. For these devices, it's advised to call
[`drm_dp_aux_register()`](#c-drm_dp_aux_register) in [`drm_connector_funcs.late_register`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_connector_funcs), and likewise to
call [`drm_dp_aux_unregister()`](#c-drm_dp_aux_unregister) in [`drm_connector_funcs.early_unregister`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_connector_funcs).
Functions which don't follow this will likely Oops when
`CONFIG_DRM_DISPLAY_DP_AUX_CHARDEV` is enabled.

For devices where the AUX channel is a device that exists independently of
the [`drm_device`](/kernel/hardware/gpu/drm-internals.md#c-struct-drm_device) that uses it, such as SoCs and bridge devices, it is
recommended to call [`drm_dp_aux_register()`](#c-drm_dp_aux_register) after a [`drm_device`](/kernel/hardware/gpu/drm-internals.md#c-struct-drm_device) has been
assigned to [`drm_dp_aux.drm_dev`](#c-struct-drm_dp_aux), and likewise to call
[`drm_dp_aux_unregister()`](#c-drm_dp_aux_unregister) once the [`drm_device`](/kernel/hardware/gpu/drm-internals.md#c-struct-drm_device) should no longer be associated
with the AUX channel (e.g. on bridge detach).

Drivers which need to use the aux channel before either of the two points
mentioned above need to call [`drm_dp_aux_init()`](#c-drm_dp_aux_init) in order to use the AUX
channel before registration.

Returns 0 on success or a negative error code on failure.

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

```c
void drm_dp_aux_unregister(struct drm_dp_aux *aux)
```

unregister an AUX adapter

**Parameters**

- `struct drm_dp_aux *aux`: DisplayPort AUX channel

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

```c
int drm_dp_psr_setup_time(const u8 psr_cap[EDP_PSR_RECEIVER_CAP_SIZE])
```

PSR setup in time usec

**Parameters**

- `const u8 psr_cap[EDP_PSR_RECEIVER_CAP_SIZE]`: PSR capabilities from DPCD

**Return**

PSR setup time for the panel in microseconds,  negative
error code on failure.

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

```c
int drm_dp_start_crc(struct drm_dp_aux *aux, struct drm_crtc *crtc)
```

start capture of frame CRCs

**Parameters**

- `struct drm_dp_aux *aux`: DisplayPort AUX channel
- `struct drm_crtc *crtc`: CRTC displaying the frames whose CRCs are to be captured

**Description**

Returns 0 on success or a negative error code on failure.

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

```c
int drm_dp_stop_crc(struct drm_dp_aux *aux)
```

stop capture of frame CRCs

**Parameters**

- `struct drm_dp_aux *aux`: DisplayPort AUX channel

**Description**

Returns 0 on success or a negative error code on failure.

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

```c
int drm_dp_read_desc(struct drm_dp_aux *aux, struct drm_dp_desc *desc, bool is_branch)
```

read sink/branch descriptor from DPCD

**Parameters**

- `struct drm_dp_aux *aux`: DisplayPort AUX channel
- `struct drm_dp_desc *desc`: Device descriptor to fill from DPCD
- `bool is_branch`: true for branch devices, false for sink devices

**Description**

Read DPCD 0x400 (sink) or 0x500 (branch) into **desc**. Also debug log the
identification.

Returns 0 on success or a negative error code on failure.

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

```c
int drm_dp_dump_lttpr_desc(struct drm_dp_aux *aux, enum drm_dp_phy dp_phy)
```

read and dump the DPCD descriptor for an LTTPR PHY

**Parameters**

- `struct drm_dp_aux *aux`: DisplayPort AUX channel
- `enum drm_dp_phy dp_phy`: LTTPR PHY instance

**Description**

Read the DPCD LTTPR PHY descriptor for **dp_phy** and print a debug message
with its details to dmesg.

Returns 0 on success or a negative error code on failure.

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

```c
u8 drm_dp_dsc_sink_bpp_incr(const u8 dsc_dpcd[DP_DSC_RECEIVER_CAP_SIZE])
```

Get bits per pixel increment

**Parameters**

- `const u8 dsc_dpcd[DP_DSC_RECEIVER_CAP_SIZE]`: DSC capabilities from DPCD

**Description**

Returns the bpp precision supported by the DP sink.

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

```c
u32 drm_dp_dsc_slice_count_to_mask(int slice_count)
```

Convert a slice count to a slice count mask

**Parameters**

- `int slice_count`: slice count

**Description**

Convert **slice_count** to a slice count mask.

Returns the slice count mask.

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

```c
u32 drm_dp_dsc_sink_slice_count_mask(const u8 dsc_dpcd[DP_DSC_RECEIVER_CAP_SIZE], bool is_edp)
```

Get the mask of valid DSC sink slice counts

**Parameters**

- `const u8 dsc_dpcd[DP_DSC_RECEIVER_CAP_SIZE]`: the sink's DSC DPCD capabilities
- `bool is_edp`: `true` for an eDP sink

**Description**

Get the mask of supported slice counts from the sink's DSC DPCD register.

**Return**

Mask of slice counts supported by the DSC sink:
- > 0: bit#0,1,3,5..,23 set if the sink supports 1,2,4,6..,24 slices
- 0:   if the sink doesn't support any slices

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

```c
u8 drm_dp_dsc_sink_max_slice_count(const u8 dsc_dpcd[DP_DSC_RECEIVER_CAP_SIZE], bool is_edp)
```

Get the max slice count supported by the DSC sink.

**Parameters**

- `const u8 dsc_dpcd[DP_DSC_RECEIVER_CAP_SIZE]`: DSC capabilities from DPCD
- `bool is_edp`: true if its eDP, false for DP

**Description**

Read the slice capabilities DPCD register from DSC sink to get
the maximum slice count supported. This is used to populate
the DSC parameters in the [`struct drm_dsc_config`](#c-struct-drm_dsc_config) by the driver.
Driver creates an infoframe using these parameters to populate
[`struct drm_dsc_pps_infoframe`](#c-struct-drm_dsc_pps_infoframe). These are sent to the sink using DSC
infoframe using the helper function `drm_dsc_pps_infoframe_pack()`

**Return**

Maximum slice count supported by DSC sink or 0 its invalid

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

```c
u8 drm_dp_dsc_sink_line_buf_depth(const u8 dsc_dpcd[DP_DSC_RECEIVER_CAP_SIZE])
```

Get the line buffer depth in bits

**Parameters**

- `const u8 dsc_dpcd[DP_DSC_RECEIVER_CAP_SIZE]`: DSC capabilities from DPCD

**Description**

Read the DSC DPCD register to parse the line buffer depth in bits which is
number of bits of precision within the decoder line buffer supported by
the DSC sink. This is used to populate the DSC parameters in the
[`struct drm_dsc_config`](#c-struct-drm_dsc_config) by the driver.
Driver creates an infoframe using these parameters to populate
[`struct drm_dsc_pps_infoframe`](#c-struct-drm_dsc_pps_infoframe). These are sent to the sink using DSC
infoframe using the helper function `drm_dsc_pps_infoframe_pack()`

**Return**

Line buffer depth supported by DSC panel or 0 its invalid

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

```c
int drm_dp_dsc_sink_supported_input_bpcs(const u8 dsc_dpcd[DP_DSC_RECEIVER_CAP_SIZE], u8 dsc_bpc[3])
```

Get all the input bits per component values supported by the DSC sink.

**Parameters**

- `const u8 dsc_dpcd[DP_DSC_RECEIVER_CAP_SIZE]`: DSC capabilities from DPCD
- `u8 dsc_bpc[3]`: An array to be filled by this helper with supported
  input bpcs.

**Description**

Read the DSC DPCD from the sink device to parse the supported bits per
component values. This is used to populate the DSC parameters
in the [`struct drm_dsc_config`](#c-struct-drm_dsc_config) by the driver.
Driver creates an infoframe using these parameters to populate
[`struct drm_dsc_pps_infoframe`](#c-struct-drm_dsc_pps_infoframe). These are sent to the sink using DSC
infoframe using the helper function `drm_dsc_pps_infoframe_pack()`

**Return**

Number of input BPC values parsed from the DPCD

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

```c
int drm_dp_dsc_sink_max_slice_throughput(const u8 dsc_dpcd[DP_DSC_RECEIVER_CAP_SIZE], int peak_pixel_rate, bool is_rgb_yuv444)
```

Get a DSC sink's maximum pixel throughput per slice

**Parameters**

- `const u8 dsc_dpcd[DP_DSC_RECEIVER_CAP_SIZE]`: DSC sink's capabilities from DPCD
- `int peak_pixel_rate`: Cumulative peak pixel rate in kHz
- `bool is_rgb_yuv444`: The mode is either RGB or YUV444

**Description**

Return the DSC sink device's maximum pixel throughput per slice, based on
the device's **dsc_dpcd** capabilities, the **peak_pixel_rate** of the transferred
stream(s) and whether the output format **is_rgb_yuv444** or yuv422/yuv420.

Note that **peak_pixel_rate** is the total pixel rate transferred to the same
DSC/display sink. For instance to calculate a tile's slice count of an MST
multi-tiled display sink (not considering here the required
rounding/alignment of slice count):

```text
@peak_pixel_rate = tile_pixel_rate * tile_count
total_slice_count = @peak_pixel_rate / drm_dp_dsc_sink_max_slice_throughput(@peak_pixel_rate)
tile_slice_count = total_slice_count / tile_count
```

**Return**

The maximum pixel throughput per slice supported by the DSC sink device
in kPixels/sec.

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

```c
int drm_dp_dsc_branch_max_overall_throughput(const u8 dsc_branch_dpcd[DP_DSC_BRANCH_CAP_SIZE], bool is_rgb_yuv444)
```

Branch device's max overall DSC pixel throughput

**Parameters**

- `const u8 dsc_branch_dpcd[DP_DSC_BRANCH_CAP_SIZE]`: DSC branch capabilities from DPCD
- `bool is_rgb_yuv444`: The mode is either RGB or YUV444

**Description**

Return the branch device's maximum overall DSC pixel throughput, based on
the device's DPCD DSC branch capabilities, and whether the output
format **is_rgb_yuv444** or yuv422/yuv420.

**Return**

- 0:   The maximum overall throughput capability is not indicated by
  the device separately and it must be determined from the per-slice
  max throughput (see **drm_dp_dsc_branch_slice_max_throughput()**)
  and the maximum slice count supported by the device.
- > 0: The maximum overall DSC pixel throughput supported by the branch
  device in kPixels/sec.

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

```c
int drm_dp_dsc_branch_max_line_width(const u8 dsc_branch_dpcd[DP_DSC_BRANCH_CAP_SIZE])
```

Branch device's max DSC line width

**Parameters**

- `const u8 dsc_branch_dpcd[DP_DSC_BRANCH_CAP_SIZE]`: DSC branch capabilities from DPCD

**Description**

Return the branch device's maximum overall DSC line width, based on
the device's **dsc_branch_dpcd** capabilities.

**Return**

- 0:        The maximum line width is not indicated by the device
  separately and it must be determined from the maximum
  slice count and slice-width supported by the device.
- `-EINVAL`: The device indicates an invalid maximum line width
  (\< 5120 pixels).
- >= 5120:  The maximum line width in pixels.

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

```c
int drm_dp_read_lttpr_common_caps(struct drm_dp_aux *aux, const u8 dpcd[DP_RECEIVER_CAP_SIZE], u8 caps[DP_LTTPR_COMMON_CAP_SIZE])
```

read the LTTPR common capabilities

**Parameters**

- `struct drm_dp_aux *aux`: DisplayPort AUX channel
- `const u8 dpcd[DP_RECEIVER_CAP_SIZE]`: DisplayPort configuration data
- `u8 caps[DP_LTTPR_COMMON_CAP_SIZE]`: buffer to return the capability info in

**Description**

Read capabilities common to all LTTPRs.

Returns 0 on success or a negative error code on failure.

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

```c
int drm_dp_read_lttpr_phy_caps(struct drm_dp_aux *aux, const u8 dpcd[DP_RECEIVER_CAP_SIZE], enum drm_dp_phy dp_phy, u8 caps[DP_LTTPR_PHY_CAP_SIZE])
```

read the capabilities for a given LTTPR PHY

**Parameters**

- `struct drm_dp_aux *aux`: DisplayPort AUX channel
- `const u8 dpcd[DP_RECEIVER_CAP_SIZE]`: DisplayPort configuration data
- `enum drm_dp_phy dp_phy`: LTTPR PHY to read the capabilities for
- `u8 caps[DP_LTTPR_PHY_CAP_SIZE]`: buffer to return the capability info in

**Description**

Read the capabilities for the given LTTPR PHY.

Returns 0 on success or a negative error code on failure.

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

```c
int drm_dp_lttpr_count(const u8 caps[DP_LTTPR_COMMON_CAP_SIZE])
```

get the number of detected LTTPRs

**Parameters**

- `const u8 caps[DP_LTTPR_COMMON_CAP_SIZE]`: LTTPR common capabilities

**Description**

Get the number of detected LTTPRs from the LTTPR common capabilities info.

**Return**

-ERANGE if more than supported number (8) of LTTPRs are detected
-EINVAL if the DP_PHY_REPEATER_CNT register contains an invalid value
otherwise the number of detected LTTPRs

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

```c
int drm_dp_lttpr_max_link_rate(const u8 caps[DP_LTTPR_COMMON_CAP_SIZE])
```

get the maximum link rate supported by all LTTPRs

**Parameters**

- `const u8 caps[DP_LTTPR_COMMON_CAP_SIZE]`: LTTPR common capabilities

**Description**

Returns the maximum link rate supported by all detected LTTPRs.

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

```c
int drm_dp_lttpr_set_transparent_mode(struct drm_dp_aux *aux, bool enable)
```

set the LTTPR in transparent mode

**Parameters**

- `struct drm_dp_aux *aux`: DisplayPort AUX channel
- `bool enable`: Enable or disable transparent mode

**Return**

0 on success or a negative error code on failure.

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

```c
int drm_dp_lttpr_init(struct drm_dp_aux *aux, int lttpr_count)
```

init LTTPR transparency mode according to DP standard

**Parameters**

- `struct drm_dp_aux *aux`: DisplayPort AUX channel
- `int lttpr_count`: Number of LTTPRs. Between 0 and 8, according to DP standard.
  Negative error code for any non-valid number.
  See [`drm_dp_lttpr_count()`](#c-drm_dp_lttpr_count).

**Return**

0 on success or a negative error code on failure.

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

```c
int drm_dp_lttpr_max_lane_count(const u8 caps[DP_LTTPR_COMMON_CAP_SIZE])
```

get the maximum lane count supported by all LTTPRs

**Parameters**

- `const u8 caps[DP_LTTPR_COMMON_CAP_SIZE]`: LTTPR common capabilities

**Description**

Returns the maximum lane count supported by all detected LTTPRs.

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

```c
bool drm_dp_lttpr_voltage_swing_level_3_supported(const u8 caps[DP_LTTPR_PHY_CAP_SIZE])
```

check for LTTPR vswing3 support

**Parameters**

- `const u8 caps[DP_LTTPR_PHY_CAP_SIZE]`: LTTPR PHY capabilities

**Description**

Returns true if the **caps** for an LTTPR TX PHY indicate support for
voltage swing level 3.

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

```c
bool drm_dp_lttpr_pre_emphasis_level_3_supported(const u8 caps[DP_LTTPR_PHY_CAP_SIZE])
```

check for LTTPR preemph3 support

**Parameters**

- `const u8 caps[DP_LTTPR_PHY_CAP_SIZE]`: LTTPR PHY capabilities

**Description**

Returns true if the **caps** for an LTTPR TX PHY indicate support for
pre-emphasis level 3.

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

```c
int drm_dp_get_phy_test_pattern(struct drm_dp_aux *aux, struct drm_dp_phy_test_params *data)
```

get the requested pattern from the sink.

**Parameters**

- `struct drm_dp_aux *aux`: DisplayPort AUX channel
- `struct drm_dp_phy_test_params *data`: DP phy compliance test parameters.

**Description**

Returns 0 on success or a negative error code on failure.

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

```c
int drm_dp_set_phy_test_pattern(struct drm_dp_aux *aux, struct drm_dp_phy_test_params *data, u8 dp_rev)
```

set the pattern to the sink.

**Parameters**

- `struct drm_dp_aux *aux`: DisplayPort AUX channel
- `struct drm_dp_phy_test_params *data`: DP phy compliance test parameters.
- `u8 dp_rev`: DP revision to use for compliance testing

**Description**

Returns 0 on success or a negative error code on failure.

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

```c
bool drm_dp_as_sdp_supported(struct drm_dp_aux *aux, const u8 dpcd[DP_RECEIVER_CAP_SIZE])
```

check if adaptive sync sdp is supported

**Parameters**

- `struct drm_dp_aux *aux`: DisplayPort AUX channel
- `const u8 dpcd[DP_RECEIVER_CAP_SIZE]`: DisplayPort configuration data

**Description**

Returns true if adaptive sync sdp is supported, else returns false

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

```c
bool drm_dp_vsc_sdp_supported(struct drm_dp_aux *aux, const u8 dpcd[DP_RECEIVER_CAP_SIZE])
```

check if vsc sdp is supported

**Parameters**

- `struct drm_dp_aux *aux`: DisplayPort AUX channel
- `const u8 dpcd[DP_RECEIVER_CAP_SIZE]`: DisplayPort configuration data

**Description**

Returns true if vsc sdp is supported, else returns false

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

```c
ssize_t drm_dp_vsc_sdp_pack(const struct drm_dp_vsc_sdp *vsc, struct dp_sdp *sdp)
```

pack a given vsc sdp into generic dp_sdp

**Parameters**

- `const struct drm_dp_vsc_sdp *vsc`: vsc sdp initialized according to its purpose as defined in
  table 2-118 - table 2-120 in DP 1.4a specification
- `struct dp_sdp *sdp`: valid handle to the generic dp_sdp which will be packed

**Description**

Returns length of sdp on success and error code on failure

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

```c
int drm_dp_get_pcon_max_frl_bw(const u8 dpcd[DP_RECEIVER_CAP_SIZE], const u8 port_cap[4])
```

maximum frl supported by PCON

**Parameters**

- `const u8 dpcd[DP_RECEIVER_CAP_SIZE]`: DisplayPort configuration data
- `const u8 port_cap[4]`: port capabilities

**Description**

Returns maximum frl bandwidth supported by PCON in GBPS,
returns 0 if not supported.

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

```c
int drm_dp_pcon_frl_prepare(struct drm_dp_aux *aux, bool enable_frl_ready_hpd)
```

Prepare PCON for FRL.

**Parameters**

- `struct drm_dp_aux *aux`: DisplayPort AUX channel
- `bool enable_frl_ready_hpd`: Configure DP_PCON_ENABLE_HPD_READY.

**Description**

Returns 0 if success, else returns negative error code.

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

```c
bool drm_dp_pcon_is_frl_ready(struct drm_dp_aux *aux)
```

Is PCON ready for FRL

**Parameters**

- `struct drm_dp_aux *aux`: DisplayPort AUX channel

**Description**

Returns true if success, else returns false.

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

```c
int drm_dp_pcon_frl_configure_1(struct drm_dp_aux *aux, int max_frl_gbps, u8 frl_mode)
```

Set HDMI LINK Configuration-Step1

**Parameters**

- `struct drm_dp_aux *aux`: DisplayPort AUX channel
- `int max_frl_gbps`: maximum frl bw to be configured between PCON and HDMI sink
- `u8 frl_mode`: FRL Training mode, it can be either Concurrent or Sequential.
  In Concurrent Mode, the FRL link bring up can be done along with
  DP Link training. In Sequential mode, the FRL link bring up is done prior to
  the DP Link training.

**Description**

Returns 0 if success, else returns negative error code.

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

```c
int drm_dp_pcon_frl_configure_2(struct drm_dp_aux *aux, int max_frl_mask, u8 frl_type)
```

Set HDMI Link configuration Step-2

**Parameters**

- `struct drm_dp_aux *aux`: DisplayPort AUX channel
- `int max_frl_mask`: Max FRL BW to be tried by the PCON with HDMI Sink
- `u8 frl_type`: FRL training type, can be Extended, or Normal.
  In Normal FRL training, the PCON tries each frl bw from the max_frl_mask
  starting from min, and stops when link training is successful. In Extended
  FRL training, all frl bw selected in the mask are trained by the PCON.

**Description**

Returns 0 if success, else returns negative error code.

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

```c
int drm_dp_pcon_reset_frl_config(struct drm_dp_aux *aux)
```

Re-Set HDMI Link configuration.

**Parameters**

- `struct drm_dp_aux *aux`: DisplayPort AUX channel

**Description**

Returns 0 if success, else returns negative error code.

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

```c
int drm_dp_pcon_frl_enable(struct drm_dp_aux *aux)
```

Enable HDMI link through FRL

**Parameters**

- `struct drm_dp_aux *aux`: DisplayPort AUX channel

**Description**

Returns 0 if success, else returns negative error code.

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

```c
bool drm_dp_pcon_hdmi_link_active(struct drm_dp_aux *aux)
```

check if the PCON HDMI LINK status is active.

**Parameters**

- `struct drm_dp_aux *aux`: DisplayPort AUX channel

**Description**

Returns true if link is active else returns false.

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

```c
int drm_dp_pcon_hdmi_link_mode(struct drm_dp_aux *aux, u8 *frl_trained_mask)
```

get the PCON HDMI LINK MODE

**Parameters**

- `struct drm_dp_aux *aux`: DisplayPort AUX channel
- `u8 *frl_trained_mask`: pointer to store bitmask of the trained bw configuration.
  Valid only if the MODE returned is FRL. For Normal Link training mode
  only 1 of the bits will be set, but in case of Extended mode, more than
  one bits can be set.

**Description**

Returns the link mode : TMDS or FRL on success, else returns negative error
code.

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

```c
void drm_dp_pcon_hdmi_frl_link_error_count(struct drm_dp_aux *aux, struct drm_connector *connector)
```

print the error count per lane during link failure between PCON and HDMI sink

**Parameters**

- `struct drm_dp_aux *aux`: DisplayPort AUX channel
- `struct drm_connector *connector`: DRM connector
  code.

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

```c
int drm_dp_pcon_pps_default(struct drm_dp_aux *aux)
```

Let PCON fill the default pps parameters for DSC1.2 between PCON & HDMI2.1 sink

**Parameters**

- `struct drm_dp_aux *aux`: DisplayPort AUX channel

**Description**

Returns 0 on success, else returns negative error code.

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

```c
int drm_dp_pcon_pps_override_buf(struct drm_dp_aux *aux, u8 pps_buf[128])
```

Configure PPS encoder override buffer for HDMI sink

**Parameters**

- `struct drm_dp_aux *aux`: DisplayPort AUX channel
- `u8 pps_buf[128]`: 128 bytes to be written into PPS buffer for HDMI sink by PCON.

**Description**

Returns 0 on success, else returns negative error code.

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

```c
int drm_edp_backlight_set_level(struct drm_dp_aux *aux, const struct drm_edp_backlight_info *bl, u32 level)
```

Set the backlight level of an eDP panel via AUX

**Parameters**

- `struct drm_dp_aux *aux`: The DP AUX channel to use
- `const struct drm_edp_backlight_info *bl`: Backlight capability info from [`drm_edp_backlight_init()`](#c-drm_edp_backlight_init)
- `u32 level`: The brightness level to set

**Description**

Sets the brightness level of an eDP panel's backlight. Note that the panel's backlight must
already have been enabled by the driver by calling [`drm_edp_backlight_enable()`](#c-drm_edp_backlight_enable).

**Return**

`0` on success, negative error code on failure

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

```c
int drm_edp_backlight_enable(struct drm_dp_aux *aux, const struct drm_edp_backlight_info *bl, const u32 level)
```

Enable an eDP panel's backlight using DPCD

**Parameters**

- `struct drm_dp_aux *aux`: The DP AUX channel to use
- `const struct drm_edp_backlight_info *bl`: Backlight capability info from [`drm_edp_backlight_init()`](#c-drm_edp_backlight_init)
- `const u32 level`: The initial backlight level to set via AUX, if there is one

**Description**

This function handles enabling DPCD backlight controls on a panel over DPCD, while additionally
restoring any important backlight state such as the given backlight level, the brightness byte
count, backlight frequency, etc.

Note that certain panels do not support being enabled or disabled via DPCD, but instead require
that the driver handle enabling/disabling the panel through implementation-specific means using
the EDP_BL_PWR GPIO. For such panels, [`drm_edp_backlight_info.aux_enable`](#c-struct-drm_edp_backlight_info) will be set to `false`,
this function becomes a no-op, and the driver is expected to handle powering the panel on using
the EDP_BL_PWR GPIO.

**Return**

`0` on success, negative error code on failure.

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

```c
int drm_edp_backlight_disable(struct drm_dp_aux *aux, const struct drm_edp_backlight_info *bl)
```

Disable an eDP backlight using DPCD, if supported

**Parameters**

- `struct drm_dp_aux *aux`: The DP AUX channel to use
- `const struct drm_edp_backlight_info *bl`: Backlight capability info from [`drm_edp_backlight_init()`](#c-drm_edp_backlight_init)

**Description**

This function handles disabling DPCD backlight controls on a panel over AUX.

Note that certain panels do not support being enabled or disabled via DPCD, but instead require
that the driver handle enabling/disabling the panel through implementation-specific means using
the EDP_BL_PWR GPIO. For such panels, [`drm_edp_backlight_info.aux_enable`](#c-struct-drm_edp_backlight_info) will be set to `false`,
this function becomes a no-op, and the driver is expected to handle powering the panel off using
the EDP_BL_PWR GPIO.

**Return**

`0` on success or no-op, negative error code on failure.

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

```c
int drm_edp_backlight_init(struct drm_dp_aux *aux, struct drm_edp_backlight_info *bl, u32 max_luminance, u16 driver_pwm_freq_hz, const u8 edp_dpcd[EDP_DISPLAY_CTL_CAP_SIZE], u32 *current_level, u8 *current_mode, bool need_luminance)
```

Probe a display panel's TCON using the standard VESA eDP backlight interface.

**Parameters**

- `struct drm_dp_aux *aux`: The DP aux device to use for probing
- `struct drm_edp_backlight_info *bl`: The [`drm_edp_backlight_info`](#c-struct-drm_edp_backlight_info) struct to fill out with information on the backlight
- `u32 max_luminance`: max luminance when need luminance is set as true
- `u16 driver_pwm_freq_hz`: Optional PWM frequency from the driver in hz
- `const u8 edp_dpcd[EDP_DISPLAY_CTL_CAP_SIZE]`: A cached copy of the eDP DPCD
- `u32 *current_level`: Where to store the probed brightness level, if any
- `u8 *current_mode`: Where to store the currently set backlight control mode
- `bool need_luminance`: Tells us if a we want to manipulate backlight using luminance values

**Description**

Initializes a [`drm_edp_backlight_info`](#c-struct-drm_edp_backlight_info) struct by probing **aux** for it's backlight capabilities,
along with also probing the current and maximum supported brightness levels.

If **driver_pwm_freq_hz** is non-zero, this will be used as the backlight frequency. Otherwise, the
default frequency from the panel is used.

**Return**

`0` on success, negative error code on failure.

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

```c
int drm_panel_dp_aux_backlight(struct drm_panel *panel, struct drm_dp_aux *aux)
```

create and use DP AUX backlight

**Parameters**

- `struct drm_panel *panel`: DRM panel
- `struct drm_dp_aux *aux`: The DP AUX channel to use

**Description**

Use this function to create and handle backlight if your panel
supports backlight control over DP AUX channel using DPCD
registers as per VESA's standard backlight control interface.

When the panel is enabled backlight will be enabled after a
successful call to [`drm_panel_funcs.enable()`](#c-struct-drm_panel_funcs)

When the panel is disabled backlight will be disabled before the
call to [`drm_panel_funcs.disable()`](#c-struct-drm_panel_funcs).

A typical implementation for a panel driver supporting backlight
control over DP AUX will call this function at probe time.
Backlight will then be handled transparently without requiring
any intervention from the driver.

[`drm_panel_dp_aux_backlight()`](#c-drm_panel_dp_aux_backlight) must be called after the call to [`drm_panel_init()`](#c-drm_panel_init).

**Return**

0 on success or a negative error code on failure.

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

```c
int drm_dp_link_symbol_cycles(int lane_count, int pixels, int dsc_slice_count, int bpp_x16, int symbol_size, bool is_mst)
```

calculate the link symbol count with/without dsc

**Parameters**

- `int lane_count`: DP link lane count
- `int pixels`: number of pixels in a scanline
- `int dsc_slice_count`: number of slices for DSC or '0' for non-DSC
- `int bpp_x16`: bits per pixel in .4 binary fixed format
- `int symbol_size`: DP symbol size
- `bool is_mst`: `true` for MST and `false` for SST

**Description**

Calculate the link symbol cycles for both DSC (**dsc_slice_count** !=0) and
non-DSC case (**dsc_slice_count** == 0) and return the count.

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

```c
int drm_dp_bw_overhead(int lane_count, int hactive, int dsc_slice_count, int bpp_x16, unsigned long flags)
```

Calculate the BW overhead of a DP link stream

**Parameters**

- `int lane_count`: DP link lane count
- `int hactive`: pixel count of the active period in one scanline of the stream
- `int dsc_slice_count`: number of slices for DSC or '0' for non-DSC
- `int bpp_x16`: bits per pixel in .4 binary fixed point
- `unsigned long flags`: DRM_DP_OVERHEAD_x flags

**Description**

Calculate the BW allocation overhead of a DP link stream, depending
on the link's
- **lane_count**
- SST/MST mode (**flags** / `DRM_DP_OVERHEAD_MST`)
- symbol size (**flags** / `DRM_DP_OVERHEAD_UHBR`)
- FEC mode (**flags** / `DRM_DP_OVERHEAD_FEC`)
- SSC/REF_CLK mode (**flags** / `DRM_DP_OVERHEAD_SSC_REF_CLK`)
as well as the stream's
- **hactive** timing
- **bpp_x16** color depth
- compression mode (**dsc_slice_count** != 0)
Note that this overhead doesn't account for the 8b/10b, 128b/132b
channel coding efficiency, for that see
**drm_dp_link_bw_channel_coding_efficiency()**.

Returns the overhead as 100% + overhead% in 1ppm units.

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

```c
int drm_dp_bw_channel_coding_efficiency(bool is_uhbr)
```

Get a DP link's channel coding efficiency

**Parameters**

- `bool is_uhbr`: Whether the link has a 128b/132b channel coding

**Description**

Return the channel coding efficiency of the given DP link type, which is
either 8b/10b or 128b/132b (aka UHBR). The corresponding overhead includes
the 8b -> 10b, 128b -> 132b pixel data to link symbol conversion overhead
and for 128b/132b any link or PHY level control symbol insertion overhead
(LLCP, FEC, PHY sync, see DP Standard v2.1 3.5.2.18). For 8b/10b the
corresponding FEC overhead is BW allocation specific, included in the value
returned by [`drm_dp_bw_overhead()`](#c-drm_dp_bw_overhead).

Returns the efficiency in the 100%/coding-overhead% ratio in
1ppm units.

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

```c
int drm_dp_max_dprx_data_rate(int max_link_rate, int max_lanes)
```

Get the max data bandwidth of a DPRX sink

**Parameters**

- `int max_link_rate`: max DPRX link rate in 10kbps units
- `int max_lanes`: max DPRX lane count

**Description**

Given a link rate and lanes, get the data bandwidth.

Data bandwidth is the actual payload rate, which depends on the data
bandwidth efficiency and the link rate.

Note that protocol layers above the DPRX link level considered here can
further limit the maximum data rate. Such layers are the MST topology (with
limits on the link between the source and first branch device as well as on
the whole MST path until the DPRX link) and (Thunderbolt) DP tunnels -
which in turn can encapsulate an MST link with its own limit - with each
SST or MST encapsulated tunnel sharing the BW of a tunnel group.

Returns the maximum data rate in kBps units.


<a id="rst-display-port-cec-helper-functions-reference"></a>

## Display Port CEC Helper Functions Reference


These functions take care of supporting the CEC-Tunneling-over-AUX
feature of DisplayPort-to-HDMI adapters.



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

```c
void drm_dp_cec_irq(struct drm_dp_aux *aux)
```

handle CEC interrupt, if any

**Parameters**

- `struct drm_dp_aux *aux`: DisplayPort AUX channel

**Description**

Should be called when handling an IRQ_HPD request. If CEC-tunneling-over-AUX
is present, then it will check for a CEC_IRQ and handle it accordingly.

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

```c
void drm_dp_cec_register_connector(struct drm_dp_aux *aux, struct drm_connector *connector)
```

register a new connector

**Parameters**

- `struct drm_dp_aux *aux`: DisplayPort AUX channel
- `struct drm_connector *connector`: drm connector

**Description**

A new connector was registered with associated CEC adapter name and
CEC adapter parent device. After registering the name and parent
`drm_dp_cec_set_edid()` is called to check if the connector supports
CEC and to register a CEC adapter if that is the case.

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

```c
void drm_dp_cec_unregister_connector(struct drm_dp_aux *aux)
```

unregister the CEC adapter, if any

**Parameters**

- `struct drm_dp_aux *aux`: DisplayPort AUX channel


<a id="rst-display-port-dual-mode-adaptor-helper-functions-reference"></a>

## Display Port Dual Mode Adaptor Helper Functions Reference


Helper functions to deal with DP dual mode (aka. DP++) adaptors.

Type 1:
Adaptor registers (if any) and the sink DDC bus may be accessed via I2C.

Type 2:
Adaptor registers and sink DDC bus can be accessed either via I2C or
I2C-over-AUX. Source devices may choose to implement either of these
access methods.



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

**Constants**

- `DRM_LSPCON_MODE_INVALID`: No LSPCON.
- `DRM_LSPCON_MODE_LS`: Level shifter mode of LSPCON
  which drives DP++ to HDMI 1.4 conversion.
- `DRM_LSPCON_MODE_PCON`: Protocol converter mode of LSPCON
  which drives DP++ to HDMI 2.0 active conversion.

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

Type of the DP dual mode adaptor

**Constants**

- `DRM_DP_DUAL_MODE_NONE`: No DP dual mode adaptor
- `DRM_DP_DUAL_MODE_UNKNOWN`: Could be either none or type 1 DVI adaptor
- `DRM_DP_DUAL_MODE_TYPE1_DVI`: Type 1 DVI adaptor
- `DRM_DP_DUAL_MODE_TYPE1_HDMI`: Type 1 HDMI adaptor
- `DRM_DP_DUAL_MODE_TYPE2_DVI`: Type 2 DVI adaptor
- `DRM_DP_DUAL_MODE_TYPE2_HDMI`: Type 2 HDMI adaptor
- `DRM_DP_DUAL_MODE_LSPCON`: Level shifter / protocol converter



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

```c
ssize_t drm_dp_dual_mode_read(struct i2c_adapter *adapter, u8 offset, void *buffer, size_t size)
```

Read from the DP dual mode adaptor register(s)

**Parameters**

- `struct i2c_adapter *adapter`: I2C adapter for the DDC bus
- `u8 offset`: register offset
- `void *buffer`: buffer for return data
- `size_t size`: size of the buffer

**Description**

Reads **size** bytes from the DP dual mode adaptor registers
starting at **offset**.

**Return**

0 on success, negative error code on failure

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

```c
ssize_t drm_dp_dual_mode_write(struct i2c_adapter *adapter, u8 offset, const void *buffer, size_t size)
```

Write to the DP dual mode adaptor register(s)

**Parameters**

- `struct i2c_adapter *adapter`: I2C adapter for the DDC bus
- `u8 offset`: register offset
- `const void *buffer`: buffer for write data
- `size_t size`: size of the buffer

**Description**

Writes **size** bytes to the DP dual mode adaptor registers
starting at **offset**.

**Return**

0 on success, negative error code on failure

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

```c
enum drm_dp_dual_mode_type drm_dp_dual_mode_detect(const struct drm_device *dev, struct i2c_adapter *adapter)
```

Identify the DP dual mode adaptor

**Parameters**

- `const struct drm_device *dev`: [`drm_device`](/kernel/hardware/gpu/drm-internals.md#c-struct-drm_device) to use
- `struct i2c_adapter *adapter`: I2C adapter for the DDC bus

**Description**

Attempt to identify the type of the DP dual mode adaptor used.

Note that when the answer is **DRM_DP_DUAL_MODE_UNKNOWN** it's not
certain whether we're dealing with a native HDMI port or
a type 1 DVI dual mode adaptor. The driver will have to use
some other hardware/driver specific mechanism to make that
distinction.

**Return**

The type of the DP dual mode adaptor used

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

```c
int drm_dp_dual_mode_max_tmds_clock(const struct drm_device *dev, enum drm_dp_dual_mode_type type, struct i2c_adapter *adapter)
```

Max TMDS clock for DP dual mode adaptor

**Parameters**

- `const struct drm_device *dev`: [`drm_device`](/kernel/hardware/gpu/drm-internals.md#c-struct-drm_device) to use
- `enum drm_dp_dual_mode_type type`: DP dual mode adaptor type
- `struct i2c_adapter *adapter`: I2C adapter for the DDC bus

**Description**

Determine the max TMDS clock the adaptor supports based on the
type of the dual mode adaptor and the DP_DUAL_MODE_MAX_TMDS_CLOCK
register (on type2 adaptors). As some type 1 adaptors have
problems with registers (see comments in [`drm_dp_dual_mode_detect()`](#c-drm_dp_dual_mode_detect))
we don't read the register on those, instead we simply assume
a 165 MHz limit based on the specification.

**Return**

Maximum supported TMDS clock rate for the DP dual mode adaptor in kHz.

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

```c
int drm_dp_dual_mode_get_tmds_output(const struct drm_device *dev, enum drm_dp_dual_mode_type type, struct i2c_adapter *adapter, bool *enabled)
```

Get the state of the TMDS output buffers in the DP dual mode adaptor

**Parameters**

- `const struct drm_device *dev`: [`drm_device`](/kernel/hardware/gpu/drm-internals.md#c-struct-drm_device) to use
- `enum drm_dp_dual_mode_type type`: DP dual mode adaptor type
- `struct i2c_adapter *adapter`: I2C adapter for the DDC bus
- `bool *enabled`: current state of the TMDS output buffers

**Description**

Get the state of the TMDS output buffers in the adaptor. For
type2 adaptors this is queried from the DP_DUAL_MODE_TMDS_OEN
register. As some type 1 adaptors have problems with registers
(see comments in [`drm_dp_dual_mode_detect()`](#c-drm_dp_dual_mode_detect)) we don't read the
register on those, instead we simply assume that the buffers
are always enabled.

**Return**

0 on success, negative error code on failure

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

```c
int drm_dp_dual_mode_set_tmds_output(const struct drm_device *dev, enum drm_dp_dual_mode_type type, struct i2c_adapter *adapter, bool enable)
```

Enable/disable TMDS output buffers in the DP dual mode adaptor

**Parameters**

- `const struct drm_device *dev`: [`drm_device`](/kernel/hardware/gpu/drm-internals.md#c-struct-drm_device) to use
- `enum drm_dp_dual_mode_type type`: DP dual mode adaptor type
- `struct i2c_adapter *adapter`: I2C adapter for the DDC bus
- `bool enable`: enable (as opposed to disable) the TMDS output buffers

**Description**

Set the state of the TMDS output buffers in the adaptor. For
type2 this is set via the DP_DUAL_MODE_TMDS_OEN register.
Type1 adaptors do not support any register writes.

**Return**

0 on success, negative error code on failure

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

```c
const char * drm_dp_get_dual_mode_type_name(enum drm_dp_dual_mode_type type)
```

Get the name of the DP dual mode adaptor type as a string

**Parameters**

- `enum drm_dp_dual_mode_type type`: DP dual mode adaptor type

**Return**

String representation of the DP dual mode adaptor type

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

```c
int drm_lspcon_get_mode(const struct drm_device *dev, struct i2c_adapter *adapter, enum drm_lspcon_mode *mode)
```

Get LSPCON's current mode of operation by reading offset (0x80, 0x41)

**Parameters**

- `const struct drm_device *dev`: [`drm_device`](/kernel/hardware/gpu/drm-internals.md#c-struct-drm_device) to use
- `struct i2c_adapter *adapter`: I2C-over-aux adapter
- `enum drm_lspcon_mode *mode`: current lspcon mode of operation output variable

**Return**

0 on success, sets the current_mode value to appropriate mode
-error on failure

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

```c
int drm_lspcon_set_mode(const struct drm_device *dev, struct i2c_adapter *adapter, enum drm_lspcon_mode mode, int time_out)
```

Change LSPCON's mode of operation by writing offset (0x80, 0x40)

**Parameters**

- `const struct drm_device *dev`: [`drm_device`](/kernel/hardware/gpu/drm-internals.md#c-struct-drm_device) to use
- `struct i2c_adapter *adapter`: I2C-over-aux adapter
- `enum drm_lspcon_mode mode`: required mode of operation
- `int time_out`: LSPCON mode change settle timeout

**Return**

0 on success, -error on failure/timeout


<a id="rst-display-port-mst-helpers"></a>

## Display Port MST Helpers

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

### Overview


These functions contain parts of the DisplayPort 1.2a MultiStream Transport
protocol. The helpers contain a topology manager and bandwidth manager.
The helpers encapsulate the sending and received of sideband msgs.



**Topology refcount overview**

The refcounting schemes for [`struct drm_dp_mst_branch`](#c-struct-drm_dp_mst_branch) and [`struct drm_dp_mst_port`](#c-struct-drm_dp_mst_port) are somewhat unusual. Both ports and branch devices have
two different kinds of refcounts: topology refcounts, and malloc refcounts.

Topology refcounts are not exposed to drivers, and are handled internally
by the DP MST helpers. The helpers use them in order to prevent the
in-memory topology state from being changed in the middle of critical
operations like changing the internal state of payload allocations. This
means each branch and port will be considered to be connected to the rest
of the topology until its topology refcount reaches zero. Additionally,
for ports this means that their associated [`struct drm_connector`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_connector) will stay
registered with userspace until the port's refcount reaches 0.

**Malloc refcount overview**

Malloc references are used to keep a [`struct drm_dp_mst_port`](#c-struct-drm_dp_mst_port) or [`struct drm_dp_mst_branch`](#c-struct-drm_dp_mst_branch) allocated even after all of its topology references have
been dropped, so that the driver or MST helpers can safely access each
branch's last known state before it was disconnected from the topology.
When the malloc refcount of a port or branch reaches 0, the memory
allocation containing the [`struct drm_dp_mst_branch`](#c-struct-drm_dp_mst_branch) or [`struct drm_dp_mst_port`](#c-struct-drm_dp_mst_port) respectively will be freed.

For [`struct drm_dp_mst_branch`](#c-struct-drm_dp_mst_branch), malloc refcounts are not currently exposed
to drivers. As of writing this documentation, there are no drivers that
have a usecase for accessing [`struct drm_dp_mst_branch`](#c-struct-drm_dp_mst_branch) outside of the MST
helpers. Exposing this API to drivers in a race-free manner would take more
tweaking of the refcounting scheme, however patches are welcome provided
there is a legitimate driver usecase for this.

**Refcount relationships in a topology**

Let's take a look at why the relationship between topology and malloc
refcounts is designed the way it is.

```mermaid
flowchart TB
  subgraph g0["#160;"]
    n0["DRM driver"]
    n1["Payload #35;1"]
    n2["Payload #35;2"]
  end
  subgraph g1["Topology Manager"]
    n3(["Port #35;1"])
    n4(["Port #35;2"])
    n5(["Port #35;3"])
    n6(["Port #35;4"])
    n7(["MSTB #35;1"])
    n8(["MSTB #35;2"])
    n9(["MSTB #35;3"])
    n10(["MSTB #35;4"])
  end
  n0 --- n1
  n0 --- n2
  n0 --> n3
  n0 --> n4
  n0 --> n5
  n0 --> n6
  n1 --> n3
  n2 --> n5
  n7 --> n3
  n7 --> n4
  n3 --> n8
  n4 --> n9
  n9 --> n5
  n9 --> n6
  n5 --> n10
  n3 --> n7
  n4 --> n7
  n8 --> n3
  n9 --> n4
  n5 --> n9
  n6 --> n9
  n10 --> n5
  style n0 fill:lightblue,color:#111
  style n1 fill:lightblue,color:#111
  style n2 fill:lightblue,color:#111
  style n7 fill:palegreen,color:#111
  style n8 fill:palegreen,color:#111
  style n9 fill:palegreen,color:#111
  style n10 fill:palegreen,color:#111
  style g0 fill:grey
  linkStyle 2 stroke-dasharray:6 4
  linkStyle 3 stroke-dasharray:6 4
  linkStyle 4 stroke-dasharray:6 4
  linkStyle 5 stroke-dasharray:6 4
  linkStyle 6 stroke-dasharray:6 4
  linkStyle 7 stroke-dasharray:6 4
  linkStyle 15 stroke-dasharray:6 4
  linkStyle 16 stroke-dasharray:6 4
  linkStyle 17 stroke-dasharray:6 4
  linkStyle 18 stroke-dasharray:6 4
  linkStyle 19 stroke-dasharray:6 4
  linkStyle 20 stroke-dasharray:6 4
  linkStyle 21 stroke-dasharray:6 4
```

An example of topology and malloc refs in a DP MST topology with two
active payloads. Topology refcount increments are indicated by solid
lines, and malloc refcount increments are indicated by dashed lines.
Each starts from the branch which incremented the refcount, and ends at
the branch to which the refcount belongs to, i.e. the arrow points the
same way as the C pointers used to reference a structure.


As you can see in the above figure, every branch increments the topology
refcount of its children, and increments the malloc refcount of its
parent. Additionally, every payload increments the malloc refcount of its
assigned port by 1.

So, what would happen if MSTB #3 from the above figure was unplugged from
the system, but the driver hadn't yet removed payload #2 from port #3? The
topology would start to look like the figure below.


```mermaid
flowchart TB
  subgraph g0["#160;"]
    n0["DRM driver"]
    n1["Payload #35;1"]
    n2["Payload #35;2"]
  end
  subgraph g1["Topology Manager"]
    n3(["Port #35;1"])
    n4(["Port #35;2"])
    n5(["Port #35;3"])
    n6(["Port #35;4"])
    n7(["MSTB #35;1"])
    n8(["MSTB #35;2"])
    n9(["MSTB #35;3"])
    n10(["MSTB #35;4"])
  end
  n0 --- n1
  n0 --- n2
  n0 --> n3
  n0 --> n4
  n0 --> n5
  n0 --> n6
  n1 --> n3
  n2 --> n5
  n7 --> n3
  n7 --> n4
  n3 --> n8
  n4 --> n9
  n9 --> n5
  n9 --> n6
  n5 --> n10
  n3 --> n7
  n4 --> n7
  n8 --> n3
  n9 --> n4
  n5 --> n9
  n6 --> n9
  n10 --> n5
  style n0 fill:lightblue,color:#111
  style n1 fill:lightblue,color:#111
  style n2 fill:lightblue,color:#111
  style n6 fill:grey,color:#111
  style n7 fill:palegreen,color:#111
  style n8 fill:palegreen,color:#111
  style n9 fill:palegreen,color:#111
  style n10 fill:grey,color:#111
  style g0 fill:grey
  linkStyle 2 stroke-dasharray:6 4
  linkStyle 3 stroke-dasharray:6 4
  linkStyle 4 stroke-dasharray:6 4
  linkStyle 5 stroke-dasharray:6 4,stroke:red
  linkStyle 6 stroke-dasharray:6 4
  linkStyle 7 stroke-dasharray:6 4
  linkStyle 11 stroke:red
  linkStyle 12 stroke:red
  linkStyle 13 stroke:red
  linkStyle 14 stroke:red
  linkStyle 15 stroke-dasharray:6 4
  linkStyle 16 stroke-dasharray:6 4
  linkStyle 17 stroke-dasharray:6 4
  linkStyle 18 stroke-dasharray:6 4
  linkStyle 19 stroke-dasharray:6 4
  linkStyle 20 stroke-dasharray:6 4,stroke:red
  linkStyle 21 stroke-dasharray:6 4,stroke:red
```

Ports and branch devices which have been released from memory are
colored grey, and references which have been removed are colored red.


Whenever a port or branch device's topology refcount reaches zero, it will
decrement the topology refcounts of all its children, the malloc refcount
of its parent, and finally its own malloc refcount. For MSTB #4 and port
\#4, this means they both have been disconnected from the topology and freed
from memory. But, because payload #2 is still holding a reference to port
\#3, port #3 is removed from the topology but its [`struct drm_dp_mst_port`](#c-struct-drm_dp_mst_port)
is still accessible from memory. This also means port #3 has not yet
decremented the malloc refcount of MSTB #3, so its [`struct drm_dp_mst_branch`](#c-struct-drm_dp_mst_branch) will also stay allocated in memory until port #3's
malloc refcount reaches 0.

This relationship is necessary because in order to release payload #2, we
need to be able to figure out the last relative of port #3 that's still
connected to the topology. In this case, we would travel up the topology as
shown below.


```mermaid
flowchart TB
  subgraph g0["#160;"]
    n0["DRM driver"]
    n1["Payload #35;1"]
    n2["Payload #35;2"]
  end
  subgraph g1["Topology Manager"]
    n3(["Port #35;1"])
    n4(["Port #35;2"])
    n5(["Port #35;3"])
    n6(["Port #35;4"])
    n7(["MSTB #35;1"])
    n8(["MSTB #35;2"])
    n9(["MSTB #35;3"])
    n10(["MSTB #35;4"])
  end
  n0 --- n1
  n0 --- n2
  n0 --> n3
  n0 --> n4
  n0 --> n5
  n0 --> n6
  n1 --> n3
  n2 --> n5
  n7 --> n3
  n7 --> n4
  n3 --> n8
  n4 --> n9
  n9 --> n5
  n9 --> n6
  n5 --> n10
  n3 --> n7
  n4 --> n7
  n8 --> n3
  n9 --> n4
  n5 --> n9
  n6 --> n9
  n10 --> n5
  style n0 fill:lightblue,color:#111
  style n1 fill:lightblue,color:#111
  style n2 fill:lightblue,color:#111
  style n6 fill:grey,color:#111
  style n7 fill:palegreen,color:#111
  style n8 fill:palegreen,color:#111
  style n9 fill:palegreen,color:#111
  style n10 fill:grey,color:#111
  style g0 fill:grey
  linkStyle 2 stroke-dasharray:6 4
  linkStyle 3 stroke-dasharray:6 4
  linkStyle 4 stroke-dasharray:6 4
  linkStyle 5 stroke-dasharray:6 4,stroke:grey
  linkStyle 6 stroke-dasharray:6 4
  linkStyle 7 stroke-dasharray:6 4
  linkStyle 11 stroke:grey
  linkStyle 12 stroke:grey
  linkStyle 13 stroke:grey
  linkStyle 14 stroke:grey
  linkStyle 15 stroke-dasharray:6 4
  linkStyle 16 stroke-dasharray:6 4
  linkStyle 17 stroke-dasharray:6 4
  linkStyle 18 stroke-dasharray:6 4
  linkStyle 19 stroke-dasharray:6 4
  linkStyle 20 stroke-dasharray:6 4,stroke:grey
  linkStyle 21 stroke-dasharray:6 4,stroke:grey
```




And finally, remove payload #2 by communicating with port #2 through
sideband transactions.


<a id="rst-functions-reference-1"></a>

### Functions Reference


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

MST port

**Definition**

```c
struct drm_dp_mst_port {
        struct kref topology_kref;
        struct kref malloc_kref;
    #if IS_ENABLED(CONFIG_DRM_DEBUG_DP_MST_TOPOLOGY_REFS);
        struct drm_dp_mst_topology_ref_history topology_ref_history;
    #endif;
        u8 port_num;
        bool input;
        bool mcs;
        bool ddps;
        u8 pdt;
        bool ldps;
        u8 dpcd_rev;
        u8 num_sdp_streams;
        u8 num_sdp_stream_sinks;
        uint16_t full_pbn;
        struct list_head next;
        struct drm_dp_mst_branch *mstb;
        struct drm_dp_aux aux;
        struct drm_dp_aux *passthrough_aux;
        struct drm_dp_mst_branch *parent;
        struct drm_connector *connector;
        struct drm_dp_mst_topology_mgr *mgr;
        const struct drm_edid *cached_edid;
        bool fec_capable;
};
```

**Members**

- `topology_kref`: refcount for this port's lifetime in the topology,
  only the DP MST helpers should need to touch this
- `malloc_kref`: refcount for the memory allocation containing this
  structure. See [`drm_dp_mst_get_port_malloc()`](#c-drm_dp_mst_get_port_malloc) and
  [`drm_dp_mst_put_port_malloc()`](#c-drm_dp_mst_put_port_malloc).
- `topology_ref_history`: A history of each topology
  reference/dereference. See CONFIG_DRM_DEBUG_DP_MST_TOPOLOGY_REFS.
- `port_num`: port number
- `input`: if this port is an input port. Protected by
  [`drm_dp_mst_topology_mgr.base`](#c-struct-drm_dp_mst_topology_mgr).lock.
- `mcs`: message capability status - DP 1.2 spec. Protected by
  [`drm_dp_mst_topology_mgr.base`](#c-struct-drm_dp_mst_topology_mgr).lock.
- `ddps`: DisplayPort Device Plug Status - DP 1.2. Protected by
  [`drm_dp_mst_topology_mgr.base`](#c-struct-drm_dp_mst_topology_mgr).lock.
- `pdt`: Peer Device Type. Protected by
  [`drm_dp_mst_topology_mgr.base`](#c-struct-drm_dp_mst_topology_mgr).lock.
- `ldps`: Legacy Device Plug Status. Protected by
  [`drm_dp_mst_topology_mgr.base`](#c-struct-drm_dp_mst_topology_mgr).lock.
- `dpcd_rev`: DPCD revision of device on this port. Protected by
  [`drm_dp_mst_topology_mgr.base`](#c-struct-drm_dp_mst_topology_mgr).lock.
- `num_sdp_streams`: Number of simultaneous streams. Protected by
  [`drm_dp_mst_topology_mgr.base`](#c-struct-drm_dp_mst_topology_mgr).lock.
- `num_sdp_stream_sinks`: Number of stream sinks. Protected by
  [`drm_dp_mst_topology_mgr.base`](#c-struct-drm_dp_mst_topology_mgr).lock.
- `full_pbn`: Max possible bandwidth for this port. Protected by
  [`drm_dp_mst_topology_mgr.base`](#c-struct-drm_dp_mst_topology_mgr).lock.
- `next`: link to next port on this branch device
- `mstb`: the branch device connected to this port, if there is one.
  This should be considered protected for reading by
  [`drm_dp_mst_topology_mgr.lock`](#c-struct-drm_dp_mst_topology_mgr). There are two exceptions to this:
  [`drm_dp_mst_topology_mgr.up_req_work`](#c-struct-drm_dp_mst_topology_mgr) and
  [`drm_dp_mst_topology_mgr.work`](#c-struct-drm_dp_mst_topology_mgr), which do not grab
  [`drm_dp_mst_topology_mgr.lock`](#c-struct-drm_dp_mst_topology_mgr) during reads but are the only
  updaters of this list and are protected from writing concurrently
  by [`drm_dp_mst_topology_mgr.probe_lock`](#c-struct-drm_dp_mst_topology_mgr).
- `aux`: i2c aux transport to talk to device connected to this port, protected
  by [`drm_dp_mst_topology_mgr.base`](#c-struct-drm_dp_mst_topology_mgr).lock.
- `passthrough_aux`: parent aux to which DSC pass-through requests should be
  sent, only set if DSC pass-through is possible.
- `parent`: branch device parent of this port
- `connector`: DRM connector this port is connected to. Protected by
  [`drm_dp_mst_topology_mgr.base`](#c-struct-drm_dp_mst_topology_mgr).lock.
- `mgr`: topology manager this port lives under.
- `cached_edid`: for DP logical ports - make tiling work by ensuring
  that the EDID for all connectors is read immediately.
- `fec_capable`: bool indicating if FEC can be supported up to that
  point in the MST topology.

**Description**

This structure represents an MST port endpoint on a device somewhere
in the MST topology.

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

MST branch device.

**Definition**

```c
struct drm_dp_mst_branch {
        struct kref topology_kref;
        struct kref malloc_kref;
    #if IS_ENABLED(CONFIG_DRM_DEBUG_DP_MST_TOPOLOGY_REFS);
        struct drm_dp_mst_topology_ref_history topology_ref_history;
    #endif;
        struct list_head destroy_next;
        u8 rad[8];
        u8 lct;
        int num_ports;
        struct list_head ports;
        struct drm_dp_mst_port *port_parent;
        struct drm_dp_mst_topology_mgr *mgr;
        bool link_address_sent;
        guid_t guid;
};
```

**Members**

- `topology_kref`: refcount for this branch device's lifetime in the
  topology, only the DP MST helpers should need to touch this
- `malloc_kref`: refcount for the memory allocation containing this
  structure. See [`drm_dp_mst_get_mstb_malloc()`](#c-drm_dp_mst_get_mstb_malloc) and
  [`drm_dp_mst_put_mstb_malloc()`](#c-drm_dp_mst_put_mstb_malloc).
- `topology_ref_history`: A history of each topology
  reference/dereference. See CONFIG_DRM_DEBUG_DP_MST_TOPOLOGY_REFS.
- `destroy_next`: linked-list entry used by
  `drm_dp_delayed_destroy_work()`
- `rad`: Relative Address of the MST branch.
  For [`drm_dp_mst_topology_mgr.mst_primary`](#c-struct-drm_dp_mst_topology_mgr), it's rad\[8\] are all 0,
  unset and unused. For MST branches connected after mst_primary,
  in each element of rad\[\] the nibbles are ordered by the most
  signifcant 4 bits first and the least significant 4 bits second.
- `lct`: Link count total to talk to this branch device.
- `num_ports`: number of ports on the branch.
- `ports`: the list of ports on this branch device. This should be
  considered protected for reading by [`drm_dp_mst_topology_mgr.lock`](#c-struct-drm_dp_mst_topology_mgr).
  There are two exceptions to this:
  [`drm_dp_mst_topology_mgr.up_req_work`](#c-struct-drm_dp_mst_topology_mgr) and
  [`drm_dp_mst_topology_mgr.work`](#c-struct-drm_dp_mst_topology_mgr), which do not grab
  [`drm_dp_mst_topology_mgr.lock`](#c-struct-drm_dp_mst_topology_mgr) during reads but are the only
  updaters of this list and are protected from updating the list
  concurrently by **drm_dp_mst_topology_mgr.probe_lock**
- `port_parent`: pointer to the port parent, NULL if toplevel.
- `mgr`: topology manager for this branch device.
- `link_address_sent`: if a link address message has been sent to this device yet.
- `guid`: guid for DP 1.2 branch device. port under this branch can be
  identified by port #.

**Description**

This structure represents an MST branch device, there is one
primary branch device at the root, along with any other branches connected
to downstream port of parent branches.

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

Atomic state struct for an MST payload

**Definition**

```c
struct drm_dp_mst_atomic_payload {
    struct drm_dp_mst_port *port;
    s8 vc_start_slot;
    u8 vcpi;
    int time_slots;
    int pbn;
    bool delete : 1;
    bool dsc_enabled : 1;
    enum drm_dp_mst_payload_allocation payload_allocation_status;
    struct list_head next;
};
```

**Members**

- `port`: The MST port assigned to this payload
- `vc_start_slot`: The time slot that this payload starts on. Because payload start slots
  can't be determined ahead of time, the contents of this value are UNDEFINED at atomic
  check time. This shouldn't usually matter, as the start slot should never be relevant for
  atomic state computations.

  Since this value is determined at commit time instead of check time, this value is
  protected by the MST helpers ensuring that async commits operating on the given topology
  never run in parallel. In the event that a driver does need to read this value (e.g. to
  inform hardware of the starting timeslot for a payload), the driver may either:

  * Read this field during the atomic commit after
    [`drm_dp_mst_atomic_wait_for_dependencies()`](#c-drm_dp_mst_atomic_wait_for_dependencies) has been called, which will ensure the
    previous MST states payload start slots have been copied over to the new state. Note
    that a new start slot won't be assigned/removed from this payload until
    [`drm_dp_add_payload_part1()`](#c-drm_dp_add_payload_part1)/[`drm_dp_remove_payload_part2()`](#c-drm_dp_remove_payload_part2) have been called.
  * Acquire the MST modesetting lock, and then wait for any pending MST-related commits to
    get committed to hardware by calling [`drm_crtc_commit_wait()`](/kernel/hardware/gpu/drm-kms.md#c-drm_crtc_commit_wait) on each of the
    [`drm_crtc_commit`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_crtc_commit) structs in [`drm_dp_mst_topology_state.commit_deps`](#c-struct-drm_dp_mst_topology_state).

  If neither of the two above solutions suffice (e.g. the driver needs to read the start
  slot in the middle of an atomic commit without waiting for some reason), then drivers
  should cache this value themselves after changing payloads.
- `vcpi`: The Virtual Channel Payload Identifier
- `time_slots`: The number of timeslots allocated to this payload from the source DP Tx to
  the immediate downstream DP Rx
- `pbn`: The payload bandwidth for this payload
- `delete`: Whether or not we intend to delete this payload during this atomic commit
- `dsc_enabled`: Whether or not this payload has DSC enabled
- `payload_allocation_status`: The allocation status of this payload
- `next`: The list node for this payload

**Description**

The primary atomic state structure for a given MST payload. Stores information like current
bandwidth allocation, intended action for this payload, etc.

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

DisplayPort MST topology atomic state

**Definition**

```c
struct drm_dp_mst_topology_state {
    struct drm_private_state base;
    struct drm_dp_mst_topology_mgr *mgr;
    u32 pending_crtc_mask;
    struct drm_crtc_commit **commit_deps;
    size_t num_commit_deps;
    u32 payload_mask;
    struct list_head payloads;
    u8 total_avail_slots;
    u8 start_slot;
    fixed20_12 pbn_div;
};
```

**Members**

- `base`: Base private state for atomic
- `mgr`: The topology manager
- `pending_crtc_mask`: A bitmask of all CRTCs this topology state touches, drivers may
  modify this to add additional dependencies if needed.
- `commit_deps`: A list of all CRTC commits affecting this topology, this field isn't
  populated until [`drm_dp_mst_atomic_wait_for_dependencies()`](#c-drm_dp_mst_atomic_wait_for_dependencies) is called.
- `num_commit_deps`: The number of CRTC commits in **commit_deps**
- `payload_mask`: A bitmask of allocated VCPIs, used for VCPI assignments
- `payloads`: The list of payloads being created/destroyed in this state
- `total_avail_slots`: The total number of slots this topology can handle (63 or 64)
- `start_slot`: The first usable time slot in this topology (1 or 0)
- `pbn_div`: The current PBN divisor for this topology. The driver is expected to fill this
  out itself.

**Description**

This struct represents the atomic state of the toplevel DisplayPort MST manager

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

DisplayPort MST manager

**Definition**

```c
struct drm_dp_mst_topology_mgr {
        struct drm_private_obj base;
        struct drm_device *dev;
        const struct drm_dp_mst_topology_cbs *cbs;
        int max_dpcd_transaction_bytes;
        struct drm_dp_aux *aux;
        int max_payloads;
        int conn_base_id;
        struct drm_dp_sideband_msg_rx up_req_recv;
        struct drm_dp_sideband_msg_rx down_rep_recv;
        struct mutex lock;
        struct mutex probe_lock;
        bool mst_state : 1;
        bool payload_id_table_cleared : 1;
        bool reset_rx_state : 1;
        u8 payload_count;
        u8 next_start_slot;
        struct drm_dp_mst_branch *mst_primary;
        u8 dpcd[DP_RECEIVER_CAP_SIZE];
        u8 sink_count;
        const struct drm_private_state_funcs *funcs;
        struct mutex qlock;
        struct list_head tx_msg_downq;
        wait_queue_head_t tx_waitq;
        struct work_struct work;
        struct work_struct tx_work;
        struct list_head destroy_port_list;
        struct list_head destroy_branch_device_list;
        struct mutex delayed_destroy_lock;
        struct workqueue_struct *delayed_destroy_wq;
        struct work_struct delayed_destroy_work;
        struct list_head up_req_list;
        struct mutex up_req_lock;
        struct work_struct up_req_work;
    #if IS_ENABLED(CONFIG_DRM_DEBUG_DP_MST_TOPOLOGY_REFS);
        struct mutex topology_ref_history_lock;
    #endif;
};
```

**Members**

- `base`: Base private object for atomic
- `dev`: device pointer for adding i2c devices etc.
- `cbs`: callbacks for connector addition and destruction.
- `max_dpcd_transaction_bytes`: maximum number of bytes to read/write
  in one go.
- `aux`: AUX channel for the DP MST connector this topolgy mgr is
  controlling.
- `max_payloads`: maximum number of payloads the GPU can generate.
- `conn_base_id`: DRM connector ID this mgr is connected to. Only used
  to build the MST connector path value.
- `up_req_recv`: Message receiver state for up requests.
- `down_rep_recv`: Message receiver state for replies to down
  requests.
- `lock`: protects **mst_state**, **mst_primary**, **dpcd**, and
  **payload_id_table_cleared**.
- `probe_lock`: Prevents **work** and **up_req_work**, the only writers of
  [`drm_dp_mst_port.mstb`](#c-struct-drm_dp_mst_port) and [`drm_dp_mst_branch.ports`](#c-struct-drm_dp_mst_branch), from racing
  while they update the topology.
- `mst_state`: If this manager is enabled for an MST capable port. False
  if no MST sink/branch devices is connected.
- `payload_id_table_cleared`: Whether or not we've cleared the payload
  ID table for **mst_primary**. Protected by **lock**.
- `reset_rx_state`: The down request's reply and up request message
  receiver state must be reset, after the topology manager got
  removed. Protected by **lock**.
- `payload_count`: The number of currently active payloads in hardware. This value is only
  intended to be used internally by MST helpers for payload tracking, and is only safe to
  read/write from the atomic commit (not check) context.
- `next_start_slot`: The starting timeslot to use for new VC payloads. This value is used
  internally by MST helpers for payload tracking, and is only safe to read/write from the
  atomic commit (not check) context.
- `mst_primary`: Pointer to the primary/first branch device.
- `dpcd`: Cache of DPCD for primary port.
- `sink_count`: Sink count from DEVICE_SERVICE_IRQ_VECTOR_ESI0.
- `funcs`: Atomic helper callbacks
- `qlock`: protects **tx_msg_downq** and `drm_dp_sideband_msg_tx.state`
- `tx_msg_downq`: List of pending down requests
- `tx_waitq`: Wait to queue stall for the tx worker.
- `work`: Probe work.
- `tx_work`: Sideband transmit worker. This can nest within the main
  **work** worker for each transaction **work** launches.
- `destroy_port_list`: List of to be destroyed connectors.
- `destroy_branch_device_list`: List of to be destroyed branch
  devices.
- `delayed_destroy_lock`: Protects **destroy_port_list** and
  **destroy_branch_device_list**.
- `delayed_destroy_wq`: Workqueue used for delayed_destroy_work items.
  A dedicated WQ makes it possible to drain any requeued work items
  on it.
- `delayed_destroy_work`: Work item to destroy MST port and branch
  devices, needed to avoid locking inversion.
- `up_req_list`: List of pending up requests from the topology that
  need to be processed, in chronological order.
- `up_req_lock`: Protects **up_req_list**
- `up_req_work`: Work item to process up requests received from the
  topology. Needed to avoid blocking hotplug handling and sideband
  transmissions.
- `topology_ref_history_lock`: protects
  [`drm_dp_mst_port.topology_ref_history`](#c-struct-drm_dp_mst_port) and
  [`drm_dp_mst_branch.topology_ref_history`](#c-struct-drm_dp_mst_branch).

**Description**

This struct represents the toplevel displayport MST topology manager.
There should be one instance of this for every MST capable DP connector
on the GPU.

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

sink's MST mode capability

**Constants**

- `DRM_DP_SST`: The sink does not support MST nor single stream sideband
  messaging.
- `DRM_DP_MST`: Sink supports MST, more than one stream and single
  stream sideband messaging.
- `DRM_DP_SST_SIDEBAND_MSG`: Sink supports only one stream and single
  stream sideband messaging.

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

```c
bool __drm_dp_mst_state_iter_get(struct drm_atomic_state *state, struct drm_dp_mst_topology_mgr **mgr, struct drm_dp_mst_topology_state **old_state, struct drm_dp_mst_topology_state **new_state, int i)
```

private atomic state iterator function for macro-internal use

**Parameters**

- `struct drm_atomic_state *state`: [`struct drm_atomic_state`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_atomic_state) pointer
- `struct drm_dp_mst_topology_mgr **mgr`: pointer to the [`struct drm_dp_mst_topology_mgr`](#c-struct-drm_dp_mst_topology_mgr) iteration cursor
- `struct drm_dp_mst_topology_state **old_state`: optional pointer to the old [`struct drm_dp_mst_topology_state`](#c-struct-drm_dp_mst_topology_state)
  iteration cursor
- `struct drm_dp_mst_topology_state **new_state`: optional pointer to the new [`struct drm_dp_mst_topology_state`](#c-struct-drm_dp_mst_topology_state)
  iteration cursor
- `int i`: int iteration cursor, for macro-internal use

**Description**

Used by [`for_each_oldnew_mst_mgr_in_state()`](#c-for_each_oldnew_mst_mgr_in_state),
[`for_each_old_mst_mgr_in_state()`](#c-for_each_old_mst_mgr_in_state), and [`for_each_new_mst_mgr_in_state()`](#c-for_each_new_mst_mgr_in_state). Don't
call this directly.

**Return**

True if the current [`struct drm_private_obj`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_private_obj) is a [`struct drm_dp_mst_topology_mgr`](#c-struct-drm_dp_mst_topology_mgr), false otherwise.

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

```c
for_each_oldnew_mst_mgr_in_state(__state, mgr, old_state, new_state, __i)
```

iterate over all DP MST topology managers in an atomic update

**Parameters**

- `__state`: [`struct drm_atomic_state`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_atomic_state) pointer
- `mgr`: [`struct drm_dp_mst_topology_mgr`](#c-struct-drm_dp_mst_topology_mgr) iteration cursor
- `old_state`: [`struct drm_dp_mst_topology_state`](#c-struct-drm_dp_mst_topology_state) iteration cursor for the old
  state
- `new_state`: [`struct drm_dp_mst_topology_state`](#c-struct-drm_dp_mst_topology_state) iteration cursor for the new
  state
- `__i`: int iteration cursor, for macro-internal use

**Description**

This iterates over all DRM DP MST topology managers in an atomic update,
tracking both old and new state. This is useful in places where the state
delta needs to be considered, for example in atomic check functions.

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

```c
for_each_old_mst_mgr_in_state(__state, mgr, old_state, __i)
```

iterate over all DP MST topology managers in an atomic update

**Parameters**

- `__state`: [`struct drm_atomic_state`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_atomic_state) pointer
- `mgr`: [`struct drm_dp_mst_topology_mgr`](#c-struct-drm_dp_mst_topology_mgr) iteration cursor
- `old_state`: [`struct drm_dp_mst_topology_state`](#c-struct-drm_dp_mst_topology_state) iteration cursor for the old
  state
- `__i`: int iteration cursor, for macro-internal use

**Description**

This iterates over all DRM DP MST topology managers in an atomic update,
tracking only the old state. This is useful in disable functions, where we
need the old state the hardware is still in.

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

```c
for_each_new_mst_mgr_in_state(__state, mgr, new_state, __i)
```

iterate over all DP MST topology managers in an atomic update

**Parameters**

- `__state`: [`struct drm_atomic_state`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_atomic_state) pointer
- `mgr`: [`struct drm_dp_mst_topology_mgr`](#c-struct-drm_dp_mst_topology_mgr) iteration cursor
- `new_state`: [`struct drm_dp_mst_topology_state`](#c-struct-drm_dp_mst_topology_state) iteration cursor for the new
  state
- `__i`: int iteration cursor, for macro-internal use

**Description**

This iterates over all DRM DP MST topology managers in an atomic update,
tracking only the new state. This is useful in enable functions, where we
need the new state the hardware should be in when the atomic commit
operation has completed.



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

```c
void drm_dp_mst_get_port_malloc(struct drm_dp_mst_port *port)
```

Increment the malloc refcount of an MST port

**Parameters**

- `struct drm_dp_mst_port *port`: The [`struct drm_dp_mst_port`](#c-struct-drm_dp_mst_port) to increment the malloc refcount of

**Description**

Increments [`drm_dp_mst_port.malloc_kref`](#c-struct-drm_dp_mst_port). When [`drm_dp_mst_port.malloc_kref`](#c-struct-drm_dp_mst_port)
reaches 0, the memory allocation for **port** will be released and **port** may
no longer be used.

Because **port** could potentially be freed at any time by the DP MST helpers
if [`drm_dp_mst_port.malloc_kref`](#c-struct-drm_dp_mst_port) reaches 0, including during a call to this
function, drivers that which to make use of [`struct drm_dp_mst_port`](#c-struct-drm_dp_mst_port) should
ensure that they grab at least one main malloc reference to their MST ports
in `drm_dp_mst_topology_cbs.add_connector`. This callback is called before
there is any chance for [`drm_dp_mst_port.malloc_kref`](#c-struct-drm_dp_mst_port) to reach 0.

See also: [`drm_dp_mst_put_port_malloc()`](#c-drm_dp_mst_put_port_malloc)

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

```c
void drm_dp_mst_put_port_malloc(struct drm_dp_mst_port *port)
```

Decrement the malloc refcount of an MST port

**Parameters**

- `struct drm_dp_mst_port *port`: The [`struct drm_dp_mst_port`](#c-struct-drm_dp_mst_port) to decrement the malloc refcount of

**Description**

Decrements [`drm_dp_mst_port.malloc_kref`](#c-struct-drm_dp_mst_port). When [`drm_dp_mst_port.malloc_kref`](#c-struct-drm_dp_mst_port)
reaches 0, the memory allocation for **port** will be released and **port** may
no longer be used.

See also: [`drm_dp_mst_get_port_malloc()`](#c-drm_dp_mst_get_port_malloc)

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

```c
int drm_dp_mst_connector_late_register(struct drm_connector *connector, struct drm_dp_mst_port *port)
```

Late MST connector registration

**Parameters**

- `struct drm_connector *connector`: The MST connector
- `struct drm_dp_mst_port *port`: The MST port for this connector

**Description**

Helper to register the remote aux device for this MST port. Drivers should
call this from their mst connector's late_register hook to enable MST aux
devices.

**Return**

0 on success, negative error code on failure.

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

```c
void drm_dp_mst_connector_early_unregister(struct drm_connector *connector, struct drm_dp_mst_port *port)
```

Early MST connector unregistration

**Parameters**

- `struct drm_connector *connector`: The MST connector
- `struct drm_dp_mst_port *port`: The MST port for this connector

**Description**

Helper to unregister the remote aux device for this MST port, registered by
[`drm_dp_mst_connector_late_register()`](#c-drm_dp_mst_connector_late_register). Drivers should call this from their mst
connector's early_unregister hook.

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

```c
int drm_dp_add_payload_part1(struct drm_dp_mst_topology_mgr *mgr, struct drm_dp_mst_topology_state *mst_state, struct drm_dp_mst_atomic_payload *payload)
```

Execute payload update part 1

**Parameters**

- `struct drm_dp_mst_topology_mgr *mgr`: Manager to use.
- `struct drm_dp_mst_topology_state *mst_state`: The MST atomic state
- `struct drm_dp_mst_atomic_payload *payload`: The payload to write

**Description**

Determines the starting time slot for the given payload, and programs the VCPI for this payload
into the DPCD of DPRX. After calling this, the driver should generate ACT and payload packets.

**Return**

0 on success, error code on failure.

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

```c
void drm_dp_remove_payload_part1(struct drm_dp_mst_topology_mgr *mgr, struct drm_dp_mst_topology_state *mst_state, struct drm_dp_mst_atomic_payload *payload)
```

Remove an MST payload along the virtual channel

**Parameters**

- `struct drm_dp_mst_topology_mgr *mgr`: Manager to use.
- `struct drm_dp_mst_topology_state *mst_state`: The MST atomic state
- `struct drm_dp_mst_atomic_payload *payload`: The payload to remove

**Description**

Removes a payload along the virtual channel if it was successfully allocated.
After calling this, the driver should set HW to generate ACT and then switch to new
payload allocation state.

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

```c
void drm_dp_remove_payload_part2(struct drm_dp_mst_topology_mgr *mgr, struct drm_dp_mst_topology_state *mst_state, const struct drm_dp_mst_atomic_payload *old_payload, struct drm_dp_mst_atomic_payload *new_payload)
```

Remove an MST payload locally

**Parameters**

- `struct drm_dp_mst_topology_mgr *mgr`: Manager to use.
- `struct drm_dp_mst_topology_state *mst_state`: The MST atomic state
- `const struct drm_dp_mst_atomic_payload *old_payload`: The payload with its old state
- `struct drm_dp_mst_atomic_payload *new_payload`: The payload with its latest state

**Description**

Updates the starting time slots of all other payloads which would have been shifted towards
the start of the payload ID table as a result of removing a payload. Driver should call this
function whenever it removes a payload in its HW. It's independent to the result of payload
allocation/deallocation at branch devices along the virtual channel.

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

```c
int drm_dp_add_payload_part2(struct drm_dp_mst_topology_mgr *mgr, struct drm_dp_mst_atomic_payload *payload)
```

Execute payload update part 2

**Parameters**

- `struct drm_dp_mst_topology_mgr *mgr`: Manager to use.
- `struct drm_dp_mst_atomic_payload *payload`: The payload to update

**Description**

If **payload** was successfully assigned a starting time slot by [`drm_dp_add_payload_part1()`](#c-drm_dp_add_payload_part1), this
function will send the sideband messages to finish allocating this payload.

**Return**

0 on success, negative error code on failure.

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

```c
fixed20_12 drm_dp_get_vc_payload_bw(int link_rate, int link_lane_count)
```

get the VC payload BW for an MTP link

**Parameters**

- `int link_rate`: link rate in 10kbits/s units
- `int link_lane_count`: lane count

**Description**

Calculate the total bandwidth of a MultiStream Transport link. The returned
value is in units of PBNs/(timeslots/1 MTP). This value can be used to
convert the number of PBNs required for a given stream to the number of
timeslots this stream requires in each MTP.

Returns the BW / timeslot value in 20.12 fixed point format.

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

```c
enum drm_dp_mst_mode drm_dp_read_mst_cap(struct drm_dp_aux *aux, const u8 dpcd[DP_RECEIVER_CAP_SIZE])
```

Read the sink's MST mode capability

**Parameters**

- `struct drm_dp_aux *aux`: The DP AUX channel to use
- `const u8 dpcd[DP_RECEIVER_CAP_SIZE]`: A cached copy of the DPCD capabilities for this sink

**Return**

enum drm_dp_mst_mode to indicate MST mode capability

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

```c
int drm_dp_mst_topology_mgr_set_mst(struct drm_dp_mst_topology_mgr *mgr, bool mst_state)
```

Set the MST state for a topology manager

**Parameters**

- `struct drm_dp_mst_topology_mgr *mgr`: manager to set state for
- `bool mst_state`: true to enable MST on this connector - false to disable.

**Description**

This is called by the driver when it detects an MST capable device plugged
into a DP MST capable port, or when a DP MST capable device is unplugged.

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

```c
void drm_dp_mst_topology_queue_probe(struct drm_dp_mst_topology_mgr *mgr)
```

Queue a topology probe

**Parameters**

- `struct drm_dp_mst_topology_mgr *mgr`: manager to probe

**Description**

Queue a work to probe the MST topology. Driver's should call this only to
sync the topology's HW->SW state after the MST link's parameters have
changed in a way the state could've become out-of-sync. This is the case
for instance when the link rate between the source and first downstream
branch device has switched between UHBR and non-UHBR rates. Except of those
cases - for instance when a sink gets plugged/unplugged to a port - the SW
state will get updated automatically via MST UP message notifications.

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

```c
void drm_dp_mst_topology_mgr_suspend(struct drm_dp_mst_topology_mgr *mgr)
```

suspend the MST manager

**Parameters**

- `struct drm_dp_mst_topology_mgr *mgr`: manager to suspend

**Description**

This function tells the MST device that we can't handle UP messages
anymore. This should stop it from sending any since we are suspended.

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

```c
int drm_dp_mst_topology_mgr_resume(struct drm_dp_mst_topology_mgr *mgr, bool sync)
```

resume the MST manager

**Parameters**

- `struct drm_dp_mst_topology_mgr *mgr`: manager to resume
- `bool sync`: whether or not to perform topology reprobing synchronously

**Description**

This will fetch DPCD and see if the device is still there,
if it is, it will rewrite the MSTM control bits, and return.

If the device fails this returns -1, and the driver should do
a full MST reprobe, in case we were undocked.

During system resume (where it is assumed that the driver will be calling
[`drm_atomic_helper_resume()`](#c-drm_atomic_helper_resume)) this function should be called beforehand with
**sync** set to true. In contexts like runtime resume where the driver is not
expected to be calling [`drm_atomic_helper_resume()`](#c-drm_atomic_helper_resume), this function should be
called with **sync** set to false in order to avoid deadlocking.

**Return**

-1 if the MST topology was removed while we were suspended, 0
otherwise.

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

```c
int drm_dp_mst_hpd_irq_handle_event(struct drm_dp_mst_topology_mgr *mgr, const u8 *esi, u8 *ack, bool *handled)
```

MST hotplug IRQ handle MST event

**Parameters**

- `struct drm_dp_mst_topology_mgr *mgr`: manager to notify irq for.
- `const u8 *esi`: 4 bytes from SINK_COUNT_ESI
- `u8 *ack`: 4 bytes used to ack events starting from SINK_COUNT_ESI
- `bool *handled`: whether the hpd interrupt was consumed or not

**Description**

This should be called from the driver when it detects a HPD IRQ,
along with the value of the DEVICE_SERVICE_IRQ_VECTOR_ESI0. The
topology manager will process the sideband messages received
as indicated in the DEVICE_SERVICE_IRQ_VECTOR_ESI0 and set the
corresponding flags that Driver has to ack the DP receiver later.

Note that driver shall also call
[`drm_dp_mst_hpd_irq_send_new_request()`](#c-drm_dp_mst_hpd_irq_send_new_request) if the 'handled' is set
after calling this function, to try to kick off a new request in
the queue if the previous message transaction is completed.

See also:
[`drm_dp_mst_hpd_irq_send_new_request()`](#c-drm_dp_mst_hpd_irq_send_new_request)

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

```c
void drm_dp_mst_hpd_irq_send_new_request(struct drm_dp_mst_topology_mgr *mgr)
```

MST hotplug IRQ kick off new request

**Parameters**

- `struct drm_dp_mst_topology_mgr *mgr`: manager to notify irq for.

**Description**

This should be called from the driver when mst irq event is handled
and acked. Note that new down request should only be sent when
previous message transaction is completed. Source is not supposed to generate
interleaved message transactions.

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

```c
int drm_dp_mst_detect_port(struct drm_connector *connector, struct drm_modeset_acquire_ctx *ctx, struct drm_dp_mst_topology_mgr *mgr, struct drm_dp_mst_port *port)
```

get connection status for an MST port

**Parameters**

- `struct drm_connector *connector`: DRM connector for this port
- `struct drm_modeset_acquire_ctx *ctx`: The acquisition context to use for grabbing locks
- `struct drm_dp_mst_topology_mgr *mgr`: manager for this port
- `struct drm_dp_mst_port *port`: pointer to a port

**Description**

This returns the current connection state for a port.

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

```c
const struct drm_edid * drm_dp_mst_edid_read(struct drm_connector *connector, struct drm_dp_mst_topology_mgr *mgr, struct drm_dp_mst_port *port)
```

get EDID for an MST port

**Parameters**

- `struct drm_connector *connector`: toplevel connector to get EDID for
- `struct drm_dp_mst_topology_mgr *mgr`: manager for this port
- `struct drm_dp_mst_port *port`: unverified pointer to a port.

**Description**

This returns an EDID for the port connected to a connector,
It validates the pointer still exists so the caller doesn't require a
reference.

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

```c
struct edid * drm_dp_mst_get_edid(struct drm_connector *connector, struct drm_dp_mst_topology_mgr *mgr, struct drm_dp_mst_port *port)
```

get EDID for an MST port

**Parameters**

- `struct drm_connector *connector`: toplevel connector to get EDID for
- `struct drm_dp_mst_topology_mgr *mgr`: manager for this port
- `struct drm_dp_mst_port *port`: unverified pointer to a port.

**Description**

This function is deprecated; please use [`drm_dp_mst_edid_read()`](#c-drm_dp_mst_edid_read) instead.

This returns an EDID for the port connected to a connector,
It validates the pointer still exists so the caller doesn't require a
reference.

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

```c
int drm_dp_atomic_find_time_slots(struct drm_atomic_state *state, struct drm_dp_mst_topology_mgr *mgr, struct drm_dp_mst_port *port, int pbn)
```

Find and add time slots to the state

**Parameters**

- `struct drm_atomic_state *state`: global atomic state
- `struct drm_dp_mst_topology_mgr *mgr`: MST topology manager for the port
- `struct drm_dp_mst_port *port`: port to find time slots for
- `int pbn`: bandwidth required for the mode in PBN

**Description**

Allocates time slots to **port**, replacing any previous time slot allocations it may
have had. Any atomic drivers which support MST must call this function in
their [`drm_encoder_helper_funcs.atomic_check()`](#c-struct-drm_encoder_helper_funcs) callback unconditionally to
change the current time slot allocation for the new state, and ensure the MST
atomic state is added whenever the state of payloads in the topology changes.

Allocations set by this function are not checked against the bandwidth
restraints of **mgr** until the driver calls [`drm_dp_mst_atomic_check()`](#c-drm_dp_mst_atomic_check).

Additionally, it is OK to call this function multiple times on the same
**port** as needed. It is not OK however, to call this function and
[`drm_dp_atomic_release_time_slots()`](#c-drm_dp_atomic_release_time_slots) in the same atomic check phase.

See also:
[`drm_dp_atomic_release_time_slots()`](#c-drm_dp_atomic_release_time_slots)
[`drm_dp_mst_atomic_check()`](#c-drm_dp_mst_atomic_check)

**Return**

Total slots in the atomic state assigned for this port, or a negative error
code if the port no longer exists

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

```c
int drm_dp_atomic_release_time_slots(struct drm_atomic_state *state, struct drm_dp_mst_topology_mgr *mgr, struct drm_dp_mst_port *port)
```

Release allocated time slots

**Parameters**

- `struct drm_atomic_state *state`: global atomic state
- `struct drm_dp_mst_topology_mgr *mgr`: MST topology manager for the port
- `struct drm_dp_mst_port *port`: The port to release the time slots from

**Description**

Releases any time slots that have been allocated to a port in the atomic
state. Any atomic drivers which support MST must call this function
unconditionally in their [`drm_connector_helper_funcs.atomic_check()`](#c-struct-drm_connector_helper_funcs) callback.
This helper will check whether time slots would be released by the new state and
respond accordingly, along with ensuring the MST state is always added to the
atomic state whenever a new state would modify the state of payloads on the
topology.

It is OK to call this even if **port** has been removed from the system.
Additionally, it is OK to call this function multiple times on the same
**port** as needed. It is not OK however, to call this function and
[`drm_dp_atomic_find_time_slots()`](#c-drm_dp_atomic_find_time_slots) on the same **port** in a single atomic check
phase.

See also:
[`drm_dp_atomic_find_time_slots()`](#c-drm_dp_atomic_find_time_slots)
[`drm_dp_mst_atomic_check()`](#c-drm_dp_mst_atomic_check)

**Return**

0 on success, negative error code otherwise

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

```c
int drm_dp_mst_atomic_setup_commit(struct drm_atomic_state *state)
```

setup_commit hook for MST helpers

**Parameters**

- `struct drm_atomic_state *state`: global atomic state

**Description**

This function saves all of the [`drm_crtc_commit`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_crtc_commit) structs in an atomic state that touch any CRTCs
currently assigned to an MST topology. Drivers must call this hook from their
[`drm_mode_config_helper_funcs.atomic_commit_setup`](#c-struct-drm_mode_config_helper_funcs) hook.

**Return**

0 if all CRTC commits were retrieved successfully, negative error code otherwise

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

```c
void drm_dp_mst_atomic_wait_for_dependencies(struct drm_atomic_state *state)
```

Wait for all pending commits on MST topologies, prepare new MST state for commit

**Parameters**

- `struct drm_atomic_state *state`: global atomic state

**Description**

Goes through any MST topologies in this atomic state, and waits for any pending commits which
touched CRTCs that were/are on an MST topology to be programmed to hardware and flipped to before
returning. This is to prevent multiple non-blocking commits affecting an MST topology from racing
with eachother by forcing them to be executed sequentially in situations where the only resources
the modeset objects in these commits share are an MST topology.

This function also prepares the new MST state for commit by performing some state preparation
which can't be done until this point, such as reading back the final VC start slots (which are
determined at commit-time) from the previous state.

All MST drivers must call this function after calling [`drm_atomic_helper_wait_for_dependencies()`](#c-drm_atomic_helper_wait_for_dependencies),
or whatever their equivalent of that is.

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

```c
int drm_dp_mst_root_conn_atomic_check(struct drm_connector_state *new_conn_state, struct drm_dp_mst_topology_mgr *mgr)
```

Serialize CRTC commits on MST-capable connectors operating in SST mode

**Parameters**

- `struct drm_connector_state *new_conn_state`: The new connector state of the [`drm_connector`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_connector)
- `struct drm_dp_mst_topology_mgr *mgr`: The MST topology manager for the [`drm_connector`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_connector)

**Description**

Since MST uses fake [`drm_encoder`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_encoder) structs, the generic atomic modesetting code isn't able to
serialize non-blocking commits happening on the real DP connector of an MST topology switching
into/away from MST mode - as the CRTC on the real DP connector and the CRTCs on the connector's
MST topology will never share the same [`drm_encoder`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_encoder).

This function takes care of this serialization issue, by checking a root MST connector's atomic
state to determine if it is about to have a modeset - and then pulling in the MST topology state
if so, along with adding any relevant CRTCs to [`drm_dp_mst_topology_state.pending_crtc_mask`](#c-struct-drm_dp_mst_topology_state).

Drivers implementing MST must call this function from the
[`drm_connector_helper_funcs.atomic_check`](#c-struct-drm_connector_helper_funcs) hook of any physical DP [`drm_connector`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_connector) capable of
driving MST sinks.

**Return**

0 on success, negative error code otherwise

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

```c
void drm_dp_mst_update_slots(struct drm_dp_mst_topology_state *mst_state, uint8_t link_encoding_cap)
```

updates the slot info depending on the DP ecoding format

**Parameters**

- `struct drm_dp_mst_topology_state *mst_state`: mst_state to update
- `uint8_t link_encoding_cap`: the ecoding format on the link

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

```c
int drm_dp_check_act_status(struct drm_dp_mst_topology_mgr *mgr)
```

Polls for ACT handled status.

**Parameters**

- `struct drm_dp_mst_topology_mgr *mgr`: manager to use

**Description**

Tries waiting for the MST hub to finish updating it's payload table by
polling for the ACT handled bit for up to 3 seconds (yes-some hubs really
take that long).

**Return**

0 if the ACT was handled in time, negative error code on failure.

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

```c
int drm_dp_calc_pbn_mode(int clock, int bpp)
```

Calculate the PBN for a mode.

**Parameters**

- `int clock`: dot clock
- `int bpp`: bpp as .4 binary fixed point

**Description**

This uses the formula in the spec to calculate the PBN value for a mode.

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

```c
void drm_dp_mst_dump_topology(struct seq_file *m, struct drm_dp_mst_topology_mgr *mgr)
```

dump topology to seq file.

**Parameters**

- `struct seq_file *m`: seq_file to dump output to
- `struct drm_dp_mst_topology_mgr *mgr`: manager to dump current topology for.

**Description**

helper to dump MST topology to a seq file for debugfs.

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

```c
bool drm_dp_mst_port_downstream_of_parent(struct drm_dp_mst_topology_mgr *mgr, struct drm_dp_mst_port *port, struct drm_dp_mst_port *parent)
```

check if a port is downstream of a parent port

**Parameters**

- `struct drm_dp_mst_topology_mgr *mgr`: MST topology manager
- `struct drm_dp_mst_port *port`: the port being looked up
- `struct drm_dp_mst_port *parent`: the parent port

**Description**

The function returns `true` if **port** is downstream of **parent**. If **parent** is
`NULL` - denoting the root port - the function returns `true` if **port** is in
**mgr**'s topology.

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

```c
int drm_dp_mst_add_affected_dsc_crtcs(struct drm_atomic_state *state, struct drm_dp_mst_topology_mgr *mgr)
```

**Parameters**

- `struct drm_atomic_state *state`: Pointer to the new struct drm_dp_mst_topology_state
- `struct drm_dp_mst_topology_mgr *mgr`: MST topology manager

**Description**

Whenever there is a change in mst topology
DSC configuration would have to be recalculated
therefore we need to trigger modeset on all affected
CRTCs in that topology

See also:
[`drm_dp_mst_atomic_enable_dsc()`](#c-drm_dp_mst_atomic_enable_dsc)

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

```c
int drm_dp_mst_atomic_enable_dsc(struct drm_atomic_state *state, struct drm_dp_mst_port *port, int pbn, bool enable)
```

Set DSC Enable Flag to On/Off

**Parameters**

- `struct drm_atomic_state *state`: Pointer to the new drm_atomic_state
- `struct drm_dp_mst_port *port`: Pointer to the affected MST Port
- `int pbn`: Newly recalculated bw required for link with DSC enabled
- `bool enable`: Boolean flag to enable or disable DSC on the port

**Description**

This function enables DSC on the given Port
by recalculating its vcpi from pbn provided
and sets dsc_enable flag to keep track of which
ports have DSC enabled

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

```c
int drm_dp_mst_atomic_check_mgr(struct drm_atomic_state *state, struct drm_dp_mst_topology_mgr *mgr, struct drm_dp_mst_topology_state *mst_state, struct drm_dp_mst_port **failing_port)
```

Check the atomic state of an MST topology manager

**Parameters**

- `struct drm_atomic_state *state`: The global atomic state
- `struct drm_dp_mst_topology_mgr *mgr`: Manager to check
- `struct drm_dp_mst_topology_state *mst_state`: The MST atomic state for **mgr**
- `struct drm_dp_mst_port **failing_port`: Returns the port with a BW limitation

**Description**

Checks the given MST manager's topology state for an atomic update to ensure
that it's valid. This includes checking whether there's enough bandwidth to
support the new timeslot allocations in the atomic update.

Any atomic drivers supporting DP MST must make sure to call this or
the [`drm_dp_mst_atomic_check()`](#c-drm_dp_mst_atomic_check) function after checking the rest of their state
in their [`drm_mode_config_funcs.atomic_check()`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_mode_config_funcs) callback.

See also:
[`drm_dp_mst_atomic_check()`](#c-drm_dp_mst_atomic_check)
[`drm_dp_atomic_find_time_slots()`](#c-drm_dp_atomic_find_time_slots)
[`drm_dp_atomic_release_time_slots()`](#c-drm_dp_atomic_release_time_slots)

- The non-root port where a BW limit check failed
  with all the ports downstream of **failing_port** passing
  the BW limit check.
  The returned port pointer is valid until at least
  one payload downstream of it exists.
- `NULL` if the BW limit check failed at the root port
  with all the ports downstream of the root port passing
  the BW limit check.

- `-EINVAL`, if the new state is invalid, because the root port has
  too many payloads.

**Return**

- 0 if the new state is valid
- `-ENOSPC`, if the new state is invalid, because of BW limitation
  **failing_port** is set to:

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

```c
int drm_dp_mst_atomic_check(struct drm_atomic_state *state)
```

Check that the new state of an MST topology in an atomic update is valid

**Parameters**

- `struct drm_atomic_state *state`: Pointer to the new [`struct drm_dp_mst_topology_state`](#c-struct-drm_dp_mst_topology_state)

**Description**

Checks the given topology state for an atomic update to ensure that it's
valid, calling [`drm_dp_mst_atomic_check_mgr()`](#c-drm_dp_mst_atomic_check_mgr) for all MST manager in the
atomic state. This includes checking whether there's enough bandwidth to
support the new timeslot allocations in the atomic update.

Any atomic drivers supporting DP MST must make sure to call this after
checking the rest of their state in their
[`drm_mode_config_funcs.atomic_check()`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_mode_config_funcs) callback.

See also:
[`drm_dp_mst_atomic_check_mgr()`](#c-drm_dp_mst_atomic_check_mgr)
[`drm_dp_atomic_find_time_slots()`](#c-drm_dp_atomic_find_time_slots)
[`drm_dp_atomic_release_time_slots()`](#c-drm_dp_atomic_release_time_slots)

**Return**

0 if the new state is valid, negative error code otherwise.

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

```c
struct drm_dp_mst_topology_state * drm_atomic_get_mst_topology_state(struct drm_atomic_state *state, struct drm_dp_mst_topology_mgr *mgr)
```

get MST topology state

**Parameters**

- `struct drm_atomic_state *state`: global atomic state
- `struct drm_dp_mst_topology_mgr *mgr`: MST topology manager, also the private object in this case

**Description**

This function wraps `drm_atomic_get_priv_obj_state()` passing in the MST atomic
state vtable so that the private object state returned is that of a MST
topology object.

**Return**

The MST topology state or error pointer.

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

```c
struct drm_dp_mst_topology_state * drm_atomic_get_old_mst_topology_state(struct drm_atomic_state *state, struct drm_dp_mst_topology_mgr *mgr)
```

get old MST topology state in atomic state, if any

**Parameters**

- `struct drm_atomic_state *state`: global atomic state
- `struct drm_dp_mst_topology_mgr *mgr`: MST topology manager, also the private object in this case

**Description**

This function wraps [`drm_atomic_get_old_private_obj_state()`](/kernel/hardware/gpu/drm-kms.md#c-drm_atomic_get_old_private_obj_state) passing in the MST atomic
state vtable so that the private object state returned is that of a MST
topology object.

**Return**

The old MST topology state, or NULL if there's no topology state for this MST mgr
in the global atomic state

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

```c
struct drm_dp_mst_topology_state * drm_atomic_get_new_mst_topology_state(struct drm_atomic_state *state, struct drm_dp_mst_topology_mgr *mgr)
```

get new MST topology state in atomic state, if any

**Parameters**

- `struct drm_atomic_state *state`: global atomic state
- `struct drm_dp_mst_topology_mgr *mgr`: MST topology manager, also the private object in this case

**Description**

This function wraps [`drm_atomic_get_new_private_obj_state()`](/kernel/hardware/gpu/drm-kms.md#c-drm_atomic_get_new_private_obj_state) passing in the MST atomic
state vtable so that the private object state returned is that of a MST
topology object.

**Return**

The new MST topology state, or NULL if there's no topology state for this MST mgr
in the global atomic state

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

```c
int drm_dp_mst_topology_mgr_init(struct drm_dp_mst_topology_mgr *mgr, struct drm_device *dev, struct drm_dp_aux *aux, int max_dpcd_transaction_bytes, int max_payloads, int conn_base_id)
```

initialise a topology manager

**Parameters**

- `struct drm_dp_mst_topology_mgr *mgr`: manager struct to initialise
- `struct drm_device *dev`: device providing this structure - for i2c addition.
- `struct drm_dp_aux *aux`: DP helper aux channel to talk to this device
- `int max_dpcd_transaction_bytes`: hw specific DPCD transaction limit
- `int max_payloads`: maximum number of payloads this GPU can source
- `int conn_base_id`: the connector object ID the MST device is connected to.

**Description**

Return 0 for success, or negative error code on failure

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

```c
void drm_dp_mst_topology_mgr_destroy(struct drm_dp_mst_topology_mgr *mgr)
```

destroy topology manager.

**Parameters**

- `struct drm_dp_mst_topology_mgr *mgr`: manager to destroy

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

```c
struct drm_dp_aux * drm_dp_mst_aux_for_parent(struct drm_dp_mst_port *port)
```

Get the AUX device for an MST port's parent

**Parameters**

- `struct drm_dp_mst_port *port`: MST port whose parent's AUX device is returned

**Description**

Return the AUX device for **port**'s parent or NULL if port's parent is the
root port.

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

```c
struct drm_dp_aux * drm_dp_mst_dsc_aux_for_port(struct drm_dp_mst_port *port)
```

Find the correct aux for DSC

**Parameters**

- `struct drm_dp_mst_port *port`: The port to check. A leaf of the MST tree with an attached display.

**Description**

Depending on the situation, DSC may be enabled via the endpoint aux,
the immediately upstream aux, or the connector's physical aux.

This is both the correct aux to read DSC_CAPABILITY and the
correct aux to write DSC_ENABLED.

This operation can be expensive (up to four aux reads), so
the caller should cache the return.

**Return**

NULL if DSC cannot be enabled on this port, otherwise the aux device


<a id="rst-topology-lifetime-internals"></a>

### Topology Lifetime Internals

These functions aren't exported to drivers, but are documented here to help make the MST topology helpers easier to understand


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

```c
void drm_dp_mst_get_mstb_malloc(struct drm_dp_mst_branch *mstb)
```

Increment the malloc refcount of a branch device

**Parameters**

- `struct drm_dp_mst_branch *mstb`: The [`struct drm_dp_mst_branch`](#c-struct-drm_dp_mst_branch) to increment the malloc refcount of

**Description**

Increments [`drm_dp_mst_branch.malloc_kref`](#c-struct-drm_dp_mst_branch). When
[`drm_dp_mst_branch.malloc_kref`](#c-struct-drm_dp_mst_branch) reaches 0, the memory allocation for **mstb**
will be released and **mstb** may no longer be used.

See also: [`drm_dp_mst_put_mstb_malloc()`](#c-drm_dp_mst_put_mstb_malloc)

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

```c
void drm_dp_mst_put_mstb_malloc(struct drm_dp_mst_branch *mstb)
```

Decrement the malloc refcount of a branch device

**Parameters**

- `struct drm_dp_mst_branch *mstb`: The [`struct drm_dp_mst_branch`](#c-struct-drm_dp_mst_branch) to decrement the malloc refcount of

**Description**

Decrements [`drm_dp_mst_branch.malloc_kref`](#c-struct-drm_dp_mst_branch). When
[`drm_dp_mst_branch.malloc_kref`](#c-struct-drm_dp_mst_branch) reaches 0, the memory allocation for **mstb**
will be released and **mstb** may no longer be used.

See also: [`drm_dp_mst_get_mstb_malloc()`](#c-drm_dp_mst_get_mstb_malloc)

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

```c
int drm_dp_mst_topology_try_get_mstb(struct drm_dp_mst_branch *mstb)
```

Increment the topology refcount of a branch device unless it's zero

**Parameters**

- `struct drm_dp_mst_branch *mstb`: [`struct drm_dp_mst_branch`](#c-struct-drm_dp_mst_branch) to increment the topology refcount of

**Description**

Attempts to grab a topology reference to **mstb**, if it hasn't yet been
removed from the topology (e.g. [`drm_dp_mst_branch.topology_kref`](#c-struct-drm_dp_mst_branch) has
reached 0). Holding a topology reference implies that a malloc reference
will be held to **mstb** as long as the user holds the topology reference.

Care should be taken to ensure that the user has at least one malloc
reference to **mstb**. If you already have a topology reference to **mstb**, you
should use [`drm_dp_mst_topology_get_mstb()`](#c-drm_dp_mst_topology_get_mstb) instead.

See also:
[`drm_dp_mst_topology_get_mstb()`](#c-drm_dp_mst_topology_get_mstb)
[`drm_dp_mst_topology_put_mstb()`](#c-drm_dp_mst_topology_put_mstb)

**Return**

* 1: A topology reference was grabbed successfully
* 0: **port** is no longer in the topology, no reference was grabbed

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

```c
void drm_dp_mst_topology_get_mstb(struct drm_dp_mst_branch *mstb)
```

Increment the topology refcount of a branch device

**Parameters**

- `struct drm_dp_mst_branch *mstb`: The [`struct drm_dp_mst_branch`](#c-struct-drm_dp_mst_branch) to increment the topology refcount of

**Description**

Increments [`drm_dp_mst_branch.topology_refcount`](#c-struct-drm_dp_mst_branch) without checking whether or
not it's already reached 0. This is only valid to use in scenarios where
you are already guaranteed to have at least one active topology reference
to **mstb**. Otherwise, [`drm_dp_mst_topology_try_get_mstb()`](#c-drm_dp_mst_topology_try_get_mstb) must be used.

See also:
[`drm_dp_mst_topology_try_get_mstb()`](#c-drm_dp_mst_topology_try_get_mstb)
[`drm_dp_mst_topology_put_mstb()`](#c-drm_dp_mst_topology_put_mstb)

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

```c
void drm_dp_mst_topology_put_mstb(struct drm_dp_mst_branch *mstb)
```

release a topology reference to a branch device

**Parameters**

- `struct drm_dp_mst_branch *mstb`: The [`struct drm_dp_mst_branch`](#c-struct-drm_dp_mst_branch) to release the topology reference from

**Description**

Releases a topology reference from **mstb** by decrementing
[`drm_dp_mst_branch.topology_kref`](#c-struct-drm_dp_mst_branch).

See also:
[`drm_dp_mst_topology_try_get_mstb()`](#c-drm_dp_mst_topology_try_get_mstb)
[`drm_dp_mst_topology_get_mstb()`](#c-drm_dp_mst_topology_get_mstb)

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

```c
int drm_dp_mst_topology_try_get_port(struct drm_dp_mst_port *port)
```

Increment the topology refcount of a port unless it's zero

**Parameters**

- `struct drm_dp_mst_port *port`: [`struct drm_dp_mst_port`](#c-struct-drm_dp_mst_port) to increment the topology refcount of

**Description**

Attempts to grab a topology reference to **port**, if it hasn't yet been
removed from the topology (e.g. [`drm_dp_mst_port.topology_kref`](#c-struct-drm_dp_mst_port) has reached
0). Holding a topology reference implies that a malloc reference will be
held to **port** as long as the user holds the topology reference.

Care should be taken to ensure that the user has at least one malloc
reference to **port**. If you already have a topology reference to **port**, you
should use [`drm_dp_mst_topology_get_port()`](#c-drm_dp_mst_topology_get_port) instead.

See also:
[`drm_dp_mst_topology_get_port()`](#c-drm_dp_mst_topology_get_port)
[`drm_dp_mst_topology_put_port()`](#c-drm_dp_mst_topology_put_port)

**Return**

* 1: A topology reference was grabbed successfully
* 0: **port** is no longer in the topology, no reference was grabbed

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

```c
void drm_dp_mst_topology_get_port(struct drm_dp_mst_port *port)
```

Increment the topology refcount of a port

**Parameters**

- `struct drm_dp_mst_port *port`: The [`struct drm_dp_mst_port`](#c-struct-drm_dp_mst_port) to increment the topology refcount of

**Description**

Increments [`drm_dp_mst_port.topology_refcount`](#c-struct-drm_dp_mst_port) without checking whether or
not it's already reached 0. This is only valid to use in scenarios where
you are already guaranteed to have at least one active topology reference
to **port**. Otherwise, [`drm_dp_mst_topology_try_get_port()`](#c-drm_dp_mst_topology_try_get_port) must be used.

See also:
[`drm_dp_mst_topology_try_get_port()`](#c-drm_dp_mst_topology_try_get_port)
[`drm_dp_mst_topology_put_port()`](#c-drm_dp_mst_topology_put_port)

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

```c
void drm_dp_mst_topology_put_port(struct drm_dp_mst_port *port)
```

release a topology reference to a port

**Parameters**

- `struct drm_dp_mst_port *port`: The [`struct drm_dp_mst_port`](#c-struct-drm_dp_mst_port) to release the topology reference from

**Description**

Releases a topology reference from **port** by decrementing
[`drm_dp_mst_port.topology_kref`](#c-struct-drm_dp_mst_port).

See also:
[`drm_dp_mst_topology_try_get_port()`](#c-drm_dp_mst_topology_try_get_port)
[`drm_dp_mst_topology_get_port()`](#c-drm_dp_mst_topology_get_port)


<a id="rst-mipi-dbi-helper-functions-reference"></a>

## MIPI DBI Helper Functions Reference


This library provides helpers for MIPI Display Bus Interface (DBI)
compatible display controllers.

Many controllers for tiny lcd displays are MIPI compliant and can use this
library. If a controller uses registers 0x2A and 0x2B to set the area to
update and uses register 0x2C to write to frame memory, it is most likely
MIPI compliant.

Only MIPI Type 1 displays are supported since a full frame memory is needed.

There are 3 MIPI DBI implementation types:

A. Motorola 6800 type parallel bus

B. Intel 8080 type parallel bus

C. SPI type with 3 options:

1. 9-bit with the Data/Command signal as the ninth bit
2. Same as above except it's sent as 16 bits
3. 8-bit with the Data/Command signal as a separate D/CX pin

Currently mipi_dbi only supports Type C options 1 and 3 with
[`mipi_dbi_spi_init()`](#c-mipi_dbi_spi_init).



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

MIPI DBI interface

**Definition**

```c
struct mipi_dbi {
    struct mutex cmdlock;
    int (*command)(struct mipi_dbi *dbi, u8 *cmd, u8 *param, size_t num);
    const u8 *read_commands;
    bool swap_bytes;
    struct gpio_desc *reset;
    struct spi_device *spi;
    unsigned int write_memory_bpw;
    struct gpio_desc *dc;
    void *tx_buf9;
    size_t tx_buf9_len;
};
```

**Members**

- `cmdlock`: Command lock
- `command`: Bus specific callback executing commands.
- `read_commands`:

  - Array of read commands terminated by a zero entry.

    Reading is disabled if this is NULL.
- `swap_bytes`: Swap bytes in buffer before transfer
- `reset`: Optional reset gpio
- `spi`: SPI device
- `write_memory_bpw`: Bits per word used on a MIPI_DCS_WRITE_MEMORY_START transfer
- `dc`: Optional D/C gpio.
- `tx_buf9`: Buffer used for Option 1 9-bit conversion
- `tx_buf9_len`: Size of tx_buf9.

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

MIPI DBI device

**Definition**

```c
struct mipi_dbi_dev {
    struct drm_device drm;
    struct drm_simple_display_pipe pipe;
    struct drm_connector connector;
    struct drm_display_mode mode;
    u32 pixel_format;
    u16 *tx_buf;
    unsigned int rotation;
    unsigned int left_offset;
    unsigned int top_offset;
    struct backlight_device *backlight;
    struct regulator *regulator;
    struct regulator *io_regulator;
    struct mipi_dbi dbi;
    void *driver_private;
};
```

**Members**

- `drm`: DRM device
- `pipe`: Display pipe structure
- `connector`: Connector
- `mode`: Fixed display mode
- `pixel_format`: Native pixel format (DRM_FORMAT\_\*)
- `tx_buf`: Buffer used for transfer (copy clip rect area)
- `rotation`: initial rotation in degrees Counter Clock Wise
- `left_offset`:

  - Horizontal offset of the display relative to the

    controller's driver array
- `top_offset`:

  - Vertical offset of the display relative to the

    controller's driver array
- `backlight`: backlight device (optional)
- `regulator`: power regulator (Vdd) (optional)
- `io_regulator`: I/O power regulator (Vddi) (optional)
- `dbi`: MIPI DBI interface
- `driver_private`:

  - Driver private data.

    Necessary for drivers with private data since [`devm_drm_dev_alloc()`](/kernel/hardware/gpu/drm-internals.md#c-devm_drm_dev_alloc)
    can't allocate structures that embed a structure which then again
    embeds drm_device.

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

```c
mipi_dbi_command(dbi, cmd, seq...)
```

MIPI DCS command with optional parameter(s)

**Parameters**

- `dbi`: MIPI DBI structure
- `cmd`: Command
- `seq...`: Optional parameter(s)

**Description**

Send MIPI DCS command to the controller. Use [`mipi_dbi_command_read()`](#c-mipi_dbi_command_read) for
get/read.

**Return**

Zero on success, negative error code on failure.

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

```c
DRM_MIPI_DBI_SIMPLE_DISPLAY_PIPE_FUNCS(enable_)
```

Initializes struct drm_simple_display_pipe_funcs for MIPI-DBI devices

**Parameters**

- `enable_`: Enable-callback implementation

**Description**

This macro initializes struct drm_simple_display_pipe_funcs with default
values for MIPI-DBI-based devices. The only callback that depends on the
hardware is **enable**, for which the driver has to provide an implementation.
MIPI-based drivers are encouraged to use this macro for initialization.



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

```c
int mipi_dbi_command_read(struct mipi_dbi *dbi, u8 cmd, u8 *val)
```

MIPI DCS read command

**Parameters**

- `struct mipi_dbi *dbi`: MIPI DBI structure
- `u8 cmd`: Command
- `u8 *val`: Value read

**Description**

Send MIPI DCS read command to the controller.

**Return**

Zero on success, negative error code on failure.

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

```c
int mipi_dbi_command_buf(struct mipi_dbi *dbi, u8 cmd, u8 *data, size_t len)
```

MIPI DCS command with parameter(s) in an array

**Parameters**

- `struct mipi_dbi *dbi`: MIPI DBI structure
- `u8 cmd`: Command
- `u8 *data`: Parameter buffer
- `size_t len`: Buffer length

**Return**

Zero on success, negative error code on failure.

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

```c
int mipi_dbi_buf_copy(void *dst, struct iosys_map *src, struct drm_framebuffer *fb, struct drm_rect *clip, bool swap, struct drm_format_conv_state *fmtcnv_state)
```

Copy a framebuffer, transforming it if necessary

**Parameters**

- `void *dst`: The destination buffer
- `struct iosys_map *src`: The source buffer
- `struct drm_framebuffer *fb`: The source framebuffer
- `struct drm_rect *clip`: Clipping rectangle of the area to be copied
- `bool swap`: When true, swap MSB/LSB of 16-bit values
- `struct drm_format_conv_state *fmtcnv_state`: Format-conversion state

**Return**

Zero on success, negative error code on failure.

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

```c
enum drm_mode_status mipi_dbi_pipe_mode_valid(struct drm_simple_display_pipe *pipe, const struct drm_display_mode *mode)
```

MIPI DBI mode-valid helper

**Parameters**

- `struct drm_simple_display_pipe *pipe`: Simple display pipe
- `const struct drm_display_mode *mode`: The mode to test

**Description**

This function validates a given display mode against the MIPI DBI's hardware
display. Drivers can use this as their [`drm_simple_display_pipe_funcs->mode_valid`](#c-struct-drm_simple_display_pipe_funcs)
callback.

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

```c
void mipi_dbi_pipe_update(struct drm_simple_display_pipe *pipe, struct drm_plane_state *old_state)
```

Display pipe update helper

**Parameters**

- `struct drm_simple_display_pipe *pipe`: Simple display pipe
- `struct drm_plane_state *old_state`: Old plane state

**Description**

This function handles framebuffer flushing and vblank events. Drivers can use
this as their [`drm_simple_display_pipe_funcs->update`](#c-struct-drm_simple_display_pipe_funcs) callback.

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

```c
void mipi_dbi_enable_flush(struct mipi_dbi_dev *dbidev, struct drm_crtc_state *crtc_state, struct drm_plane_state *plane_state)
```

MIPI DBI enable helper

**Parameters**

- `struct mipi_dbi_dev *dbidev`: MIPI DBI device structure
- `struct drm_crtc_state *crtc_state`: CRTC state
- `struct drm_plane_state *plane_state`: Plane state

**Description**

Flushes the whole framebuffer and enables the backlight. Drivers can use this
in their [`drm_simple_display_pipe_funcs->enable`](#c-struct-drm_simple_display_pipe_funcs) callback.

**Note**

Drivers which don't use [`mipi_dbi_pipe_update()`](#c-mipi_dbi_pipe_update) because they have custom
framebuffer flushing, can't use this function since they both use the same
flushing code.

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

```c
void mipi_dbi_pipe_disable(struct drm_simple_display_pipe *pipe)
```

MIPI DBI pipe disable helper

**Parameters**

- `struct drm_simple_display_pipe *pipe`: Display pipe

**Description**

This function disables backlight if present, if not the display memory is
blanked. The regulator is disabled if in use. Drivers can use this as their
[`drm_simple_display_pipe_funcs->disable`](#c-struct-drm_simple_display_pipe_funcs) callback.

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

```c
int mipi_dbi_pipe_begin_fb_access(struct drm_simple_display_pipe *pipe, struct drm_plane_state *plane_state)
```

MIPI DBI pipe begin-access helper

**Parameters**

- `struct drm_simple_display_pipe *pipe`: Display pipe
- `struct drm_plane_state *plane_state`: Plane state

**Description**

This function implements struct `drm_simple_display_funcs.begin_fb_access`.

See [`drm_gem_begin_shadow_fb_access()`](#c-drm_gem_begin_shadow_fb_access) for details and `mipi_dbi_pipe_cleanup_fb()`
for cleanup.

**Return**

0 on success, or a negative errno code otherwise.

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

```c
void mipi_dbi_pipe_end_fb_access(struct drm_simple_display_pipe *pipe, struct drm_plane_state *plane_state)
```

MIPI DBI pipe end-access helper

**Parameters**

- `struct drm_simple_display_pipe *pipe`: Display pipe
- `struct drm_plane_state *plane_state`: Plane state

**Description**

This function implements struct `drm_simple_display_funcs.end_fb_access`.

See [`mipi_dbi_pipe_begin_fb_access()`](#c-mipi_dbi_pipe_begin_fb_access).

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

```c
void mipi_dbi_pipe_reset_plane(struct drm_simple_display_pipe *pipe)
```

MIPI DBI plane-reset helper

**Parameters**

- `struct drm_simple_display_pipe *pipe`: Display pipe

**Description**

This function implements struct `drm_simple_display_funcs.reset_plane`
for MIPI DBI planes.

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

```c
struct drm_plane_state * mipi_dbi_pipe_duplicate_plane_state(struct drm_simple_display_pipe *pipe)
```

duplicates MIPI DBI plane state

**Parameters**

- `struct drm_simple_display_pipe *pipe`: Display pipe

**Description**

This function implements struct `drm_simple_display_funcs.duplicate_plane_state`
for MIPI DBI planes.

See [`drm_gem_duplicate_shadow_plane_state()`](#c-drm_gem_duplicate_shadow_plane_state) for additional details.

**Return**

A pointer to a new plane state on success, or NULL otherwise.

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

```c
void mipi_dbi_pipe_destroy_plane_state(struct drm_simple_display_pipe *pipe, struct drm_plane_state *plane_state)
```

cleans up MIPI DBI plane state

**Parameters**

- `struct drm_simple_display_pipe *pipe`: Display pipe
- `struct drm_plane_state *plane_state`: Plane state

**Description**

This function implements struct drm_simple_display_funcs.destroy_plane_state
for MIPI DBI planes.

See [`drm_gem_destroy_shadow_plane_state()`](#c-drm_gem_destroy_shadow_plane_state) for additional details.

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

```c
int mipi_dbi_dev_init_with_formats(struct mipi_dbi_dev *dbidev, const struct drm_simple_display_pipe_funcs *funcs, const uint32_t *formats, unsigned int format_count, const struct drm_display_mode *mode, unsigned int rotation, size_t tx_buf_size)
```

MIPI DBI device initialization with custom formats

**Parameters**

- `struct mipi_dbi_dev *dbidev`: MIPI DBI device structure to initialize
- `const struct drm_simple_display_pipe_funcs *funcs`: Display pipe functions
- `const uint32_t *formats`: Array of supported formats (DRM_FORMAT\_\*).
- `unsigned int format_count`: Number of elements in **formats**
- `const struct drm_display_mode *mode`: Display mode
- `unsigned int rotation`: Initial rotation in degrees Counter Clock Wise
- `size_t tx_buf_size`: Allocate a transmit buffer of this size.

**Description**

This function sets up a [`drm_simple_display_pipe`](#c-struct-drm_simple_display_pipe) with a [`drm_connector`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_connector) that
has one fixed [`drm_display_mode`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_display_mode) which is rotated according to **rotation**.
This mode is used to set the mode config min/max width/height properties.

Use [`mipi_dbi_dev_init()`](#c-mipi_dbi_dev_init) if you want native RGB565 and emulated XRGB8888 format.

**Note**

Some of the helper functions expects RGB565 to be the default format and the
transmit buffer sized to fit that.

**Return**

Zero on success, negative error code on failure.

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

```c
int mipi_dbi_dev_init(struct mipi_dbi_dev *dbidev, const struct drm_simple_display_pipe_funcs *funcs, const struct drm_display_mode *mode, unsigned int rotation)
```

MIPI DBI device initialization

**Parameters**

- `struct mipi_dbi_dev *dbidev`: MIPI DBI device structure to initialize
- `const struct drm_simple_display_pipe_funcs *funcs`: Display pipe functions
- `const struct drm_display_mode *mode`: Display mode
- `unsigned int rotation`: Initial rotation in degrees Counter Clock Wise

**Description**

This function sets up a [`drm_simple_display_pipe`](#c-struct-drm_simple_display_pipe) with a [`drm_connector`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_connector) that
has one fixed [`drm_display_mode`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_display_mode) which is rotated according to **rotation**.
This mode is used to set the mode config min/max width/height properties.
Additionally [`mipi_dbi.tx_buf`](#c-struct-mipi_dbi) is allocated.

Supported formats: Native RGB565 and emulated XRGB8888.

**Return**

Zero on success, negative error code on failure.

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

```c
void mipi_dbi_hw_reset(struct mipi_dbi *dbi)
```

Hardware reset of controller

**Parameters**

- `struct mipi_dbi *dbi`: MIPI DBI structure

**Description**

Reset controller if the [`mipi_dbi->reset`](#c-struct-mipi_dbi) gpio is set.

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

```c
bool mipi_dbi_display_is_on(struct mipi_dbi *dbi)
```

Check if display is on

**Parameters**

- `struct mipi_dbi *dbi`: MIPI DBI structure

**Description**

This function checks the Power Mode register (if readable) to see if
display output is turned on. This can be used to see if the bootloader
has already turned on the display avoiding flicker when the pipeline is
enabled.

**Return**

true if the display can be verified to be on, false otherwise.

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

```c
int mipi_dbi_poweron_reset(struct mipi_dbi_dev *dbidev)
```

MIPI DBI poweron and reset

**Parameters**

- `struct mipi_dbi_dev *dbidev`: MIPI DBI device structure

**Description**

This function enables the regulator if used and does a hardware and software
reset.

**Return**

Zero on success, or a negative error code.

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

```c
int mipi_dbi_poweron_conditional_reset(struct mipi_dbi_dev *dbidev)
```

MIPI DBI poweron and conditional reset

**Parameters**

- `struct mipi_dbi_dev *dbidev`: MIPI DBI device structure

**Description**

This function enables the regulator if used and if the display is off, it
does a hardware and software reset. If [`mipi_dbi_display_is_on()`](#c-mipi_dbi_display_is_on) determines
that the display is on, no reset is performed.

**Return**

Zero if the controller was reset, 1 if the display was already on, or a
negative error code.

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

```c
u32 mipi_dbi_spi_cmd_max_speed(struct spi_device *spi, size_t len)
```

get the maximum SPI bus speed

**Parameters**

- `struct spi_device *spi`: SPI device
- `size_t len`: The transfer buffer length.

**Description**

Many controllers have a max speed of 10MHz, but can be pushed way beyond
that. Increase reliability by running pixel data at max speed and the rest
at 10MHz, preventing transfer glitches from messing up the init settings.

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

```c
int mipi_dbi_spi_init(struct spi_device *spi, struct mipi_dbi *dbi, struct gpio_desc *dc)
```

Initialize MIPI DBI SPI interface

**Parameters**

- `struct spi_device *spi`: SPI device
- `struct mipi_dbi *dbi`: MIPI DBI structure to initialize
- `struct gpio_desc *dc`: D/C gpio (optional)

**Description**

This function sets [`mipi_dbi->command`](#c-struct-mipi_dbi), enables [`mipi_dbi->read_commands`](#c-struct-mipi_dbi) for the
usual read commands. It should be followed by a call to [`mipi_dbi_dev_init()`](#c-mipi_dbi_dev_init) or
a driver-specific init.

If **dc** is set, a Type C Option 3 interface is assumed, if not
Type C Option 1.

If the command is `MIPI_DCS_WRITE_MEMORY_START` and the pixel format is RGB565, endianness has
to be taken into account. The MIPI DBI serial interface is big endian and framebuffers are
assumed stored in memory as little endian (`DRM_FORMAT_BIG_ENDIAN` is not supported).

This is how endianness is handled:

- Option 1 (D/C as a bit): The buffer is sent on the wire byte by byte so the 16-bit buffer is

  byteswapped before transfer.

- Option 3 (D/C as a gpio): If the SPI controller supports 16 bits per word the buffer can be

  sent as-is. If not the caller is responsible for swapping the bytes
  before calling [`mipi_dbi_command_buf()`](#c-mipi_dbi_command_buf) and the buffer is sent 8 bpw.

This handling is optimised for `DRM_FORMAT_RGB565` framebuffers.

If the interface is Option 1 and the SPI controller doesn't support 9 bits per word,
the buffer is sent as 9x 8-bit words, padded with MIPI DCS no-op commands if necessary.

**Return**

Zero on success, negative error code on failure.

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

```c
int mipi_dbi_spi_transfer(struct spi_device *spi, u32 speed_hz, u8 bpw, const void *buf, size_t len)
```

SPI transfer helper

**Parameters**

- `struct spi_device *spi`: SPI device
- `u32 speed_hz`: Override speed (optional)
- `u8 bpw`: Bits per word
- `const void *buf`: Buffer to transfer
- `size_t len`: Buffer length

**Description**

This SPI transfer helper breaks up the transfer of **buf** into chunks which
the SPI controller driver can handle. The SPI bus must be locked when
calling this.

**Return**

Zero on success, negative error code on failure.

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

```c
void mipi_dbi_debugfs_init(struct drm_minor *minor)
```

Create debugfs entries

**Parameters**

- `struct drm_minor *minor`: DRM minor

**Description**

This function creates a 'command' debugfs file for sending commands to the
controller or getting the read command values.
Drivers can use this as their [`drm_driver->debugfs_init`](/kernel/hardware/gpu/drm-internals.md#c-struct-drm_driver) callback.


<a id="rst-mipi-dsi-helper-functions-reference"></a>

## MIPI DSI Helper Functions Reference


These functions contain some common logic and helpers to deal with MIPI DSI
peripherals.

Helpers are provided for a number of standard MIPI DSI command as well as a
subset of the MIPI DCS command set.



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

read/write DSI buffer

**Definition**

```c
struct mipi_dsi_msg {
    u8 channel;
    u8 type;
    u16 flags;
    size_t tx_len;
    const void *tx_buf;
    size_t rx_len;
    void *rx_buf;
};
```

**Members**

- `channel`: virtual channel id
- `type`: payload data type
- `flags`: flags controlling this message transmission
- `tx_len`: length of **tx_buf**
- `tx_buf`: data to be written
- `rx_len`: length of **rx_buf**
- `rx_buf`: data to be read, or NULL

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

represents a MIPI DSI packet in protocol format

**Definition**

```c
struct mipi_dsi_packet {
    size_t size;
    u8 header[4];
    size_t payload_length;
    const u8 *payload;
};
```

**Members**

- `size`: size (in bytes) of the packet
- `header`: the four bytes that make up the header (Data ID, Word Count or
  Packet Data, and ECC)
- `payload_length`: number of bytes in the payload
- `payload`: a pointer to a buffer containing the payload, if any

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

DSI bus operations

**Definition**

```c
struct mipi_dsi_host_ops {
    int (*attach)(struct mipi_dsi_host *host, struct mipi_dsi_device *dsi);
    int (*detach)(struct mipi_dsi_host *host, struct mipi_dsi_device *dsi);
    ssize_t (*transfer)(struct mipi_dsi_host *host, const struct mipi_dsi_msg *msg);
};
```

**Members**

- `attach`: attach DSI device to DSI host
- `detach`: detach DSI device from DSI host
- `transfer`: transmit a DSI packet

**Description**

DSI packets transmitted by .`transfer()` are passed in as mipi_dsi_msg
structures. This structure contains information about the type of packet
being transmitted as well as the transmit and receive buffers. When an
error is encountered during transmission, this function will return a
negative error code. On success it shall return the number of bytes
transmitted for write packets or the number of bytes received for read
packets.

Note that typically DSI packet transmission is atomic, so the .`transfer()`
function will seldomly return anything other than the number of bytes
contained in the transmit buffer on success.

Also note that those callbacks can be called no matter the state the
host is in. Drivers that need the underlying device to be powered to
perform these operations will first need to make sure it's been
properly enabled.

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

DSI host device

**Definition**

```c
struct mipi_dsi_host {
    struct device *dev;
    const struct mipi_dsi_host_ops *ops;
    struct list_head list;
};
```

**Members**

- `dev`: driver model device node for this DSI host
- `ops`: DSI host operations
- `list`: list management

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

template for creating a mipi_dsi_device

**Definition**

```c
struct mipi_dsi_device_info {
    char type[DSI_DEV_NAME_SIZE];
    u32 channel;
    struct device_node *node;
};
```

**Members**

- `type`: DSI peripheral chip type
- `channel`: DSI virtual channel assigned to peripheral
- `node`: pointer to OF device node or NULL

**Description**

This is populated and passed to mipi_dsi_device_new to create a new
DSI device

#### <a id="c-struct-mipi_dsi_device"></a>`struct mipi_dsi_device`

DSI peripheral device

**Definition**

```c
struct mipi_dsi_device {
    struct mipi_dsi_host *host;
    struct device dev;
    bool attached;
    char name[DSI_DEV_NAME_SIZE];
    unsigned int channel;
    unsigned int lanes;
    enum mipi_dsi_pixel_format format;
    unsigned long mode_flags;
    unsigned long hs_rate;
    unsigned long lp_rate;
    struct drm_dsc_config *dsc;
};
```

**Members**

- `host`: DSI host for this peripheral
- `dev`: driver model device node for this peripheral
- `attached`: the DSI device has been successfully attached
- `name`: DSI peripheral chip type
- `channel`: virtual channel assigned to the peripheral
- `lanes`: number of active data lanes
- `format`: pixel format for video mode
- `mode_flags`: DSI operation mode related flags
- `hs_rate`: maximum lane frequency for high speed mode in hertz, this should
  be set to the real limits of the hardware, zero is only accepted for
  legacy drivers
- `lp_rate`: maximum lane frequency for low power mode in hertz, this should
  be set to the real limits of the hardware, zero is only accepted for
  legacy drivers
- `dsc`: panel/bridge DSC pps payload to be sent

#### <a id="c-struct-mipi_dsi_multi_context"></a>`struct mipi_dsi_multi_context`

Context to call multiple MIPI DSI funcs in a row

**Definition**

```c
struct mipi_dsi_multi_context {
    struct mipi_dsi_device *dsi;
    int accum_err;
};
```

**Members**

- `dsi`: Pointer to the MIPI DSI device
- `accum_err`: Storage for the accumulated error over the multiple calls

  Init to 0. If a function encounters an error then the error code
  will be stored here. If you call a function and this points to a
  non-zero value then the function will be a noop. This allows calling
  a function many times in a row and just checking the error at the
  end to see if any of them failed.

#### <a id="c-mipi_dsi_pixel_format_to_bpp"></a>`mipi_dsi_pixel_format_to_bpp()`

```c
int mipi_dsi_pixel_format_to_bpp(enum mipi_dsi_pixel_format fmt)
```

obtain the number of bits per pixel for any given pixel format defined by the MIPI DSI specification

**Parameters**

- `enum mipi_dsi_pixel_format fmt`: MIPI DSI pixel format

**Return**

The number of bits per pixel of the given pixel format.

#### <a id="c-enum-mipi_dsi_dcs_tear_mode"></a>`enum mipi_dsi_dcs_tear_mode`

Tearing Effect Output Line mode

**Constants**

- `MIPI_DSI_DCS_TEAR_MODE_VBLANK`: the TE output line consists of V-Blanking
  information only
- `MIPI_DSI_DCS_TEAR_MODE_VHBLANK`: the TE output line consists of both
  V-Blanking and H-Blanking information

#### <a id="c-mipi_dsi_generic_write_seq_multi"></a>`mipi_dsi_generic_write_seq_multi()`

```c
mipi_dsi_generic_write_seq_multi(ctx, seq...)
```

transmit data using a generic write packet

**Parameters**

- `ctx`: Context for multiple DSI transactions
- `seq...`: buffer containing the payload

**Description**

This macro will print errors for you and error handling is optimized for
callers that call this multiple times in a row.

#### <a id="c-mipi_dsi_generic_write_var_seq_multi"></a>`mipi_dsi_generic_write_var_seq_multi()`

```c
mipi_dsi_generic_write_var_seq_multi(ctx, seq...)
```

transmit non-constant data using a generic write packet

**Parameters**

- `ctx`: Context for multiple DSI transactions
- `seq...`: buffer containing the payload

**Description**

This macro will print errors for you and error handling is optimized for
callers that call this multiple times in a row.

#### <a id="c-mipi_dsi_dcs_write_seq_multi"></a>`mipi_dsi_dcs_write_seq_multi()`

```c
mipi_dsi_dcs_write_seq_multi(ctx, cmd, seq...)
```

transmit a DCS command with payload

**Parameters**

- `ctx`: Context for multiple DSI transactions
- `cmd`: Command
- `seq...`: buffer containing data to be transmitted

**Description**

This macro will print errors for you and error handling is optimized for
callers that call this multiple times in a row.

#### <a id="c-mipi_dsi_dcs_write_var_seq_multi"></a>`mipi_dsi_dcs_write_var_seq_multi()`

```c
mipi_dsi_dcs_write_var_seq_multi(ctx, cmd, seq...)
```

transmit a DCS command with non-constant payload

**Parameters**

- `ctx`: Context for multiple DSI transactions
- `cmd`: Command
- `seq...`: buffer containing data to be transmitted

**Description**

This macro will print errors for you and error handling is optimized for
callers that call this multiple times in a row.

#### <a id="c-mipi_dsi_dual"></a>`mipi_dsi_dual()`

```c
mipi_dsi_dual(_func, _ctx, _dsi1, _dsi2, ...)
```

send the same MIPI DSI command to two interfaces

**Parameters**

- `_func`: MIPI DSI function to pass context and arguments into
- `_ctx`: Context for multiple DSI transactions
- `_dsi1`: First DSI interface to act as recipient of the MIPI DSI command
- `_dsi2`: Second DSI interface to act as recipient of the MIPI DSI command
- `...`: Arguments to pass to MIPI DSI function or macro

**Description**

This macro will send the specified MIPI DSI command twice, once per each of
the two interfaces supplied. This is useful for reducing duplication of code
in panel drivers which use two parallel serial interfaces.

Note that the _func parameter cannot accept a macro such as
[`mipi_dsi_generic_write_multi()`](#c-mipi_dsi_generic_write_multi) or [`mipi_dsi_dcs_write_buffer_multi()`](#c-mipi_dsi_dcs_write_buffer_multi). See
[`mipi_dsi_dual_generic_write_multi()`](#c-mipi_dsi_dual_generic_write_multi) and
[`mipi_dsi_dual_dcs_write_buffer_multi()`](#c-mipi_dsi_dual_dcs_write_buffer_multi) instead.

WARNING: This macro reuses the _func argument and the optional trailing
arguments twice each, which may cause unintended side effects. For example,
adding the postfix increment ++ operator to one of the arguments to be
passed to _func will cause the variable to be incremented twice instead of
once and the variable will be its original value + 1 when sent to _dsi2.

#### <a id="c-mipi_dsi_dual_generic_write_seq_multi"></a>`mipi_dsi_dual_generic_write_seq_multi()`

```c
mipi_dsi_dual_generic_write_seq_multi(_ctx, _dsi1, _dsi2, _seq...)
```

transmit data using a generic write packet to two dsi interfaces, one after the other

**Parameters**

- `_ctx`: Context for multiple DSI transactions
- `_dsi1`: First DSI interface to act as recipient of packet
- `_dsi2`: Second DSI interface to act as recipient of packet
- `_seq...`: buffer containing the payload

**Description**

This macro will send the specified generic packet twice, once per each of
the two interfaces supplied. This is useful for reducing duplication of code
in panel drivers which use two parallel serial interfaces.

Note that if an error occurs while transmitting the packet to the first DSI
interface, the packet will not be sent to the second DSI interface.

This macro will print errors for you and error handling is optimized for
callers that call this multiple times in a row.

#### <a id="c-mipi_dsi_dual_dcs_write_seq_multi"></a>`mipi_dsi_dual_dcs_write_seq_multi()`

```c
mipi_dsi_dual_dcs_write_seq_multi(_ctx, _dsi1, _dsi2, _cmd, _seq...)
```

transmit a DCS command with payload to two dsi interfaces, one after the other

**Parameters**

- `_ctx`: Context for multiple DSI transactions
- `_dsi1`: First DSI interface to act as recipient of packet
- `_dsi2`: Second DSI interface to act as recipient of packet
- `_cmd`: Command
- `_seq...`: buffer containing the payload

**Description**

This macro will send the specified DCS command with payload twice, once per
each of the two interfaces supplied. This is useful for reducing duplication
of code in panel drivers which use two parallel serial interfaces.

Note that if an error occurs while transmitting the payload to the first DSI
interface, the payload will not be sent to the second DSI interface.

This macro will print errors for you and error handling is optimized for
callers that call this multiple times in a row.

#### <a id="c-struct-mipi_dsi_driver"></a>`struct mipi_dsi_driver`

DSI driver

**Definition**

```c
struct mipi_dsi_driver {
    struct device_driver driver;
    int(*probe)(struct mipi_dsi_device *dsi);
    void (*remove)(struct mipi_dsi_device *dsi);
    void (*shutdown)(struct mipi_dsi_device *dsi);
};
```

**Members**

- `driver`: device driver model driver
- `probe`: callback for device binding
- `remove`: callback for device unbinding
- `shutdown`: called at shutdown time to quiesce the device



#### <a id="c-of_find_mipi_dsi_device_by_node"></a>`of_find_mipi_dsi_device_by_node()`

```c
struct mipi_dsi_device * of_find_mipi_dsi_device_by_node(struct device_node *np)
```

find the MIPI DSI device matching a device tree node

**Parameters**

- `struct device_node *np`: device tree node

**Return**

A pointer to the MIPI DSI device corresponding to **np** or NULL if no
such device exists (or has not been registered yet).

#### <a id="c-mipi_dsi_device_register_full"></a>`mipi_dsi_device_register_full()`

```c
struct mipi_dsi_device * mipi_dsi_device_register_full(struct mipi_dsi_host *host, const struct mipi_dsi_device_info *info)
```

create a MIPI DSI device

**Parameters**

- `struct mipi_dsi_host *host`: DSI host to which this device is connected
- `const struct mipi_dsi_device_info *info`: pointer to template containing DSI device information

**Description**

Create a MIPI DSI device by using the device information provided by
mipi_dsi_device_info template

**Return**

A pointer to the newly created MIPI DSI device, or, a pointer encoded
with an error

#### <a id="c-mipi_dsi_device_unregister"></a>`mipi_dsi_device_unregister()`

```c
void mipi_dsi_device_unregister(struct mipi_dsi_device *dsi)
```

unregister MIPI DSI device

**Parameters**

- `struct mipi_dsi_device *dsi`: DSI peripheral device

#### <a id="c-devm_mipi_dsi_device_register_full"></a>`devm_mipi_dsi_device_register_full()`

```c
struct mipi_dsi_device * devm_mipi_dsi_device_register_full(struct device *dev, struct mipi_dsi_host *host, const struct mipi_dsi_device_info *info)
```

create a managed MIPI DSI device

**Parameters**

- `struct device *dev`: device to tie the MIPI-DSI device lifetime to
- `struct mipi_dsi_host *host`: DSI host to which this device is connected
- `const struct mipi_dsi_device_info *info`: pointer to template containing DSI device information

**Description**

Create a MIPI DSI device by using the device information provided by
mipi_dsi_device_info template

This is the managed version of [`mipi_dsi_device_register_full()`](#c-mipi_dsi_device_register_full) which
automatically calls [`mipi_dsi_device_unregister()`](#c-mipi_dsi_device_unregister) when **dev** is
unbound.

**Return**

A pointer to the newly created MIPI DSI device, or, a pointer encoded
with an error

#### <a id="c-of_find_mipi_dsi_host_by_node"></a>`of_find_mipi_dsi_host_by_node()`

```c
struct mipi_dsi_host * of_find_mipi_dsi_host_by_node(struct device_node *node)
```

find the MIPI DSI host matching a device tree node

**Parameters**

- `struct device_node *node`: device tree node

**Return**

A pointer to the MIPI DSI host corresponding to **node** or NULL if no
such device exists (or has not been registered yet).

#### <a id="c-mipi_dsi_attach"></a>`mipi_dsi_attach()`

```c
int mipi_dsi_attach(struct mipi_dsi_device *dsi)
```

attach a DSI device to its DSI host

**Parameters**

- `struct mipi_dsi_device *dsi`: DSI peripheral

#### <a id="c-mipi_dsi_detach"></a>`mipi_dsi_detach()`

```c
int mipi_dsi_detach(struct mipi_dsi_device *dsi)
```

detach a DSI device from its DSI host

**Parameters**

- `struct mipi_dsi_device *dsi`: DSI peripheral

#### <a id="c-devm_mipi_dsi_attach"></a>`devm_mipi_dsi_attach()`

```c
int devm_mipi_dsi_attach(struct device *dev, struct mipi_dsi_device *dsi)
```

Attach a MIPI-DSI device to its DSI Host

**Parameters**

- `struct device *dev`: device to tie the MIPI-DSI device attachment lifetime to
- `struct mipi_dsi_device *dsi`: DSI peripheral

**Description**

This is the managed version of [`mipi_dsi_attach()`](#c-mipi_dsi_attach) which automatically
calls [`mipi_dsi_detach()`](#c-mipi_dsi_detach) when **dev** is unbound.

**Return**

0 on success, a negative error code on failure.

#### <a id="c-mipi_dsi_packet_format_is_short"></a>`mipi_dsi_packet_format_is_short()`

```c
bool mipi_dsi_packet_format_is_short(u8 type)
```

check if a packet is of the short format

**Parameters**

- `u8 type`: MIPI DSI data type of the packet

**Return**

true if the packet for the given data type is a short packet, false
otherwise.

#### <a id="c-mipi_dsi_packet_format_is_long"></a>`mipi_dsi_packet_format_is_long()`

```c
bool mipi_dsi_packet_format_is_long(u8 type)
```

check if a packet is of the long format

**Parameters**

- `u8 type`: MIPI DSI data type of the packet

**Return**

true if the packet for the given data type is a long packet, false
otherwise.

#### <a id="c-mipi_dsi_create_packet"></a>`mipi_dsi_create_packet()`

```c
int mipi_dsi_create_packet(struct mipi_dsi_packet *packet, const struct mipi_dsi_msg *msg)
```

create a packet from a message according to the DSI protocol

**Parameters**

- `struct mipi_dsi_packet *packet`: pointer to a DSI packet structure
- `const struct mipi_dsi_msg *msg`: message to translate into a packet

**Return**

0 on success or a negative error code on failure.

#### <a id="c-mipi_dsi_shutdown_peripheral"></a>`mipi_dsi_shutdown_peripheral()`

```c
int mipi_dsi_shutdown_peripheral(struct mipi_dsi_device *dsi)
```

sends a Shutdown Peripheral command

**Parameters**

- `struct mipi_dsi_device *dsi`: DSI peripheral device

**Return**

0 on success or a negative error code on failure.

#### <a id="c-mipi_dsi_turn_on_peripheral"></a>`mipi_dsi_turn_on_peripheral()`

```c
int mipi_dsi_turn_on_peripheral(struct mipi_dsi_device *dsi)
```

sends a Turn On Peripheral command

**Parameters**

- `struct mipi_dsi_device *dsi`: DSI peripheral device

**Description**

This function is deprecated. Use [`mipi_dsi_turn_on_peripheral_multi()`](#c-mipi_dsi_turn_on_peripheral_multi) instead.

**Return**

0 on success or a negative error code on failure.

#### <a id="c-mipi_dsi_compression_mode_ext"></a>`mipi_dsi_compression_mode_ext()`

```c
int mipi_dsi_compression_mode_ext(struct mipi_dsi_device *dsi, bool enable, enum mipi_dsi_compression_algo algo, unsigned int pps_selector)
```

enable/disable DSC on the peripheral

**Parameters**

- `struct mipi_dsi_device *dsi`: DSI peripheral device
- `bool enable`: Whether to enable or disable the DSC
- `enum mipi_dsi_compression_algo algo`: Selected compression algorithm
- `unsigned int pps_selector`: Select PPS from the table of pre-stored or uploaded PPS entries

**Description**

Enable or disable Display Stream Compression on the peripheral.
This function is deprecated. Use [`mipi_dsi_compression_mode_ext_multi()`](#c-mipi_dsi_compression_mode_ext_multi) instead.

**Return**

0 on success or a negative error code on failure.

#### <a id="c-mipi_dsi_compression_mode"></a>`mipi_dsi_compression_mode()`

```c
int mipi_dsi_compression_mode(struct mipi_dsi_device *dsi, bool enable)
```

enable/disable DSC on the peripheral

**Parameters**

- `struct mipi_dsi_device *dsi`: DSI peripheral device
- `bool enable`: Whether to enable or disable the DSC

**Description**

Enable or disable Display Stream Compression on the peripheral using the
default Picture Parameter Set and VESA DSC 1.1 algorithm.

**Return**

0 on success or a negative error code on failure.

#### <a id="c-mipi_dsi_picture_parameter_set"></a>`mipi_dsi_picture_parameter_set()`

```c
int mipi_dsi_picture_parameter_set(struct mipi_dsi_device *dsi, const struct drm_dsc_picture_parameter_set *pps)
```

transmit the DSC PPS to the peripheral

**Parameters**

- `struct mipi_dsi_device *dsi`: DSI peripheral device
- `const struct drm_dsc_picture_parameter_set *pps`: VESA DSC 1.1 Picture Parameter Set

**Description**

Transmit the VESA DSC 1.1 Picture Parameter Set to the peripheral.
This function is deprecated. Use [`mipi_dsi_picture_parameter_set_multi()`](#c-mipi_dsi_picture_parameter_set_multi) instead.

**Return**

0 on success or a negative error code on failure.

#### <a id="c-mipi_dsi_generic_write"></a>`mipi_dsi_generic_write()`

```c
ssize_t mipi_dsi_generic_write(struct mipi_dsi_device *dsi, const void *payload, size_t size)
```

transmit data using a generic write packet

**Parameters**

- `struct mipi_dsi_device *dsi`: DSI peripheral device
- `const void *payload`: buffer containing the payload
- `size_t size`: size of payload buffer

**Description**

This function will automatically choose the right data type depending on
the payload length.

**Return**

The number of bytes transmitted on success or a negative error code
on failure.

#### <a id="c-mipi_dsi_generic_write_multi"></a>`mipi_dsi_generic_write_multi()`

```c
void mipi_dsi_generic_write_multi(struct mipi_dsi_multi_context *ctx, const void *payload, size_t size)
```

[`mipi_dsi_generic_write()`](#c-mipi_dsi_generic_write) w/ accum_err

**Parameters**

- `struct mipi_dsi_multi_context *ctx`: Context for multiple DSI transactions
- `const void *payload`: buffer containing the payload
- `size_t size`: size of payload buffer

**Description**

A wrapper around [`mipi_dsi_generic_write()`](#c-mipi_dsi_generic_write) that deals with errors in a way
that makes it convenient to make several calls in a row.

#### <a id="c-mipi_dsi_dual_generic_write_multi"></a>`mipi_dsi_dual_generic_write_multi()`

```c
void mipi_dsi_dual_generic_write_multi(struct mipi_dsi_multi_context *ctx, struct mipi_dsi_device *dsi1, struct mipi_dsi_device *dsi2, const void *payload, size_t size)
```

[`mipi_dsi_generic_write_multi()`](#c-mipi_dsi_generic_write_multi) for two dsi channels, one after the other

**Parameters**

- `struct mipi_dsi_multi_context *ctx`: Context for multiple DSI transactions
- `struct mipi_dsi_device *dsi1`: First dsi channel to write buffer to
- `struct mipi_dsi_device *dsi2`: Second dsi channel to write buffer to
- `const void *payload`: Buffer containing the payload
- `size_t size`: Size of payload buffer

**Description**

A wrapper around [`mipi_dsi_generic_write_multi()`](#c-mipi_dsi_generic_write_multi) that allows the user to
conveniently write to two dsi channels, one after the other.

#### <a id="c-mipi_dsi_generic_read"></a>`mipi_dsi_generic_read()`

```c
ssize_t mipi_dsi_generic_read(struct mipi_dsi_device *dsi, const void *params, size_t num_params, void *data, size_t size)
```

receive data using a generic read packet

**Parameters**

- `struct mipi_dsi_device *dsi`: DSI peripheral device
- `const void *params`: buffer containing the request parameters
- `size_t num_params`: number of request parameters
- `void *data`: buffer in which to return the received data
- `size_t size`: size of receive buffer

**Description**

This function will automatically choose the right data type depending on
the number of parameters passed in.

**Return**

The number of bytes successfully read or a negative error code on
failure.

#### <a id="c-drm_mipi_dsi_get_input_bus_fmt"></a>`drm_mipi_dsi_get_input_bus_fmt()`

```c
u32 drm_mipi_dsi_get_input_bus_fmt(enum mipi_dsi_pixel_format dsi_format)
```

Get the required MEDIA_BUS_FMT_* based input pixel format for a given DSI output pixel format

**Parameters**

- `enum mipi_dsi_pixel_format dsi_format`: pixel format that a DSI host needs to output

**Description**

Various DSI hosts can use this function during their
[`drm_bridge_funcs.atomic_get_input_bus_fmts`](#c-struct-drm_bridge_funcs) operation to ascertain
the MEDIA_BUS_FMT_* pixel format required as input.

**Return**

a 32-bit MEDIA_BUS_FMT_* value on success or 0 in case of failure.

#### <a id="c-mipi_dsi_dcs_write_buffer"></a>`mipi_dsi_dcs_write_buffer()`

```c
ssize_t mipi_dsi_dcs_write_buffer(struct mipi_dsi_device *dsi, const void *data, size_t len)
```

transmit a DCS command with payload

**Parameters**

- `struct mipi_dsi_device *dsi`: DSI peripheral device
- `const void *data`: buffer containing data to be transmitted
- `size_t len`: size of transmission buffer

**Description**

This function will automatically choose the right data type depending on
the command payload length.

**Return**

The number of bytes successfully transmitted or a negative error
code on failure.

#### <a id="c-mipi_dsi_dcs_write_buffer_chatty"></a>`mipi_dsi_dcs_write_buffer_chatty()`

```c
int mipi_dsi_dcs_write_buffer_chatty(struct mipi_dsi_device *dsi, const void *data, size_t len)
```

[`mipi_dsi_dcs_write_buffer()`](#c-mipi_dsi_dcs_write_buffer) w/ an error log

**Parameters**

- `struct mipi_dsi_device *dsi`: DSI peripheral device
- `const void *data`: buffer containing data to be transmitted
- `size_t len`: size of transmission buffer

**Description**

Like [`mipi_dsi_dcs_write_buffer()`](#c-mipi_dsi_dcs_write_buffer) but includes a `dev_err()`
call for you and returns 0 upon success, not the number of bytes sent.

**Return**

0 on success or a negative error code on failure.

#### <a id="c-mipi_dsi_dcs_write_buffer_multi"></a>`mipi_dsi_dcs_write_buffer_multi()`

```c
void mipi_dsi_dcs_write_buffer_multi(struct mipi_dsi_multi_context *ctx, const void *data, size_t len)
```

[`mipi_dsi_dcs_write_buffer_chatty()`](#c-mipi_dsi_dcs_write_buffer_chatty) w/ accum_err

**Parameters**

- `struct mipi_dsi_multi_context *ctx`: Context for multiple DSI transactions
- `const void *data`: buffer containing data to be transmitted
- `size_t len`: size of transmission buffer

**Description**

Like [`mipi_dsi_dcs_write_buffer_chatty()`](#c-mipi_dsi_dcs_write_buffer_chatty) but deals with errors in a way that
makes it convenient to make several calls in a row.

#### <a id="c-mipi_dsi_dual_dcs_write_buffer_multi"></a>`mipi_dsi_dual_dcs_write_buffer_multi()`

```c
void mipi_dsi_dual_dcs_write_buffer_multi(struct mipi_dsi_multi_context *ctx, struct mipi_dsi_device *dsi1, struct mipi_dsi_device *dsi2, const void *data, size_t len)
```

[`mipi_dsi_dcs_write_buffer_multi()`](#c-mipi_dsi_dcs_write_buffer_multi) for two dsi channels, one after the other

**Parameters**

- `struct mipi_dsi_multi_context *ctx`: Context for multiple DSI transactions
- `struct mipi_dsi_device *dsi1`: First dsi channel to write buffer to
- `struct mipi_dsi_device *dsi2`: Second dsi channel to write buffer to
- `const void *data`: Buffer containing data to be transmitted
- `size_t len`: Size of transmission buffer

**Description**

A wrapper around [`mipi_dsi_dcs_write_buffer_multi()`](#c-mipi_dsi_dcs_write_buffer_multi) that allows the user to
conveniently write to two dsi channels, one after the other.

#### <a id="c-mipi_dsi_dcs_write"></a>`mipi_dsi_dcs_write()`

```c
ssize_t mipi_dsi_dcs_write(struct mipi_dsi_device *dsi, u8 cmd, const void *data, size_t len)
```

send DCS write command

**Parameters**

- `struct mipi_dsi_device *dsi`: DSI peripheral device
- `u8 cmd`: DCS command
- `const void *data`: buffer containing the command payload
- `size_t len`: command payload length

**Description**

This function will automatically choose the right data type depending on
the command payload length.

**Return**

The number of bytes successfully transmitted or a negative error
code on failure.

#### <a id="c-mipi_dsi_dcs_read"></a>`mipi_dsi_dcs_read()`

```c
ssize_t mipi_dsi_dcs_read(struct mipi_dsi_device *dsi, u8 cmd, void *data, size_t len)
```

send DCS read request command

**Parameters**

- `struct mipi_dsi_device *dsi`: DSI peripheral device
- `u8 cmd`: DCS command
- `void *data`: buffer in which to receive data
- `size_t len`: size of receive buffer

**Return**

The number of bytes read or a negative error code on failure.

#### <a id="c-mipi_dsi_dcs_read_multi"></a>`mipi_dsi_dcs_read_multi()`

```c
void mipi_dsi_dcs_read_multi(struct mipi_dsi_multi_context *ctx, u8 cmd, void *data, size_t len)
```

[`mipi_dsi_dcs_read()`](#c-mipi_dsi_dcs_read) w/ accum_err

**Parameters**

- `struct mipi_dsi_multi_context *ctx`: Context for multiple DSI transactions
- `u8 cmd`: DCS command
- `void *data`: buffer in which to receive data
- `size_t len`: size of receive buffer

**Description**

Like [`mipi_dsi_dcs_read()`](#c-mipi_dsi_dcs_read) but deals with errors in a way that makes it
convenient to make several calls in a row.

#### <a id="c-mipi_dsi_dcs_nop"></a>`mipi_dsi_dcs_nop()`

```c
int mipi_dsi_dcs_nop(struct mipi_dsi_device *dsi)
```

send DCS nop packet

**Parameters**

- `struct mipi_dsi_device *dsi`: DSI peripheral device

**Description**

This function is deprecated. Use [`mipi_dsi_dcs_nop_multi()`](#c-mipi_dsi_dcs_nop_multi) instead.

**Return**

0 on success or a negative error code on failure.

#### <a id="c-mipi_dsi_dcs_soft_reset"></a>`mipi_dsi_dcs_soft_reset()`

```c
int mipi_dsi_dcs_soft_reset(struct mipi_dsi_device *dsi)
```

perform a software reset of the display module

**Parameters**

- `struct mipi_dsi_device *dsi`: DSI peripheral device

**Description**

This function is deprecated. Use [`mipi_dsi_dcs_soft_reset_multi()`](#c-mipi_dsi_dcs_soft_reset_multi) instead.

**Return**

0 on success or a negative error code on failure.

#### <a id="c-mipi_dsi_dcs_get_power_mode"></a>`mipi_dsi_dcs_get_power_mode()`

```c
int mipi_dsi_dcs_get_power_mode(struct mipi_dsi_device *dsi, u8 *mode)
```

query the display module's current power mode

**Parameters**

- `struct mipi_dsi_device *dsi`: DSI peripheral device
- `u8 *mode`: return location for the current power mode

**Return**

0 on success or a negative error code on failure.

#### <a id="c-mipi_dsi_dcs_get_pixel_format"></a>`mipi_dsi_dcs_get_pixel_format()`

```c
int mipi_dsi_dcs_get_pixel_format(struct mipi_dsi_device *dsi, u8 *format)
```

gets the pixel format for the RGB image data used by the interface

**Parameters**

- `struct mipi_dsi_device *dsi`: DSI peripheral device
- `u8 *format`: return location for the pixel format

**Return**

0 on success or a negative error code on failure.

#### <a id="c-mipi_dsi_dcs_enter_sleep_mode"></a>`mipi_dsi_dcs_enter_sleep_mode()`

```c
int mipi_dsi_dcs_enter_sleep_mode(struct mipi_dsi_device *dsi)
```

disable all unnecessary blocks inside the display module except interface communication

**Parameters**

- `struct mipi_dsi_device *dsi`: DSI peripheral device

**Description**

This function is deprecated. Use [`mipi_dsi_dcs_enter_sleep_mode_multi()`](#c-mipi_dsi_dcs_enter_sleep_mode_multi) instead.

**Return**

0 on success or a negative error code on failure.

#### <a id="c-mipi_dsi_dcs_exit_sleep_mode"></a>`mipi_dsi_dcs_exit_sleep_mode()`

```c
int mipi_dsi_dcs_exit_sleep_mode(struct mipi_dsi_device *dsi)
```

enable all blocks inside the display module

**Parameters**

- `struct mipi_dsi_device *dsi`: DSI peripheral device

**Description**

This function is deprecated. Use [`mipi_dsi_dcs_exit_sleep_mode_multi()`](#c-mipi_dsi_dcs_exit_sleep_mode_multi) instead.

**Return**

0 on success or a negative error code on failure.

#### <a id="c-mipi_dsi_dcs_set_display_off"></a>`mipi_dsi_dcs_set_display_off()`

```c
int mipi_dsi_dcs_set_display_off(struct mipi_dsi_device *dsi)
```

stop displaying the image data on the display device

**Parameters**

- `struct mipi_dsi_device *dsi`: DSI peripheral device

**Description**

This function is deprecated. Use [`mipi_dsi_dcs_set_display_off_multi()`](#c-mipi_dsi_dcs_set_display_off_multi) instead.

**Return**

0 on success or a negative error code on failure.

#### <a id="c-mipi_dsi_dcs_set_display_on"></a>`mipi_dsi_dcs_set_display_on()`

```c
int mipi_dsi_dcs_set_display_on(struct mipi_dsi_device *dsi)
```

start displaying the image data on the display device

**Parameters**

- `struct mipi_dsi_device *dsi`: DSI peripheral device

**Description**

This function is deprecated. Use [`mipi_dsi_dcs_set_display_on_multi()`](#c-mipi_dsi_dcs_set_display_on_multi) instead.

**Return**

0 on success or a negative error code on failure

#### <a id="c-mipi_dsi_dcs_set_column_address"></a>`mipi_dsi_dcs_set_column_address()`

```c
int mipi_dsi_dcs_set_column_address(struct mipi_dsi_device *dsi, u16 start, u16 end)
```

define the column extent of the frame memory accessed by the host processor

**Parameters**

- `struct mipi_dsi_device *dsi`: DSI peripheral device
- `u16 start`: first column of frame memory
- `u16 end`: last column of frame memory

**Description**

This function is deprecated. Use [`mipi_dsi_dcs_set_column_address_multi()`](#c-mipi_dsi_dcs_set_column_address_multi)
instead.

**Return**

0 on success or a negative error code on failure.

#### <a id="c-mipi_dsi_dcs_set_page_address"></a>`mipi_dsi_dcs_set_page_address()`

```c
int mipi_dsi_dcs_set_page_address(struct mipi_dsi_device *dsi, u16 start, u16 end)
```

define the page extent of the frame memory accessed by the host processor

**Parameters**

- `struct mipi_dsi_device *dsi`: DSI peripheral device
- `u16 start`: first page of frame memory
- `u16 end`: last page of frame memory

**Description**

This function is deprecated. Use [`mipi_dsi_dcs_set_page_address_multi()`](#c-mipi_dsi_dcs_set_page_address_multi)
instead.

**Return**

0 on success or a negative error code on failure.

#### <a id="c-mipi_dsi_dcs_set_tear_on"></a>`mipi_dsi_dcs_set_tear_on()`

```c
int mipi_dsi_dcs_set_tear_on(struct mipi_dsi_device *dsi, enum mipi_dsi_dcs_tear_mode mode)
```

turn on the display module's Tearing Effect output signal on the TE signal line.

**Parameters**

- `struct mipi_dsi_device *dsi`: DSI peripheral device
- `enum mipi_dsi_dcs_tear_mode mode`: the Tearing Effect Output Line mode

**Description**

This function is deprecated. Use [`mipi_dsi_dcs_set_tear_on_multi()`](#c-mipi_dsi_dcs_set_tear_on_multi) instead.

**Return**

0 on success or a negative error code on failure

#### <a id="c-mipi_dsi_dcs_set_pixel_format"></a>`mipi_dsi_dcs_set_pixel_format()`

```c
int mipi_dsi_dcs_set_pixel_format(struct mipi_dsi_device *dsi, u8 format)
```

sets the pixel format for the RGB image data used by the interface

**Parameters**

- `struct mipi_dsi_device *dsi`: DSI peripheral device
- `u8 format`: pixel format

**Description**

This function is deprecated. Use [`mipi_dsi_dcs_set_pixel_format_multi()`](#c-mipi_dsi_dcs_set_pixel_format_multi)
instead.

**Return**

0 on success or a negative error code on failure.

#### <a id="c-mipi_dsi_dcs_set_tear_scanline"></a>`mipi_dsi_dcs_set_tear_scanline()`

```c
int mipi_dsi_dcs_set_tear_scanline(struct mipi_dsi_device *dsi, u16 scanline)
```

set the scanline to use as trigger for the Tearing Effect output signal of the display module

**Parameters**

- `struct mipi_dsi_device *dsi`: DSI peripheral device
- `u16 scanline`: scanline to use as trigger

**Description**

This function is deprecated. Use [`mipi_dsi_dcs_set_tear_scanline_multi()`](#c-mipi_dsi_dcs_set_tear_scanline_multi)
instead.

**Return**

0 on success or a negative error code on failure

#### <a id="c-mipi_dsi_dcs_set_display_brightness"></a>`mipi_dsi_dcs_set_display_brightness()`

```c
int mipi_dsi_dcs_set_display_brightness(struct mipi_dsi_device *dsi, u16 brightness)
```

sets the brightness value of the display

**Parameters**

- `struct mipi_dsi_device *dsi`: DSI peripheral device
- `u16 brightness`: brightness value

**Description**

This function is deprecated. Use [`mipi_dsi_dcs_set_display_brightness_multi()`](#c-mipi_dsi_dcs_set_display_brightness_multi)
instead.

**Return**

0 on success or a negative error code on failure.

#### <a id="c-mipi_dsi_dcs_get_display_brightness"></a>`mipi_dsi_dcs_get_display_brightness()`

```c
int mipi_dsi_dcs_get_display_brightness(struct mipi_dsi_device *dsi, u16 *brightness)
```

gets the current brightness value of the display

**Parameters**

- `struct mipi_dsi_device *dsi`: DSI peripheral device
- `u16 *brightness`: brightness value

**Return**

0 on success or a negative error code on failure.

#### <a id="c-mipi_dsi_dcs_set_display_brightness_large"></a>`mipi_dsi_dcs_set_display_brightness_large()`

```c
int mipi_dsi_dcs_set_display_brightness_large(struct mipi_dsi_device *dsi, u16 brightness)
```

sets the 16-bit brightness value of the display

**Parameters**

- `struct mipi_dsi_device *dsi`: DSI peripheral device
- `u16 brightness`: brightness value

**Return**

0 on success or a negative error code on failure.

#### <a id="c-mipi_dsi_dcs_get_display_brightness_large"></a>`mipi_dsi_dcs_get_display_brightness_large()`

```c
int mipi_dsi_dcs_get_display_brightness_large(struct mipi_dsi_device *dsi, u16 *brightness)
```

gets the current 16-bit brightness value of the display

**Parameters**

- `struct mipi_dsi_device *dsi`: DSI peripheral device
- `u16 *brightness`: brightness value

**Return**

0 on success or a negative error code on failure.

#### <a id="c-mipi_dsi_picture_parameter_set_multi"></a>`mipi_dsi_picture_parameter_set_multi()`

```c
void mipi_dsi_picture_parameter_set_multi(struct mipi_dsi_multi_context *ctx, const struct drm_dsc_picture_parameter_set *pps)
```

transmit the DSC PPS to the peripheral

**Parameters**

- `struct mipi_dsi_multi_context *ctx`: Context for multiple DSI transactions
- `const struct drm_dsc_picture_parameter_set *pps`: VESA DSC 1.1 Picture Parameter Set

**Description**

Like [`mipi_dsi_picture_parameter_set()`](#c-mipi_dsi_picture_parameter_set) but deals with errors in a way that
makes it convenient to make several calls in a row.

#### <a id="c-mipi_dsi_compression_mode_ext_multi"></a>`mipi_dsi_compression_mode_ext_multi()`

```c
void mipi_dsi_compression_mode_ext_multi(struct mipi_dsi_multi_context *ctx, bool enable, enum mipi_dsi_compression_algo algo, unsigned int pps_selector)
```

enable/disable DSC on the peripheral

**Parameters**

- `struct mipi_dsi_multi_context *ctx`: Context for multiple DSI transactions
- `bool enable`: Whether to enable or disable the DSC
- `enum mipi_dsi_compression_algo algo`: Selected compression algorithm
- `unsigned int pps_selector`: Select PPS from the table of pre-stored or uploaded PPS entries

**Description**

Like [`mipi_dsi_compression_mode_ext()`](#c-mipi_dsi_compression_mode_ext) but deals with errors in a way that
makes it convenient to make several calls in a row.

#### <a id="c-mipi_dsi_compression_mode_multi"></a>`mipi_dsi_compression_mode_multi()`

```c
void mipi_dsi_compression_mode_multi(struct mipi_dsi_multi_context *ctx, bool enable)
```

enable/disable DSC on the peripheral

**Parameters**

- `struct mipi_dsi_multi_context *ctx`: Context for multiple DSI transactions
- `bool enable`: Whether to enable or disable the DSC

**Description**

Enable or disable Display Stream Compression on the peripheral using the
default Picture Parameter Set and VESA DSC 1.1 algorithm.

#### <a id="c-mipi_dsi_dcs_nop_multi"></a>`mipi_dsi_dcs_nop_multi()`

```c
void mipi_dsi_dcs_nop_multi(struct mipi_dsi_multi_context *ctx)
```

send DCS NOP packet

**Parameters**

- `struct mipi_dsi_multi_context *ctx`: Context for multiple DSI transactions

**Description**

Like [`mipi_dsi_dcs_nop()`](#c-mipi_dsi_dcs_nop) but deals with errors in a way that
makes it convenient to make several calls in a row.

#### <a id="c-mipi_dsi_dcs_enter_sleep_mode_multi"></a>`mipi_dsi_dcs_enter_sleep_mode_multi()`

```c
void mipi_dsi_dcs_enter_sleep_mode_multi(struct mipi_dsi_multi_context *ctx)
```

send DCS ENTER_SLEEP_MODE packet

**Parameters**

- `struct mipi_dsi_multi_context *ctx`: Context for multiple DSI transactions

**Description**

Like [`mipi_dsi_dcs_enter_sleep_mode()`](#c-mipi_dsi_dcs_enter_sleep_mode) but deals with errors in a way that
makes it convenient to make several calls in a row.

#### <a id="c-mipi_dsi_dcs_exit_sleep_mode_multi"></a>`mipi_dsi_dcs_exit_sleep_mode_multi()`

```c
void mipi_dsi_dcs_exit_sleep_mode_multi(struct mipi_dsi_multi_context *ctx)
```

send DCS EXIT_SLEEP_MODE packet

**Parameters**

- `struct mipi_dsi_multi_context *ctx`: Context for multiple DSI transactions

**Description**

Like [`mipi_dsi_dcs_exit_sleep_mode()`](#c-mipi_dsi_dcs_exit_sleep_mode) but deals with errors in a way that
makes it convenient to make several calls in a row.

#### <a id="c-mipi_dsi_dcs_set_display_off_multi"></a>`mipi_dsi_dcs_set_display_off_multi()`

```c
void mipi_dsi_dcs_set_display_off_multi(struct mipi_dsi_multi_context *ctx)
```

send DCS SET_DISPLAY_OFF packet

**Parameters**

- `struct mipi_dsi_multi_context *ctx`: Context for multiple DSI transactions

**Description**

Like [`mipi_dsi_dcs_set_display_off()`](#c-mipi_dsi_dcs_set_display_off) but deals with errors in a way that
makes it convenient to make several calls in a row.

#### <a id="c-mipi_dsi_dcs_set_display_on_multi"></a>`mipi_dsi_dcs_set_display_on_multi()`

```c
void mipi_dsi_dcs_set_display_on_multi(struct mipi_dsi_multi_context *ctx)
```

send DCS SET_DISPLAY_ON packet

**Parameters**

- `struct mipi_dsi_multi_context *ctx`: Context for multiple DSI transactions

**Description**

Like [`mipi_dsi_dcs_set_display_on()`](#c-mipi_dsi_dcs_set_display_on) but deals with errors in a way that
makes it convenient to make several calls in a row.

#### <a id="c-mipi_dsi_dcs_set_tear_on_multi"></a>`mipi_dsi_dcs_set_tear_on_multi()`

```c
void mipi_dsi_dcs_set_tear_on_multi(struct mipi_dsi_multi_context *ctx, enum mipi_dsi_dcs_tear_mode mode)
```

send DCS SET_TEAR_ON packet

**Parameters**

- `struct mipi_dsi_multi_context *ctx`: Context for multiple DSI transactions
- `enum mipi_dsi_dcs_tear_mode mode`: the Tearing Effect Output Line mode

**Description**

Like [`mipi_dsi_dcs_set_tear_on()`](#c-mipi_dsi_dcs_set_tear_on) but deals with errors in a way that
makes it convenient to make several calls in a row.

#### <a id="c-mipi_dsi_turn_on_peripheral_multi"></a>`mipi_dsi_turn_on_peripheral_multi()`

```c
void mipi_dsi_turn_on_peripheral_multi(struct mipi_dsi_multi_context *ctx)
```

sends a Turn On Peripheral command

**Parameters**

- `struct mipi_dsi_multi_context *ctx`: Context for multiple DSI transactions

**Description**

Like [`mipi_dsi_turn_on_peripheral()`](#c-mipi_dsi_turn_on_peripheral) but deals with errors in a way that
makes it convenient to make several calls in a row.

#### <a id="c-mipi_dsi_dcs_set_tear_off_multi"></a>`mipi_dsi_dcs_set_tear_off_multi()`

```c
void mipi_dsi_dcs_set_tear_off_multi(struct mipi_dsi_multi_context *ctx)
```

turn off the display module's Tearing Effect output signal on the TE signal line

**Parameters**

- `struct mipi_dsi_multi_context *ctx`: Context for multiple DSI transactions

#### <a id="c-mipi_dsi_dcs_soft_reset_multi"></a>`mipi_dsi_dcs_soft_reset_multi()`

```c
void mipi_dsi_dcs_soft_reset_multi(struct mipi_dsi_multi_context *ctx)
```

perform a software reset of the display module

**Parameters**

- `struct mipi_dsi_multi_context *ctx`: Context for multiple DSI transactions

**Description**

Like [`mipi_dsi_dcs_soft_reset()`](#c-mipi_dsi_dcs_soft_reset) but deals with errors in a way that
makes it convenient to make several calls in a row.

#### <a id="c-mipi_dsi_dcs_set_display_brightness_multi"></a>`mipi_dsi_dcs_set_display_brightness_multi()`

```c
void mipi_dsi_dcs_set_display_brightness_multi(struct mipi_dsi_multi_context *ctx, u16 brightness)
```

sets the brightness value of the display

**Parameters**

- `struct mipi_dsi_multi_context *ctx`: Context for multiple DSI transactions
- `u16 brightness`: brightness value

**Description**

Like [`mipi_dsi_dcs_set_display_brightness()`](#c-mipi_dsi_dcs_set_display_brightness) but deals with errors in a way that
makes it convenient to make several calls in a row.

#### <a id="c-mipi_dsi_dcs_set_pixel_format_multi"></a>`mipi_dsi_dcs_set_pixel_format_multi()`

```c
void mipi_dsi_dcs_set_pixel_format_multi(struct mipi_dsi_multi_context *ctx, u8 format)
```

sets the pixel format for the RGB image data used by the interface

**Parameters**

- `struct mipi_dsi_multi_context *ctx`: Context for multiple DSI transactions
- `u8 format`: pixel format

**Description**

Like [`mipi_dsi_dcs_set_pixel_format()`](#c-mipi_dsi_dcs_set_pixel_format) but deals with errors in a way that
makes it convenient to make several calls in a row.

#### <a id="c-mipi_dsi_dcs_set_column_address_multi"></a>`mipi_dsi_dcs_set_column_address_multi()`

```c
void mipi_dsi_dcs_set_column_address_multi(struct mipi_dsi_multi_context *ctx, u16 start, u16 end)
```

define the column extent of the frame memory accessed by the host processor

**Parameters**

- `struct mipi_dsi_multi_context *ctx`: Context for multiple DSI transactions
- `u16 start`: first column of frame memory
- `u16 end`: last column of frame memory

**Description**

Like [`mipi_dsi_dcs_set_column_address()`](#c-mipi_dsi_dcs_set_column_address) but deals with errors in a way that
makes it convenient to make several calls in a row.

#### <a id="c-mipi_dsi_dcs_set_page_address_multi"></a>`mipi_dsi_dcs_set_page_address_multi()`

```c
void mipi_dsi_dcs_set_page_address_multi(struct mipi_dsi_multi_context *ctx, u16 start, u16 end)
```

define the page extent of the frame memory accessed by the host processor

**Parameters**

- `struct mipi_dsi_multi_context *ctx`: Context for multiple DSI transactions
- `u16 start`: first page of frame memory
- `u16 end`: last page of frame memory

**Description**

Like [`mipi_dsi_dcs_set_page_address()`](#c-mipi_dsi_dcs_set_page_address) but deals with errors in a way that
makes it convenient to make several calls in a row.

#### <a id="c-mipi_dsi_dcs_set_tear_scanline_multi"></a>`mipi_dsi_dcs_set_tear_scanline_multi()`

```c
void mipi_dsi_dcs_set_tear_scanline_multi(struct mipi_dsi_multi_context *ctx, u16 scanline)
```

set the scanline to use as trigger for the Tearing Effect output signal of the display module

**Parameters**

- `struct mipi_dsi_multi_context *ctx`: Context for multiple DSI transactions
- `u16 scanline`: scanline to use as trigger

**Description**

Like [`mipi_dsi_dcs_set_tear_scanline()`](#c-mipi_dsi_dcs_set_tear_scanline) but deals with errors in a way that
makes it convenient to make several calls in a row.

#### <a id="c-mipi_dsi_driver_register_full"></a>`mipi_dsi_driver_register_full()`

```c
int mipi_dsi_driver_register_full(struct mipi_dsi_driver *drv, struct module *owner)
```

register a driver for DSI devices

**Parameters**

- `struct mipi_dsi_driver *drv`: DSI driver structure
- `struct module *owner`: owner module

**Return**

0 on success or a negative error code on failure.

#### <a id="c-mipi_dsi_driver_unregister"></a>`mipi_dsi_driver_unregister()`

```c
void mipi_dsi_driver_unregister(struct mipi_dsi_driver *drv)
```

unregister a driver for DSI devices

**Parameters**

- `struct mipi_dsi_driver *drv`: DSI driver structure

**Return**

0 on success or a negative error code on failure.


<a id="rst-display-stream-compression-helper-functions-reference"></a>

## Display Stream Compression Helper Functions Reference


VESA specification for DP 1.4 adds a new feature called Display Stream
Compression (DSC) used to compress the pixel bits before sending it on
DP/eDP/MIPI DSI interface. DSC is required to be enabled so that the existing
display interfaces can support high resolutions at higher frames rates uisng
the maximum available link capacity of these interfaces.

These functions contain some common logic and helpers to deal with VESA
Display Stream Compression standard required for DSC on Display Port/eDP or
MIPI display interfaces.



#### <a id="c-struct-drm_dsc_rc_range_parameters"></a>`struct drm_dsc_rc_range_parameters`

DSC Rate Control range parameters

**Definition**

```c
struct drm_dsc_rc_range_parameters {
    u8 range_min_qp;
    u8 range_max_qp;
    u8 range_bpg_offset;
};
```

**Members**

- `range_min_qp`: Min Quantization Parameters allowed for this range
- `range_max_qp`: Max Quantization Parameters allowed for this range
- `range_bpg_offset`: Bits/group offset to apply to target for this group

**Description**

This defines different rate control parameters used by the DSC engine
to compress the frame.

#### <a id="c-struct-drm_dsc_config"></a>`struct drm_dsc_config`

Parameters required to configure DSC

**Definition**

```c
struct drm_dsc_config {
    u8 line_buf_depth;
    u8 bits_per_component;
    bool convert_rgb;
    u8 slice_count;
    u16 slice_width;
    u16 slice_height;
    bool simple_422;
    u16 pic_width;
    u16 pic_height;
    u8 rc_tgt_offset_high;
    u8 rc_tgt_offset_low;
    u16 bits_per_pixel;
    u8 rc_edge_factor;
    u8 rc_quant_incr_limit1;
    u8 rc_quant_incr_limit0;
    u16 initial_xmit_delay;
    u16 initial_dec_delay;
    bool block_pred_enable;
    u8 first_line_bpg_offset;
    u16 initial_offset;
    u16 rc_buf_thresh[DSC_NUM_BUF_RANGES - 1];
    struct drm_dsc_rc_range_parameters rc_range_params[DSC_NUM_BUF_RANGES];
    u16 rc_model_size;
    u8 flatness_min_qp;
    u8 flatness_max_qp;
    u8 initial_scale_value;
    u16 scale_decrement_interval;
    u16 scale_increment_interval;
    u16 nfl_bpg_offset;
    u16 slice_bpg_offset;
    u16 final_offset;
    bool vbr_enable;
    u8 mux_word_size;
    u16 slice_chunk_size;
    u16 rc_bits;
    u8 dsc_version_minor;
    u8 dsc_version_major;
    bool native_422;
    bool native_420;
    u8 second_line_bpg_offset;
    u16 nsl_bpg_offset;
    u16 second_line_offset_adj;
};
```

**Members**

- `line_buf_depth`: Bits per component for previous reconstructed line buffer
- `bits_per_component`: Bits per component to code (8/10/12)
- `convert_rgb`: Flag to indicate if RGB - YCoCg conversion is needed
  True if RGB input, False if YCoCg input
- `slice_count`: Number fo slices per line used by the DSC encoder
- `slice_width`: Width of each slice in pixels
- `slice_height`: Slice height in pixels
- `simple_422`: True if simple 4_2_2 mode is enabled else False
- `pic_width`: Width of the input display frame in pixels
- `pic_height`: Vertical height of the input display frame
- `rc_tgt_offset_high`: Offset to bits/group used by RC to determine QP adjustment
- `rc_tgt_offset_low`: Offset to bits/group used by RC to determine QP adjustment
- `bits_per_pixel`: Target bits per pixel with 4 fractional bits, bits_per_pixel \<\< 4
- `rc_edge_factor`: Factor to determine if an edge is present based on the bits produced
- `rc_quant_incr_limit1`: Slow down incrementing once the range reaches this value
- `rc_quant_incr_limit0`: Slow down incrementing once the range reaches this value
- `initial_xmit_delay`: Number of pixels to delay the initial transmission
- `initial_dec_delay`: Initial decoder delay, number of pixel times that the decoder
  accumulates data in its rate buffer before starting to decode
  and output pixels.
- `block_pred_enable`: True if block prediction is used to code any groups within the
  picture. False if BP not used
- `first_line_bpg_offset`: Number of additional bits allocated for each group on the first
  line of slice.
- `initial_offset`: Value to use for RC model offset at slice start
- `rc_buf_thresh`: Thresholds defining each of the buffer ranges
- `rc_range_params`: Parameters for each of the RC ranges defined in
  [`struct drm_dsc_rc_range_parameters`](#c-struct-drm_dsc_rc_range_parameters)
- `rc_model_size`: Total size of RC model
- `flatness_min_qp`: Minimum QP where flatness information is sent
- `flatness_max_qp`: Maximum QP where flatness information is sent
- `initial_scale_value`: Initial value for the scale factor
- `scale_decrement_interval`: Specifies number of group times between decrementing the scale factor
  at beginning of a slice.
- `scale_increment_interval`: Number of group times between incrementing the scale factor value
  used at the beginning of a slice.
- `nfl_bpg_offset`: Non first line BPG offset to be used
- `slice_bpg_offset`: BPG offset used to enforce slice bit
- `final_offset`: Final RC linear transformation offset value
- `vbr_enable`: True if VBR mode is enabled, false if disabled
- `mux_word_size`: Mux word size (in bits) for SSM mode
- `slice_chunk_size`: The (max) size in bytes of the "chunks" that are used in slice
  multiplexing.
- `rc_bits`: Rate control buffer size in bits
- `dsc_version_minor`: DSC minor version
- `dsc_version_major`: DSC major version
- `native_422`: True if Native 4:2:2 supported, else false
- `native_420`: True if Native 4:2:0 supported else false.
- `second_line_bpg_offset`: Additional bits/grp for seconnd line of slice for native 4:2:0
- `nsl_bpg_offset`: Num of bits deallocated for each grp that is not in second line of
  slice
- `second_line_offset_adj`: Offset adjustment for second line in Native 4:2:0 mode

**Description**

Driver populates this structure with all the parameters required
to configure the display stream compression on the source.

#### <a id="c-struct-drm_dsc_picture_parameter_set"></a>`struct drm_dsc_picture_parameter_set`

Represents 128 bytes of Picture Parameter Set

**Definition**

```c
struct drm_dsc_picture_parameter_set {
    u8 dsc_version;
    u8 pps_identifier;
    u8 pps_reserved;
    u8 pps_3;
    u8 pps_4;
    u8 bits_per_pixel_low;
    __be16 pic_height;
    __be16 pic_width;
    __be16 slice_height;
    __be16 slice_width;
    __be16 chunk_size;
    u8 initial_xmit_delay_high;
    u8 initial_xmit_delay_low;
    __be16 initial_dec_delay;
    u8 pps20_reserved;
    u8 initial_scale_value;
    __be16 scale_increment_interval;
    u8 scale_decrement_interval_high;
    u8 scale_decrement_interval_low;
    u8 pps26_reserved;
    u8 first_line_bpg_offset;
    __be16 nfl_bpg_offset;
    __be16 slice_bpg_offset;
    __be16 initial_offset;
    __be16 final_offset;
    u8 flatness_min_qp;
    u8 flatness_max_qp;
    __be16 rc_model_size;
    u8 rc_edge_factor;
    u8 rc_quant_incr_limit0;
    u8 rc_quant_incr_limit1;
    u8 rc_tgt_offset;
    u8 rc_buf_thresh[DSC_NUM_BUF_RANGES - 1];
    __be16 rc_range_parameters[DSC_NUM_BUF_RANGES];
    u8 native_422_420;
    u8 second_line_bpg_offset;
    __be16 nsl_bpg_offset;
    __be16 second_line_offset_adj;
    u32 pps_long_94_reserved;
    u32 pps_long_98_reserved;
    u32 pps_long_102_reserved;
    u32 pps_long_106_reserved;
    u32 pps_long_110_reserved;
    u32 pps_long_114_reserved;
    u32 pps_long_118_reserved;
    u32 pps_long_122_reserved;
    __be16 pps_short_126_reserved;
};
```

**Members**

- `dsc_version`: PPS0\[3:0\] - dsc_version_minor: Contains Minor version of DSC
  PPS0\[7:4\] - dsc_version_major: Contains major version of DSC
- `pps_identifier`: PPS1\[7:0\] - Application specific identifier that can be
  used to differentiate between different PPS tables.
- `pps_reserved`: PPS2\[7:0\]- RESERVED Byte
- `pps_3`: PPS3\[3:0\] - linebuf_depth: Contains linebuffer bit depth used to
  generate the bitstream. (0x0 - 16 bits for DSC 1.2, 0x8 - 8 bits,
  0xA - 10 bits, 0xB - 11 bits, 0xC - 12 bits, 0xD - 13 bits,
  0xE - 14 bits for DSC1.2, 0xF - 14 bits for DSC 1.2.
  PPS3\[7:4\] - bits_per_component: Bits per component for the original
  pixels of the encoded picture.
  0x0 = 16bpc (allowed only when dsc_version_minor = 0x2)
  0x8 = 8bpc, 0xA = 10bpc, 0xC = 12bpc, 0xE = 14bpc (also
  allowed only when dsc_minor_version = 0x2)
- `pps_4`: PPS4\[1:0\] -These are the most significant 2 bits of
  compressed BPP bits_per_pixel\[9:0\] syntax element.
  PPS4\[2\] - vbr_enable: 0 = VBR disabled, 1 = VBR enabled
  PPS4\[3\] - simple_422: Indicates if decoder drops samples to
  reconstruct the 4:2:2 picture.
  PPS4\[4\] - Convert_rgb: Indicates if DSC color space conversion is
  active.
  PPS4\[5\] - blobk_pred_enable: Indicates if BP is used to code any
  groups in picture
  PPS4\[7:6\] - Reseved bits
- `bits_per_pixel_low`: PPS5\[7:0\] - This indicates the lower significant 8 bits of
  the compressed BPP bits_per_pixel\[9:0\] element.
- `pic_height`: PPS6\[7:0\], PPS7\[7:0\] -pic_height: Specifies the number of pixel rows
  within the raster.
- `pic_width`: PPS8\[7:0\], PPS9\[7:0\] - pic_width: Number of pixel columns within
  the raster.
- `slice_height`: PPS10\[7:0\], PPS11\[7:0\] - Slice height in units of pixels.
- `slice_width`: PPS12\[7:0\], PPS13\[7:0\] - Slice width in terms of pixels.
- `chunk_size`: PPS14\[7:0\], PPS15\[7:0\] - Size in units of bytes of the chunks
  that are used for slice multiplexing.
- `initial_xmit_delay_high`: PPS16\[1:0\] - Most Significant two bits of initial transmission delay.
  It specifies the number of pixel times that the encoder waits before
  transmitting data from its rate buffer.
  PPS16\[7:2\] - Reserved
- `initial_xmit_delay_low`: PPS17\[7:0\] - Least significant 8 bits of initial transmission delay.
- `initial_dec_delay`: PPS18\[7:0\], PPS19\[7:0\] - Initial decoding delay which is the number
  of pixel times that the decoder accumulates data in its rate buffer
  before starting to decode and output pixels.
- `pps20_reserved`: PPS20\[7:0\] - Reserved
- `initial_scale_value`: PPS21\[5:0\] - Initial rcXformScale factor used at beginning
  of a slice.
  PPS21\[7:6\] - Reserved
- `scale_increment_interval`: PPS22\[7:0\], PPS23\[7:0\] - Number of group times between incrementing
  the rcXformScale factor at end of a slice.
- `scale_decrement_interval_high`: PPS24\[3:0\] - Higher 4 bits indicating number of group times between
  decrementing the rcXformScale factor at beginning of a slice.
  PPS24\[7:4\] - Reserved
- `scale_decrement_interval_low`: PPS25\[7:0\] - Lower 8 bits of scale decrement interval
- `pps26_reserved`: PPS26\[7:0\]
- `first_line_bpg_offset`: PPS27\[4:0\] - Number of additional bits that are allocated
  for each group on first line of a slice.
  PPS27\[7:5\] - Reserved
- `nfl_bpg_offset`: PPS28\[7:0\], PPS29\[7:0\] - Number of bits including frac bits
  deallocated for each group for groups after the first line of slice.
- `slice_bpg_offset`: PPS30, PPS31\[7:0\] - Number of bits that are deallocated for each
  group to enforce the slice constraint.
- `initial_offset`: PPS32,33\[7:0\] - Initial value for rcXformOffset
- `final_offset`: PPS34,35\[7:0\] - Maximum end-of-slice value for rcXformOffset
- `flatness_min_qp`: PPS36\[4:0\] - Minimum QP at which flatness is signaled and
  flatness QP adjustment is made.
  PPS36\[7:5\] - Reserved
- `flatness_max_qp`: PPS37\[4:0\] - Max QP at which flatness is signalled and
  the flatness adjustment is made.
  PPS37\[7:5\] - Reserved
- `rc_model_size`: PPS38,39\[7:0\] - Number of bits within RC Model.
- `rc_edge_factor`: PPS40\[3:0\] - Ratio of current activity vs, previous
  activity to determine presence of edge.
  PPS40\[7:4\] - Reserved
- `rc_quant_incr_limit0`: PPS41\[4:0\] - QP threshold used in short term RC
  PPS41\[7:5\] - Reserved
- `rc_quant_incr_limit1`: PPS42\[4:0\] - QP threshold used in short term RC
  PPS42\[7:5\] - Reserved
- `rc_tgt_offset`: PPS43\[3:0\] - Lower end of the variability range around the target
  bits per group that is allowed by short term RC.
  PPS43\[7:4\]- Upper end of the variability range around the target
  bits per group that i allowed by short term rc.
- `rc_buf_thresh`: PPS44\[7:0\] - PPS57\[7:0\] - Specifies the thresholds in RC model for
  the 15 ranges defined by 14 thresholds.
- `rc_range_parameters`: PPS58\[7:0\] - PPS87\[7:0\]
  Parameters that correspond to each of the 15 ranges.
- `native_422_420`: PPS88\[0\] - 0 = Native 4:2:2 not used
  1 = Native 4:2:2 used
  PPS88\[1\] - 0 = Native 4:2:0 not use
  1 = Native 4:2:0 used
  PPS88\[7:2\] - Reserved 6 bits
- `second_line_bpg_offset`: PPS89\[4:0\] - Additional bits/group budget for the
  second line of a slice in Native 4:2:0 mode.
  Set to 0 if DSC minor version is 1 or native420 is 0.
  PPS89\[7:5\] - Reserved
- `nsl_bpg_offset`: PPS90\[7:0\], PPS91\[7:0\] - Number of bits that are deallocated
  for each group that is not in the second line of a slice.
- `second_line_offset_adj`: PPS92\[7:0\], PPS93\[7:0\] - Used as offset adjustment for the second
  line in Native 4:2:0 mode.
- `pps_long_94_reserved`: PPS 94, 95, 96, 97 - Reserved
- `pps_long_98_reserved`: PPS 98, 99, 100, 101 - Reserved
- `pps_long_102_reserved`: PPS 102, 103, 104, 105 - Reserved
- `pps_long_106_reserved`: PPS 106, 107, 108, 109 - reserved
- `pps_long_110_reserved`: PPS 110, 111, 112, 113 - reserved
- `pps_long_114_reserved`: PPS 114 - 117 - reserved
- `pps_long_118_reserved`: PPS 118 - 121 - reserved
- `pps_long_122_reserved`: PPS 122- 125 - reserved
- `pps_short_126_reserved`: PPS 126, 127 - reserved

**Description**

The VESA DSC standard defines picture parameter set (PPS) which display
stream compression encoders must communicate to decoders.
The PPS is encapsulated in 128 bytes (PPS 0 through PPS 127). The fields in
this structure are as per Table 4.1 in Vesa DSC specification v1.1/v1.2.
The PPS fields that span over more than a byte should be stored in Big Endian
format.

#### <a id="c-struct-drm_dsc_pps_infoframe"></a>`struct drm_dsc_pps_infoframe`

DSC infoframe carrying the Picture Parameter Set Metadata

**Definition**

```c
struct drm_dsc_pps_infoframe {
    struct dp_sdp_header pps_header;
    struct drm_dsc_picture_parameter_set pps_payload;
};
```

**Members**

- `pps_header`: Header for PPS as per DP SDP header format of type
  [`struct dp_sdp_header`](#c-struct-dp_sdp_header)
- `pps_payload`: PPS payload fields as per DSC specification Table 4-1
  as represented in [`struct drm_dsc_picture_parameter_set`](#c-struct-drm_dsc_picture_parameter_set)

**Description**

This structure represents the DSC PPS infoframe required to send the Picture
Parameter Set metadata required before enabling VESA Display Stream
Compression. This is based on the DP Secondary Data Packet structure and
comprises of SDP Header as defined [`struct dp_sdp_header`](#c-struct-dp_sdp_header) in drm_dp_helper.h
and PPS payload defined in [`struct drm_dsc_picture_parameter_set`](#c-struct-drm_dsc_picture_parameter_set).



#### <a id="c-drm_dsc_dp_pps_header_init"></a>`drm_dsc_dp_pps_header_init()`

```c
void drm_dsc_dp_pps_header_init(struct dp_sdp_header *pps_header)
```

Initializes the PPS Header for DisplayPort as per the DP 1.4 spec.

**Parameters**

- `struct dp_sdp_header *pps_header`: Secondary data packet header for DSC Picture
  Parameter Set as defined in [`struct dp_sdp_header`](#c-struct-dp_sdp_header)

**Description**

DP 1.4 spec defines the secondary data packet for sending the
picture parameter infoframes from the source to the sink.
This function populates the SDP header defined in
[`struct dp_sdp_header`](#c-struct-dp_sdp_header).

#### <a id="c-drm_dsc_dp_rc_buffer_size"></a>`drm_dsc_dp_rc_buffer_size()`

```c
int drm_dsc_dp_rc_buffer_size(u8 rc_buffer_block_size, u8 rc_buffer_size)
```

get rc buffer size in bytes

**Parameters**

- `u8 rc_buffer_block_size`: block size code, according to DPCD offset 62h
- `u8 rc_buffer_size`: number of blocks - 1, according to DPCD offset 63h

**Return**

buffer size in bytes, or 0 on invalid input

#### <a id="c-drm_dsc_pps_payload_pack"></a>`drm_dsc_pps_payload_pack()`

```c
void drm_dsc_pps_payload_pack(struct drm_dsc_picture_parameter_set *pps_payload, const struct drm_dsc_config *dsc_cfg)
```

Populates the DSC PPS

**Parameters**

- `struct drm_dsc_picture_parameter_set *pps_payload`: Bitwise struct for DSC Picture Parameter Set. This is defined
  by [`struct drm_dsc_picture_parameter_set`](#c-struct-drm_dsc_picture_parameter_set)
- `const struct drm_dsc_config *dsc_cfg`: DSC Configuration data filled by driver as defined by
  [`struct drm_dsc_config`](#c-struct-drm_dsc_config)

**Description**

DSC source device sends a picture parameter set (PPS) containing the
information required by the sink to decode the compressed frame. Driver
populates the DSC PPS struct using the DSC configuration parameters in
the order expected by the DSC Display Sink device. For the DSC, the sink
device expects the PPS payload in big endian format for fields
that span more than 1 byte.

#### <a id="c-drm_dsc_set_const_params"></a>`drm_dsc_set_const_params()`

```c
void drm_dsc_set_const_params(struct drm_dsc_config *vdsc_cfg)
```

Set DSC parameters considered typically constant across operation modes

**Parameters**

- `struct drm_dsc_config *vdsc_cfg`: DSC Configuration data partially filled by driver

#### <a id="c-drm_dsc_set_rc_buf_thresh"></a>`drm_dsc_set_rc_buf_thresh()`

```c
void drm_dsc_set_rc_buf_thresh(struct drm_dsc_config *vdsc_cfg)
```

Set thresholds for the RC model in accordance with the DSC 1.2 specification.

**Parameters**

- `struct drm_dsc_config *vdsc_cfg`: DSC Configuration data partially filled by driver

#### <a id="c-drm_dsc_setup_rc_params"></a>`drm_dsc_setup_rc_params()`

```c
int drm_dsc_setup_rc_params(struct drm_dsc_config *vdsc_cfg, enum drm_dsc_params_type type)
```

Set parameters and limits for RC model in accordance with the DSC 1.1 or 1.2 specification and DSC C Model Required bits_per_pixel and bits_per_component to be set before calling this function.

**Parameters**

- `struct drm_dsc_config *vdsc_cfg`: DSC Configuration data partially filled by driver
- `enum drm_dsc_params_type type`: operating mode and standard to follow

**Return**

0 or -error code in case of an error

#### <a id="c-drm_dsc_compute_rc_parameters"></a>`drm_dsc_compute_rc_parameters()`

```c
int drm_dsc_compute_rc_parameters(struct drm_dsc_config *vdsc_cfg)
```

Write rate control parameters to the dsc configuration defined in [`struct drm_dsc_config`](#c-struct-drm_dsc_config) in accordance with the DSC 1.2 specification. Some configuration fields must be present beforehand.

**Parameters**

- `struct drm_dsc_config *vdsc_cfg`: DSC Configuration data partially filled by driver

#### <a id="c-drm_dsc_get_bpp_int"></a>`drm_dsc_get_bpp_int()`

```c
u32 drm_dsc_get_bpp_int(const struct drm_dsc_config *vdsc_cfg)
```

Get integer bits per pixel value for the given DRM DSC config

**Parameters**

- `const struct drm_dsc_config *vdsc_cfg`: Pointer to DRM DSC config struct

**Return**

Integer BPP value

#### <a id="c-drm_dsc_initial_scale_value"></a>`drm_dsc_initial_scale_value()`

```c
u8 drm_dsc_initial_scale_value(const struct drm_dsc_config *dsc)
```

Calculate the initial scale value for the given DSC config

**Parameters**

- `const struct drm_dsc_config *dsc`: Pointer to DRM DSC config struct

**Return**

Calculated initial scale value

#### <a id="c-drm_dsc_flatness_det_thresh"></a>`drm_dsc_flatness_det_thresh()`

```c
u32 drm_dsc_flatness_det_thresh(const struct drm_dsc_config *dsc)
```

Calculate the flatness_det_thresh for the given DSC config

**Parameters**

- `const struct drm_dsc_config *dsc`: Pointer to DRM DSC config struct

**Return**

Calculated flatness det thresh value

#### <a id="c-drm_dsc_dump_config"></a>`drm_dsc_dump_config()`

```c
void drm_dsc_dump_config(struct drm_printer *p, int indent, const struct drm_dsc_config *cfg)
```

Dump the provided DSC configuration

**Parameters**

- `struct drm_printer *p`: The printer used for output
- `int indent`: Tab indentation level (max 5)
- `const struct drm_dsc_config *cfg`: DSC configuration to print

**Description**

Print the provided DSC configuration in **cfg**.


<a id="rst-output-probing-helper-functions-reference"></a>

## Output Probing Helper Functions Reference


This library provides some helper code for output probing. It provides an
implementation of the core [`drm_connector_funcs.fill_modes`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_connector_funcs) interface with
[`drm_helper_probe_single_connector_modes()`](#c-drm_helper_probe_single_connector_modes).

It also provides support for polling connectors with a work item and for
generic hotplug interrupt handling where the driver doesn't or cannot keep
track of a per-connector hpd interrupt.

This helper library can be used independently of the modeset helper library.
Drivers can also overwrite different parts e.g. use their own hotplug
handling code to avoid probing unrelated outputs.

The probe helpers share the function table structures with other display
helper libraries. See [`struct drm_connector_helper_funcs`](#c-struct-drm_connector_helper_funcs) for the details.



#### <a id="c-drm_kms_helper_poll_enable"></a>`drm_kms_helper_poll_enable()`

```c
void drm_kms_helper_poll_enable(struct drm_device *dev)
```

re-enable output polling.

**Parameters**

- `struct drm_device *dev`: drm_device

**Description**

This function re-enables the output polling work, after it has been
temporarily disabled using [`drm_kms_helper_poll_disable()`](#c-drm_kms_helper_poll_disable), for example over
suspend/resume.

Drivers can call this helper from their device resume implementation. It is
not an error to call this even when output polling isn't enabled.

If device polling was never initialized before, this call will trigger a
warning and return.

Note that calls to enable and disable polling must be strictly ordered, which
is automatically the case when they're only call from suspend/resume
callbacks.

#### <a id="c-drm_kms_helper_poll_reschedule"></a>`drm_kms_helper_poll_reschedule()`

```c
void drm_kms_helper_poll_reschedule(struct drm_device *dev)
```

reschedule the output polling work

**Parameters**

- `struct drm_device *dev`: drm_device

**Description**

This function reschedules the output polling work, after polling for a
connector has been enabled.

Drivers must call this helper after enabling polling for a connector by
setting `DRM_CONNECTOR_POLL_CONNECT` / `DRM_CONNECTOR_POLL_DISCONNECT` flags
in drm_connector::polled. Note that after disabling polling by clearing these
flags for a connector will stop the output polling work automatically if
the polling is disabled for all other connectors as well.

The function can be called only after polling has been enabled by calling
[`drm_kms_helper_poll_init()`](#c-drm_kms_helper_poll_init) / [`drm_kms_helper_poll_enable()`](#c-drm_kms_helper_poll_enable).

#### <a id="c-drm_helper_probe_detect"></a>`drm_helper_probe_detect()`

```c
int drm_helper_probe_detect(struct drm_connector *connector, struct drm_modeset_acquire_ctx *ctx, bool force)
```

probe connector status

**Parameters**

- `struct drm_connector *connector`: connector to probe
- `struct drm_modeset_acquire_ctx *ctx`: acquire_ctx, or NULL to let this function handle locking.
- `bool force`: Whether destructive probe operations should be performed.

**Description**

This function calls the detect callbacks of the connector.
This function returns [`drm_connector_status`](/kernel/hardware/gpu/drm-kms.md#c-enum-drm_connector_status), or
if **ctx** is set, it might also return -EDEADLK.

#### <a id="c-drm_helper_probe_single_connector_modes"></a>`drm_helper_probe_single_connector_modes()`

```c
int drm_helper_probe_single_connector_modes(struct drm_connector *connector, uint32_t maxX, uint32_t maxY)
```

get complete set of display modes

**Parameters**

- `struct drm_connector *connector`: connector to probe
- `uint32_t maxX`: max width for modes
- `uint32_t maxY`: max height for modes

**Description**

Based on the helper callbacks implemented by **connector** in struct
[`drm_connector_helper_funcs`](#c-struct-drm_connector_helper_funcs) try to detect all valid modes.  Modes will first
be added to the connector's probed_modes list, then culled (based on validity
and the **maxX**, **maxY** parameters) and put into the normal modes list.

Intended to be used as a generic implementation of the
[`drm_connector_funcs.fill_modes()`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_connector_funcs) vfunc for drivers that use the CRTC helpers
for output mode filtering and detection.

The basic procedure is as follows

1. All modes currently on the connector's modes list are marked as stale

2. New modes are added to the connector's probed_modes list with
   [`drm_mode_probed_add()`](/kernel/hardware/gpu/drm-kms.md#c-drm_mode_probed_add). New modes start their life with status as OK.
   Modes are added from a single source using the following priority order.

   - [`drm_connector_helper_funcs.get_modes`](#c-struct-drm_connector_helper_funcs) vfunc
   - if the connector status is connector_status_connected, standard
     VESA DMT modes up to 1024x768 are automatically added
     ([`drm_add_modes_noedid()`](#c-drm_add_modes_noedid))

   Finally modes specified via the kernel command line (video=...) are
   added in addition to what the earlier probes produced
   (`drm_helper_probe_add_cmdline_mode()`). These modes are generated
   using the VESA GTF/CVT formulas.

3. Modes are moved from the probed_modes list to the modes list. Potential
   duplicates are merged together (see [`drm_connector_list_update()`](/kernel/hardware/gpu/drm-kms.md#c-drm_connector_list_update)).
   After this step the probed_modes list will be empty again.

4. Any non-stale mode on the modes list then undergoes validation

   - `drm_mode_validate_basic()` performs basic sanity checks
   - [`drm_mode_validate_size()`](/kernel/hardware/gpu/drm-kms.md#c-drm_mode_validate_size) filters out modes larger than **maxX** and **maxY**
     (if specified)
   - `drm_mode_validate_flag()` checks the modes against basic connector
     capabilities (interlace_allowed,doublescan_allowed,stereo_allowed)
   - the optional [`drm_connector_helper_funcs.mode_valid`](#c-struct-drm_connector_helper_funcs) or
     [`drm_connector_helper_funcs.mode_valid_ctx`](#c-struct-drm_connector_helper_funcs) helpers can perform driver
     and/or sink specific checks
   - the optional [`drm_crtc_helper_funcs.mode_valid`](#c-struct-drm_crtc_helper_funcs),
     [`drm_bridge_funcs.mode_valid`](#c-struct-drm_bridge_funcs) and [`drm_encoder_helper_funcs.mode_valid`](#c-struct-drm_encoder_helper_funcs)
     helpers can perform driver and/or source specific checks which are also
     enforced by the modeset/atomic helpers

5. Any mode whose status is not OK is pruned from the connector's modes list,
   accompanied by a debug message indicating the reason for the mode's
   rejection (see [`drm_mode_prune_invalid()`](/kernel/hardware/gpu/drm-kms.md#c-drm_mode_prune_invalid)).

**Return**

The number of modes found on **connector**.

#### <a id="c-drm_kms_helper_hotplug_event"></a>`drm_kms_helper_hotplug_event()`

```c
void drm_kms_helper_hotplug_event(struct drm_device *dev)
```

fire off KMS hotplug events

**Parameters**

- `struct drm_device *dev`: drm_device whose connector state changed

**Description**

This function fires off the uevent for userspace and also calls the
client hotplug function, which is most commonly used to inform the fbdev
emulation code and allow it to update the fbcon output configuration.

Drivers should call this from their hotplug handling code when a change is
detected. Note that this function does not do any output detection of its
own, like [`drm_helper_hpd_irq_event()`](#c-drm_helper_hpd_irq_event) does - this is assumed to be done by the
driver already.

This function must be called from process context with no mode
setting locks held.

If only a single connector has changed, consider calling
[`drm_kms_helper_connector_hotplug_event()`](#c-drm_kms_helper_connector_hotplug_event) instead.

#### <a id="c-drm_kms_helper_connector_hotplug_event"></a>`drm_kms_helper_connector_hotplug_event()`

```c
void drm_kms_helper_connector_hotplug_event(struct drm_connector *connector)
```

fire off a KMS connector hotplug event

**Parameters**

- `struct drm_connector *connector`: drm_connector which has changed

**Description**

This is the same as [`drm_kms_helper_hotplug_event()`](#c-drm_kms_helper_hotplug_event), except it fires a more
fine-grained uevent for a single connector.

#### <a id="c-drm_kms_helper_is_poll_worker"></a>`drm_kms_helper_is_poll_worker()`

```c
bool drm_kms_helper_is_poll_worker(void)
```

is `current` task an output poll worker?

**Parameters**

- `void`: no arguments

**Description**

Determine if `current` task is an output poll worker.  This can be used
to select distinct code paths for output polling versus other contexts.

One use case is to avoid a deadlock between the output poll worker and
the autosuspend worker wherein the latter waits for polling to finish
upon calling [`drm_kms_helper_poll_disable()`](#c-drm_kms_helper_poll_disable), while the former waits for
runtime suspend to finish upon calling `pm_runtime_get_sync()` in a
connector ->detect hook.

#### <a id="c-drm_kms_helper_poll_disable"></a>`drm_kms_helper_poll_disable()`

```c
void drm_kms_helper_poll_disable(struct drm_device *dev)
```

disable output polling

**Parameters**

- `struct drm_device *dev`: drm_device

**Description**

This function disables the output polling work.

Drivers can call this helper from their device suspend implementation. It is
not an error to call this even when output polling isn't enabled or already
disabled. Polling is re-enabled by calling [`drm_kms_helper_poll_enable()`](#c-drm_kms_helper_poll_enable).

If however, the polling was never initialized, this call will trigger a
warning and return.

Note that calls to enable and disable polling must be strictly ordered, which
is automatically the case when they're only call from suspend/resume
callbacks.

#### <a id="c-drm_kms_helper_poll_init"></a>`drm_kms_helper_poll_init()`

```c
void drm_kms_helper_poll_init(struct drm_device *dev)
```

initialize and enable output polling

**Parameters**

- `struct drm_device *dev`: drm_device

**Description**

This function initializes and then also enables output polling support for
**dev**. Drivers which do not have reliable hotplug support in hardware can use
this helper infrastructure to regularly poll such connectors for changes in
their connection state.

Drivers can control which connectors are polled by setting the
DRM_CONNECTOR_POLL_CONNECT and DRM_CONNECTOR_POLL_DISCONNECT flags. On
connectors where probing live outputs can result in visual distortion drivers
should not set the DRM_CONNECTOR_POLL_DISCONNECT flag to avoid this.
Connectors which have no flag or only DRM_CONNECTOR_POLL_HPD set are
completely ignored by the polling logic.

Note that a connector can be both polled and probed from the hotplug handler,
in case the hotplug interrupt is known to be unreliable.

#### <a id="c-drm_kms_helper_poll_fini"></a>`drm_kms_helper_poll_fini()`

```c
void drm_kms_helper_poll_fini(struct drm_device *dev)
```

disable output polling and clean it up

**Parameters**

- `struct drm_device *dev`: drm_device

#### <a id="c-drmm_kms_helper_poll_init"></a>`drmm_kms_helper_poll_init()`

```c
void drmm_kms_helper_poll_init(struct drm_device *dev)
```

initialize and enable output polling

**Parameters**

- `struct drm_device *dev`: drm_device

**Description**

This function initializes and then also enables output polling support for
**dev** similar to [`drm_kms_helper_poll_init()`](#c-drm_kms_helper_poll_init). Polling will automatically be
cleaned up when the DRM device goes away.

See [`drm_kms_helper_poll_init()`](#c-drm_kms_helper_poll_init) for more information.

#### <a id="c-drm_connector_helper_hpd_irq_event"></a>`drm_connector_helper_hpd_irq_event()`

```c
bool drm_connector_helper_hpd_irq_event(struct drm_connector *connector)
```

hotplug processing

**Parameters**

- `struct drm_connector *connector`: drm_connector

**Description**

Drivers can use this helper function to run a detect cycle on a connector
which has the DRM_CONNECTOR_POLL_HPD flag set in its `polled` member.

This helper function is useful for drivers which can track hotplug
interrupts for a single connector. Drivers that want to send a
hotplug event for all connectors or can't track hotplug interrupts
per connector need to use [`drm_helper_hpd_irq_event()`](#c-drm_helper_hpd_irq_event).

This function must be called from process context with no mode
setting locks held.

Note that a connector can be both polled and probed from the hotplug
handler, in case the hotplug interrupt is known to be unreliable.

**Return**

A boolean indicating whether the connector status changed or not

#### <a id="c-drm_helper_hpd_irq_event"></a>`drm_helper_hpd_irq_event()`

```c
bool drm_helper_hpd_irq_event(struct drm_device *dev)
```

hotplug processing

**Parameters**

- `struct drm_device *dev`: drm_device

**Description**

Drivers can use this helper function to run a detect cycle on all connectors
which have the DRM_CONNECTOR_POLL_HPD flag set in their `polled` member. All
other connectors are ignored, which is useful to avoid reprobing fixed
panels.

This helper function is useful for drivers which can't or don't track hotplug
interrupts for each connector.

Drivers which support hotplug interrupts for each connector individually and
which have a more fine-grained detect logic can use
[`drm_connector_helper_hpd_irq_event()`](#c-drm_connector_helper_hpd_irq_event). Alternatively, they should bypass this
code and directly call [`drm_kms_helper_hotplug_event()`](#c-drm_kms_helper_hotplug_event) in case the connector
state changed.

This function must be called from process context with no mode
setting locks held.

Note that a connector can be both polled and probed from the hotplug handler,
in case the hotplug interrupt is known to be unreliable.

**Return**

A boolean indicating whether the connector status changed or not

#### <a id="c-drm_crtc_helper_mode_valid_fixed"></a>`drm_crtc_helper_mode_valid_fixed()`

```c
enum drm_mode_status drm_crtc_helper_mode_valid_fixed(struct drm_crtc *crtc, const struct drm_display_mode *mode, const struct drm_display_mode *fixed_mode)
```

Validates a display mode

**Parameters**

- `struct drm_crtc *crtc`: the crtc
- `const struct drm_display_mode *mode`: the mode to validate
- `const struct drm_display_mode *fixed_mode`: the display hardware's mode

**Return**

MODE_OK on success, or another mode-status code otherwise.

#### <a id="c-drm_connector_helper_get_modes_fixed"></a>`drm_connector_helper_get_modes_fixed()`

```c
int drm_connector_helper_get_modes_fixed(struct drm_connector *connector, const struct drm_display_mode *fixed_mode)
```

Duplicates a display mode for a connector

**Parameters**

- `struct drm_connector *connector`: the connector
- `const struct drm_display_mode *fixed_mode`: the display hardware's mode

**Description**

This function duplicates a display modes for a connector. Drivers for hardware
that only supports a single fixed mode can use this function in their connector's
get_modes helper.

**Return**

The number of created modes.

#### <a id="c-drm_connector_helper_get_modes"></a>`drm_connector_helper_get_modes()`

```c
int drm_connector_helper_get_modes(struct drm_connector *connector)
```

Read EDID and update connector.

**Parameters**

- `struct drm_connector *connector`: The connector

**Description**

Read the EDID using [`drm_edid_read()`](#c-drm_edid_read) (which requires that connector->ddc is
set), and update the connector using the EDID.

This can be used as the "default" connector helper .`get_modes()` hook if the
driver does not need any special processing. This is sets the example what
custom .`get_modes()` hooks should do regarding EDID read and connector update.

**Return**

Number of modes.

#### <a id="c-drm_connector_helper_tv_get_modes"></a>`drm_connector_helper_tv_get_modes()`

```c
int drm_connector_helper_tv_get_modes(struct drm_connector *connector)
```

Fills the modes availables to a TV connector

**Parameters**

- `struct drm_connector *connector`: The connector

**Description**

Fills the available modes for a TV connector based on the supported
TV modes, and the default mode expressed by the kernel command line.

This can be used as the default TV connector helper .`get_modes()` hook
if the driver does not need any special processing.

**Return**

The number of modes added to the connector.

#### <a id="c-drm_connector_helper_detect_from_ddc"></a>`drm_connector_helper_detect_from_ddc()`

```c
int drm_connector_helper_detect_from_ddc(struct drm_connector *connector, struct drm_modeset_acquire_ctx *ctx, bool force)
```

Read EDID and detect connector status.

**Parameters**

- `struct drm_connector *connector`: The connector
- `struct drm_modeset_acquire_ctx *ctx`: Acquire context
- `bool force`: Perform screen-destructive operations, if necessary

**Description**

Detects the connector status by reading the EDID using [`drm_probe_ddc()`](#c-drm_probe_ddc),
which requires connector->ddc to be set. Returns connector_status_connected
on success or connector_status_disconnected on failure.

**Return**

The connector status as defined by enum drm_connector_status.


<a id="rst-edid-helper-functions-reference"></a>

## EDID Helper Functions Reference


#### <a id="c-drm_edid_decode_mfg_id"></a>`drm_edid_decode_mfg_id()`

```c
const char * drm_edid_decode_mfg_id(u16 mfg_id, char vend[4])
```

Decode the manufacturer ID

**Parameters**

- `u16 mfg_id`: The manufacturer ID
- `char vend[4]`: A 4-byte buffer to store the 3-letter vendor string plus a '\0'
  termination

#### <a id="c-drm_edid_encode_panel_id"></a>`drm_edid_encode_panel_id()`

```c
drm_edid_encode_panel_id(vend_chr_0, vend_chr_1, vend_chr_2, product_id)
```

Encode an ID for matching against [`drm_edid_get_panel_id()`](#c-drm_edid_get_panel_id)

**Parameters**

- `vend_chr_0`: First character of the vendor string.
- `vend_chr_1`: Second character of the vendor string.
- `vend_chr_2`: Third character of the vendor string.
- `product_id`: The 16-bit product ID.

**Description**

This is a macro so that it can be calculated at compile time and used
as an initializer.

- For instance:
  drm_edid_encode_panel_id('B', 'O', 'E', 0x2d08) => 0x09e52d08

**Return**

a 32-bit ID per panel.

#### <a id="c-drm_edid_decode_panel_id"></a>`drm_edid_decode_panel_id()`

```c
void drm_edid_decode_panel_id(u32 panel_id, char vend[4], u16 *product_id)
```

Decode a panel ID from [`drm_edid_encode_panel_id()`](#c-drm_edid_encode_panel_id)

**Parameters**

- `u32 panel_id`: The panel ID to decode.
- `char vend[4]`: A 4-byte buffer to store the 3-letter vendor string plus a '\0'
  termination
- `u16 *product_id`: The product ID will be returned here.

**Description**

- For instance, after:
  drm_edid_decode_panel_id(0x09e52d08, vend, `product_id`)
- These will be true:
  vend\[0\] = 'B'
  vend\[1\] = 'O'
  vend\[2\] = 'E'
  vend\[3\] = '\0'
  product_id = 0x2d08



#### <a id="c-drm_edid_header_is_valid"></a>`drm_edid_header_is_valid()`

```c
int drm_edid_header_is_valid(const void *_edid)
```

sanity check the header of the base EDID block

**Parameters**

- `const void *_edid`: pointer to raw base EDID block

**Description**

Sanity check the header of the base EDID block.

**Return**

8 if the header is perfect, down to 0 if it's totally wrong.

#### <a id="c-drm_edid_is_valid"></a>`drm_edid_is_valid()`

```c
bool drm_edid_is_valid(struct edid *edid)
```

sanity check EDID data

**Parameters**

- `struct edid *edid`: EDID data

**Description**

Sanity-check an entire EDID record (including extensions)

**Return**

True if the EDID data is valid, false otherwise.

#### <a id="c-drm_edid_valid"></a>`drm_edid_valid()`

```c
bool drm_edid_valid(const struct drm_edid *drm_edid)
```

sanity check EDID data

**Parameters**

- `const struct drm_edid *drm_edid`: EDID data

**Description**

Sanity check an EDID. Cross check block count against allocated size and
checksum the blocks.

**Return**

True if the EDID data is valid, false otherwise.

#### <a id="c-drm_edid_override_connector_update"></a>`drm_edid_override_connector_update()`

```c
int drm_edid_override_connector_update(struct drm_connector *connector)
```

add modes from override/firmware EDID

**Parameters**

- `struct drm_connector *connector`: connector we're probing

**Description**

Add modes from the override/firmware EDID, if available. Only to be used from
[`drm_helper_probe_single_connector_modes()`](#c-drm_helper_probe_single_connector_modes) as a fallback for when DDC probe
failed during [`drm_get_edid()`](#c-drm_get_edid) and caused the override/firmware EDID to be
skipped.

**Return**

The number of modes added or 0 if we couldn't find any.

#### <a id="c-drm_edid_raw"></a>`drm_edid_raw()`

```c
const struct edid * drm_edid_raw(const struct drm_edid *drm_edid)
```

Get a pointer to the raw EDID data.

**Parameters**

- `const struct drm_edid *drm_edid`: drm_edid container

**Description**

Get a pointer to the raw EDID data.

This is for transition only. Avoid using this like the plague.

**Return**

Pointer to raw EDID data.

#### <a id="c-drm_edid_alloc"></a>`drm_edid_alloc()`

```c
const struct drm_edid * drm_edid_alloc(const void *edid, size_t size)
```

Allocate a new drm_edid container

**Parameters**

- `const void *edid`: Pointer to raw EDID data
- `size_t size`: Size of memory allocated for EDID

**Description**

Allocate a new drm_edid container. Do not calculate edid size from edid, pass
the actual size that has been allocated for the data. There is no validation
of the raw EDID data against the size, but at least the EDID base block must
fit in the buffer.

The returned pointer must be freed using [`drm_edid_free()`](#c-drm_edid_free).

**Return**

drm_edid container, or NULL on errors

#### <a id="c-drm_edid_dup"></a>`drm_edid_dup()`

```c
const struct drm_edid * drm_edid_dup(const struct drm_edid *drm_edid)
```

Duplicate a drm_edid container

**Parameters**

- `const struct drm_edid *drm_edid`: EDID to duplicate

**Description**

The returned pointer must be freed using [`drm_edid_free()`](#c-drm_edid_free).

**Return**

drm_edid container copy, or NULL on errors

#### <a id="c-drm_edid_free"></a>`drm_edid_free()`

```c
void drm_edid_free(const struct drm_edid *drm_edid)
```

Free the drm_edid container

**Parameters**

- `const struct drm_edid *drm_edid`: EDID to free

#### <a id="c-drm_probe_ddc"></a>`drm_probe_ddc()`

```c
bool drm_probe_ddc(struct i2c_adapter *adapter)
```

probe DDC presence

**Parameters**

- `struct i2c_adapter *adapter`: I2C adapter to probe

**Return**

True on success, false on failure.

#### <a id="c-drm_get_edid"></a>`drm_get_edid()`

```c
struct edid * drm_get_edid(struct drm_connector *connector, struct i2c_adapter *adapter)
```

get EDID data, if available

**Parameters**

- `struct drm_connector *connector`: connector we're probing
- `struct i2c_adapter *adapter`: I2C adapter to use for DDC

**Description**

Poke the given I2C channel to grab EDID data if possible.  If found,
attach it to the connector.

**Return**

Pointer to valid EDID or NULL if we couldn't find any.

#### <a id="c-drm_edid_read_custom"></a>`drm_edid_read_custom()`

```c
const struct drm_edid * drm_edid_read_custom(struct drm_connector *connector, read_block_fn read_block, void *context)
```

Read EDID data using given EDID block read function

**Parameters**

- `struct drm_connector *connector`: Connector to use
- `read_block_fn read_block`: EDID block read function
- `void *context`: Private data passed to the block read function

**Description**

When the I2C adapter connected to the DDC bus is hidden behind a device that
exposes a different interface to read EDID blocks this function can be used
to get EDID data using a custom block read function.

As in the general case the DDC bus is accessible by the kernel at the I2C
level, drivers must make all reasonable efforts to expose it as an I2C
adapter and use [`drm_edid_read()`](#c-drm_edid_read) or [`drm_edid_read_ddc()`](#c-drm_edid_read_ddc) instead of abusing
this function.

The EDID may be overridden using debugfs override_edid or firmware EDID
(`drm_edid_load_firmware()` and drm.edid_firmware parameter), in this priority
order. Having either of them bypasses actual EDID reads.

The returned pointer must be freed using [`drm_edid_free()`](#c-drm_edid_free).

**Return**

Pointer to EDID, or NULL if probe/read failed.

#### <a id="c-drm_edid_read_ddc"></a>`drm_edid_read_ddc()`

```c
const struct drm_edid * drm_edid_read_ddc(struct drm_connector *connector, struct i2c_adapter *adapter)
```

Read EDID data using given I2C adapter

**Parameters**

- `struct drm_connector *connector`: Connector to use
- `struct i2c_adapter *adapter`: I2C adapter to use for DDC

**Description**

Read EDID using the given I2C adapter.

The EDID may be overridden using debugfs override_edid or firmware EDID
(`drm_edid_load_firmware()` and drm.edid_firmware parameter), in this priority
order. Having either of them bypasses actual EDID reads.

Prefer initializing connector->ddc with [`drm_connector_init_with_ddc()`](/kernel/hardware/gpu/drm-kms.md#c-drm_connector_init_with_ddc) and
using [`drm_edid_read()`](#c-drm_edid_read) instead of this function.

The returned pointer must be freed using [`drm_edid_free()`](#c-drm_edid_free).

**Return**

Pointer to EDID, or NULL if probe/read failed.

#### <a id="c-drm_edid_read"></a>`drm_edid_read()`

```c
const struct drm_edid * drm_edid_read(struct drm_connector *connector)
```

Read EDID data using connector's I2C adapter

**Parameters**

- `struct drm_connector *connector`: Connector to use

**Description**

Read EDID using the connector's I2C adapter.

The EDID may be overridden using debugfs override_edid or firmware EDID
(`drm_edid_load_firmware()` and drm.edid_firmware parameter), in this priority
order. Having either of them bypasses actual EDID reads.

The returned pointer must be freed using [`drm_edid_free()`](#c-drm_edid_free).

**Return**

Pointer to EDID, or NULL if probe/read failed.

#### <a id="c-drm_edid_get_product_id"></a>`drm_edid_get_product_id()`

```c
void drm_edid_get_product_id(const struct drm_edid *drm_edid, struct drm_edid_product_id *id)
```

Get the vendor and product identification

**Parameters**

- `const struct drm_edid *drm_edid`: EDID
- `struct drm_edid_product_id *id`: Where to place the product id

#### <a id="c-drm_edid_print_product_id"></a>`drm_edid_print_product_id()`

```c
void drm_edid_print_product_id(struct drm_printer *p, const struct drm_edid_product_id *id, bool raw)
```

Print decoded product id to printer

**Parameters**

- `struct drm_printer *p`: drm printer
- `const struct drm_edid_product_id *id`: EDID product id
- `bool raw`: If true, also print the raw hex

**Description**

See VESA E-EDID 1.4 section 3.4.

#### <a id="c-drm_edid_get_panel_id"></a>`drm_edid_get_panel_id()`

```c
u32 drm_edid_get_panel_id(const struct drm_edid *drm_edid)
```

Get a panel's ID from EDID

**Parameters**

- `const struct drm_edid *drm_edid`: EDID that contains panel ID.

**Description**

This function uses the first block of the EDID of a panel and (assuming
that the EDID is valid) extracts the ID out of it. The ID is a 32-bit value
(16 bits of manufacturer ID and 16 bits of per-manufacturer ID) that's
supposed to be different for each different modem of panel.

**Return**

A 32-bit ID that should be different for each make/model of panel.
See the functions [`drm_edid_encode_panel_id()`](#c-drm_edid_encode_panel_id) and
[`drm_edid_decode_panel_id()`](#c-drm_edid_decode_panel_id) for some details on the structure of this
ID. Return 0 if the EDID size is less than a base block.

#### <a id="c-drm_edid_read_base_block"></a>`drm_edid_read_base_block()`

```c
const struct drm_edid * drm_edid_read_base_block(struct i2c_adapter *adapter)
```

Get a panel's EDID base block

**Parameters**

- `struct i2c_adapter *adapter`: I2C adapter to use for DDC

**Description**

This function returns the drm_edid containing the first block of the EDID of
a panel.

This function is intended to be used during early probing on devices where
more than one panel might be present. Because of its intended use it must
assume that the EDID of the panel is correct, at least as far as the base
block is concerned (in other words, we don't process any overrides here).

Caller should call [`drm_edid_free()`](#c-drm_edid_free) after use.

**NOTE**

it's expected that this function and `drm_do_get_edid()` will both
be read the EDID, but there is no caching between them. Since we're only
reading the first block, hopefully this extra overhead won't be too big.

WARNING: Only use this function when the connector is unknown. For example,
during the early probe of panel. The EDID read from the function is temporary
and should be replaced by the full EDID returned from other drm_edid_read.

**Return**

Pointer to allocated EDID base block, or NULL on any failure.

#### <a id="c-drm_get_edid_switcheroo"></a>`drm_get_edid_switcheroo()`

```c
struct edid * drm_get_edid_switcheroo(struct drm_connector *connector, struct i2c_adapter *adapter)
```

get EDID data for a vga_switcheroo output

**Parameters**

- `struct drm_connector *connector`: connector we're probing
- `struct i2c_adapter *adapter`: I2C adapter to use for DDC

**Description**

Wrapper around [`drm_get_edid()`](#c-drm_get_edid) for laptops with dual GPUs using one set of
outputs. The wrapper adds the requisite vga_switcheroo calls to temporarily
switch DDC to the GPU which is retrieving EDID.

**Return**

Pointer to valid EDID or `NULL` if we couldn't find any.

#### <a id="c-drm_edid_read_switcheroo"></a>`drm_edid_read_switcheroo()`

```c
const struct drm_edid * drm_edid_read_switcheroo(struct drm_connector *connector, struct i2c_adapter *adapter)
```

get EDID data for a vga_switcheroo output

**Parameters**

- `struct drm_connector *connector`: connector we're probing
- `struct i2c_adapter *adapter`: I2C adapter to use for DDC

**Description**

Wrapper around [`drm_edid_read_ddc()`](#c-drm_edid_read_ddc) for laptops with dual GPUs using one set
of outputs. The wrapper adds the requisite vga_switcheroo calls to
temporarily switch DDC to the GPU which is retrieving EDID.

**Return**

Pointer to valid EDID or `NULL` if we couldn't find any.

#### <a id="c-drm_edid_duplicate"></a>`drm_edid_duplicate()`

```c
struct edid * drm_edid_duplicate(const struct edid *edid)
```

duplicate an EDID and the extensions

**Parameters**

- `const struct edid *edid`: EDID to duplicate

**Return**

Pointer to duplicated EDID or NULL on allocation failure.

#### <a id="c-drm_match_cea_mode"></a>`drm_match_cea_mode()`

```c
u8 drm_match_cea_mode(const struct drm_display_mode *to_match)
```

look for a CEA mode matching given mode

**Parameters**

- `const struct drm_display_mode *to_match`: display mode

**Return**

The CEA Video ID (VIC) of the mode or 0 if it isn't a CEA-861
mode.

#### <a id="c-drm_display_mode_from_cea_vic"></a>`drm_display_mode_from_cea_vic()`

```c
struct drm_display_mode * drm_display_mode_from_cea_vic(struct drm_device *dev, u8 video_code)
```

return a mode for CEA VIC

**Parameters**

- `struct drm_device *dev`: DRM device
- `u8 video_code`: CEA VIC of the mode

**Description**

Creates a new mode matching the specified CEA VIC.

**Return**

A new drm_display_mode on success or NULL on failure

#### <a id="c-drm_edid_match"></a>`drm_edid_match()`

```c
bool drm_edid_match(const struct drm_edid *drm_edid, const struct drm_edid_ident *ident)
```

match drm_edid with given identity

**Parameters**

- `const struct drm_edid *drm_edid`: EDID
- `const struct drm_edid_ident *ident`: the EDID identity to match with

**Description**

Check if the EDID matches with the given identity.

**Return**

True if the given identity matched with EDID, false otherwise.

#### <a id="c-drm_edid_get_monitor_name"></a>`drm_edid_get_monitor_name()`

```c
void drm_edid_get_monitor_name(const struct edid *edid, char *name, int bufsize)
```

fetch the monitor name from the edid

**Parameters**

- `const struct edid *edid`: monitor EDID information
- `char *name`: pointer to a character array to hold the name of the monitor
- `int bufsize`: The size of the name buffer (should be at least 14 chars.)

#### <a id="c-drm_edid_to_sad"></a>`drm_edid_to_sad()`

```c
int drm_edid_to_sad(const struct edid *edid, struct cea_sad **sads)
```

extracts SADs from EDID

**Parameters**

- `const struct edid *edid`: EDID to parse
- `struct cea_sad **sads`: pointer that will be set to the extracted SADs

**Description**

Looks for CEA EDID block and extracts SADs (Short Audio Descriptors) from it.

**Note**

The returned pointer needs to be freed using [`kfree()`](/kernel/internals/core-api/mm-api.md#c-kfree).

**Return**

The number of found SADs or negative number on error.

#### <a id="c-drm_edid_to_speaker_allocation"></a>`drm_edid_to_speaker_allocation()`

```c
int drm_edid_to_speaker_allocation(const struct edid *edid, u8 **sadb)
```

extracts Speaker Allocation Data Blocks from EDID

**Parameters**

- `const struct edid *edid`: EDID to parse
- `u8 **sadb`: pointer to the speaker block

**Description**

Looks for CEA EDID block and extracts the Speaker Allocation Data Block from it.

**Note**

The returned pointer needs to be freed using [`kfree()`](/kernel/internals/core-api/mm-api.md#c-kfree).

**Return**

The number of found Speaker Allocation Blocks or negative number on
error.

#### <a id="c-drm_av_sync_delay"></a>`drm_av_sync_delay()`

```c
int drm_av_sync_delay(struct drm_connector *connector, const struct drm_display_mode *mode)
```

compute the HDMI/DP sink audio-video sync delay

**Parameters**

- `struct drm_connector *connector`: connector associated with the HDMI/DP sink
- `const struct drm_display_mode *mode`: the display mode

**Return**

The HDMI/DP sink's audio-video sync delay in milliseconds or 0 if
the sink doesn't support audio or video.

#### <a id="c-drm_detect_hdmi_monitor"></a>`drm_detect_hdmi_monitor()`

```c
bool drm_detect_hdmi_monitor(const struct edid *edid)
```

detect whether monitor is HDMI

**Parameters**

- `const struct edid *edid`: monitor EDID information

**Description**

Parse the CEA extension according to CEA-861-B.

Drivers that have added the modes parsed from EDID to drm_display_info
should use [`drm_display_info.is_hdmi`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_display_info) instead of calling this function.

**Return**

True if the monitor is HDMI, false if not or unknown.

#### <a id="c-drm_detect_monitor_audio"></a>`drm_detect_monitor_audio()`

```c
bool drm_detect_monitor_audio(const struct edid *edid)
```

check monitor audio capability

**Parameters**

- `const struct edid *edid`: EDID block to scan

**Description**

Monitor should have CEA extension block.
If monitor has 'basic audio', but no CEA audio blocks, it's 'basic
audio' only. If there is any audio extension block and supported
audio format, assume at least 'basic audio' support, even if 'basic
audio' is not defined in EDID.

**Return**

True if the monitor supports audio, false otherwise.

#### <a id="c-drm_default_rgb_quant_range"></a>`drm_default_rgb_quant_range()`

```c
enum hdmi_quantization_range drm_default_rgb_quant_range(const struct drm_display_mode *mode)
```

default RGB quantization range

**Parameters**

- `const struct drm_display_mode *mode`: display mode

**Description**

Determine the default RGB quantization range for the mode,
as specified in CEA-861.

**Return**

The default RGB quantization range for the mode

#### <a id="c-drm_edid_connector_update"></a>`drm_edid_connector_update()`

```c
int drm_edid_connector_update(struct drm_connector *connector, const struct drm_edid *drm_edid)
```

Update connector information from EDID

**Parameters**

- `struct drm_connector *connector`: Connector
- `const struct drm_edid *drm_edid`: EDID

**Description**

Update the connector display info, ELD, HDR metadata, relevant properties,
etc. from the passed in EDID.

If EDID is NULL, reset the information.

Must be called before calling [`drm_edid_connector_add_modes()`](#c-drm_edid_connector_add_modes).

**Return**

0 on success, negative error on errors.

#### <a id="c-drm_edid_connector_add_modes"></a>`drm_edid_connector_add_modes()`

```c
int drm_edid_connector_add_modes(struct drm_connector *connector)
```

Update probed modes from the EDID property

**Parameters**

- `struct drm_connector *connector`: Connector

**Description**

Add the modes from the previously updated EDID property to the connector
probed modes list.

[`drm_edid_connector_update()`](#c-drm_edid_connector_update) must have been called before this to update the
EDID property.

**Return**

The number of modes added, or 0 if we couldn't find any.

#### <a id="c-drm_connector_update_edid_property"></a>`drm_connector_update_edid_property()`

```c
int drm_connector_update_edid_property(struct drm_connector *connector, const struct edid *edid)
```

update the edid property of a connector

**Parameters**

- `struct drm_connector *connector`: drm connector
- `const struct edid *edid`: new value of the edid property

**Description**

This function creates a new blob modeset object and assigns its id to the
connector's edid property.
Since we also parse tile information from EDID's displayID block, we also
set the connector's tile property here. See [`drm_connector_set_tile_property()`](/kernel/hardware/gpu/drm-kms.md#c-drm_connector_set_tile_property)
for more details.

This function is deprecated. Use [`drm_edid_connector_update()`](#c-drm_edid_connector_update) instead.

**Return**

Zero on success, negative errno on failure.

#### <a id="c-drm_add_edid_modes"></a>`drm_add_edid_modes()`

```c
int drm_add_edid_modes(struct drm_connector *connector, struct edid *edid)
```

add modes from EDID data, if available

**Parameters**

- `struct drm_connector *connector`: connector we're probing
- `struct edid *edid`: EDID data

**Description**

Add the specified modes to the connector's mode list. Also fills out the
[`drm_display_info`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_display_info) structure and ELD in **connector** with any information which
can be derived from the edid.

This function is deprecated. Use [`drm_edid_connector_add_modes()`](#c-drm_edid_connector_add_modes) instead.

**Return**

The number of modes added or 0 if we couldn't find any.

#### <a id="c-drm_add_modes_noedid"></a>`drm_add_modes_noedid()`

```c
int drm_add_modes_noedid(struct drm_connector *connector, unsigned int hdisplay, unsigned int vdisplay)
```

add modes for the connectors without EDID

**Parameters**

- `struct drm_connector *connector`: connector we're probing
- `unsigned int hdisplay`: the horizontal display limit
- `unsigned int vdisplay`: the vertical display limit

**Description**

Add the specified modes to the connector's mode list. Only when the
hdisplay/vdisplay is not beyond the given limit, it will be added.

**Return**

The number of modes added or 0 if we couldn't find any.

#### <a id="c-drm_hdmi_avi_infoframe_from_display_mode"></a>`drm_hdmi_avi_infoframe_from_display_mode()`

```c
int drm_hdmi_avi_infoframe_from_display_mode(struct hdmi_avi_infoframe *frame, const struct drm_connector *connector, const struct drm_display_mode *mode)
```

fill an HDMI AVI infoframe with data from a DRM display mode

**Parameters**

- `struct hdmi_avi_infoframe *frame`: HDMI AVI infoframe
- `const struct drm_connector *connector`: the connector
- `const struct drm_display_mode *mode`: DRM display mode

**Return**

0 on success or a negative error code on failure.

#### <a id="c-drm_hdmi_avi_infoframe_quant_range"></a>`drm_hdmi_avi_infoframe_quant_range()`

```c
void drm_hdmi_avi_infoframe_quant_range(struct hdmi_avi_infoframe *frame, const struct drm_connector *connector, const struct drm_display_mode *mode, enum hdmi_quantization_range rgb_quant_range)
```

fill the HDMI AVI infoframe quantization range information

**Parameters**

- `struct hdmi_avi_infoframe *frame`: HDMI AVI infoframe
- `const struct drm_connector *connector`: the connector
- `const struct drm_display_mode *mode`: DRM display mode
- `enum hdmi_quantization_range rgb_quant_range`: RGB quantization range (Q)

#### <a id="c-drm_hdmi_vendor_infoframe_from_display_mode"></a>`drm_hdmi_vendor_infoframe_from_display_mode()`

```c
int drm_hdmi_vendor_infoframe_from_display_mode(struct hdmi_vendor_infoframe *frame, const struct drm_connector *connector, const struct drm_display_mode *mode)
```

fill an HDMI infoframe with data from a DRM display mode

**Parameters**

- `struct hdmi_vendor_infoframe *frame`: HDMI vendor infoframe
- `const struct drm_connector *connector`: the connector
- `const struct drm_display_mode *mode`: DRM display mode

**Description**

Note that there's is a need to send HDMI vendor infoframes only when using a
4k or stereoscopic 3D mode. So when giving any other mode as input this
function will return -EINVAL, error that can be safely ignored.

**Return**

0 on success or a negative error code on failure.

#### <a id="c-drm_edid_is_digital"></a>`drm_edid_is_digital()`

```c
bool drm_edid_is_digital(const struct drm_edid *drm_edid)
```

is digital?

**Parameters**

- `const struct drm_edid *drm_edid`: The EDID

**Description**

Return true if input is digital.



#### <a id="c-drm_eld_mnl"></a>`drm_eld_mnl()`

```c
int drm_eld_mnl(const u8 *eld)
```

Get ELD monitor name length in bytes.

**Parameters**

- `const u8 *eld`: pointer to an eld memory structure with mnl set

#### <a id="c-drm_eld_sad"></a>`drm_eld_sad()`

```c
const u8 * drm_eld_sad(const u8 *eld)
```

Get ELD SAD structures.

**Parameters**

- `const u8 *eld`: pointer to an eld memory structure with sad_count set

#### <a id="c-drm_eld_sad_count"></a>`drm_eld_sad_count()`

```c
int drm_eld_sad_count(const u8 *eld)
```

Get ELD SAD count.

**Parameters**

- `const u8 *eld`: pointer to an eld memory structure with sad_count set

#### <a id="c-drm_eld_calc_baseline_block_size"></a>`drm_eld_calc_baseline_block_size()`

```c
int drm_eld_calc_baseline_block_size(const u8 *eld)
```

Calculate baseline block size in bytes

**Parameters**

- `const u8 *eld`: pointer to an eld memory structure with mnl and sad_count set

**Description**

This is a helper for determining the payload size of the baseline block, in
bytes, for e.g. setting the Baseline_ELD_Len field in the ELD header block.

#### <a id="c-drm_eld_size"></a>`drm_eld_size()`

```c
int drm_eld_size(const u8 *eld)
```

Get ELD size in bytes

**Parameters**

- `const u8 *eld`: pointer to a complete eld memory structure

**Description**

The returned value does not include the vendor block. It's vendor specific,
and comprises of the remaining bytes in the ELD memory buffer after
[`drm_eld_size()`](#c-drm_eld_size) bytes of header and baseline block.

The returned value is guaranteed to be a multiple of 4.

#### <a id="c-drm_eld_get_spk_alloc"></a>`drm_eld_get_spk_alloc()`

```c
u8 drm_eld_get_spk_alloc(const u8 *eld)
```

Get speaker allocation

**Parameters**

- `const u8 *eld`: pointer to an ELD memory structure

**Description**

The returned value is the speakers mask. User has to use `DRM_ELD_SPEAKER`
field definitions to identify speakers.

#### <a id="c-drm_eld_get_conn_type"></a>`drm_eld_get_conn_type()`

```c
u8 drm_eld_get_conn_type(const u8 *eld)
```

Get device type hdmi/dp connected

**Parameters**

- `const u8 *eld`: pointer to an ELD memory structure

**Description**

The caller need to use `DRM_ELD_CONN_TYPE_HDMI` or `DRM_ELD_CONN_TYPE_DP` to
identify the display type connected.



#### <a id="c-drm_eld_sad_get"></a>`drm_eld_sad_get()`

```c
int drm_eld_sad_get(const u8 *eld, int sad_index, struct cea_sad *cta_sad)
```

get SAD from ELD to struct cea_sad

**Parameters**

- `const u8 *eld`: ELD buffer
- `int sad_index`: SAD index
- `struct cea_sad *cta_sad`: destination struct cea_sad

**Return**

0 on success, or negative on errors

#### <a id="c-drm_eld_sad_set"></a>`drm_eld_sad_set()`

```c
int drm_eld_sad_set(u8 *eld, int sad_index, const struct cea_sad *cta_sad)
```

set SAD to ELD from struct cea_sad

**Parameters**

- `u8 *eld`: ELD buffer
- `int sad_index`: SAD index
- `const struct cea_sad *cta_sad`: source struct cea_sad

**Return**

0 on success, or negative on errors


<a id="rst-scdc-helper-functions-reference"></a>

## SCDC Helper Functions Reference


Status and Control Data Channel (SCDC) is a mechanism introduced by the
HDMI 2.0 specification. It is a point-to-point protocol that allows the
HDMI source and HDMI sink to exchange data. The same I2C interface that
is used to access EDID serves as the transport mechanism for SCDC.

Note: The SCDC status is going to be lost when the display is
disconnected. This can happen physically when the user disconnects
the cable, but also when a display is switched on (such as waking up
a TV).

This is further complicated by the fact that, upon a disconnection /
reconnection, KMS won't change the mode on its own. This means that
one can't just rely on setting the SCDC status on enable, but also
has to track the connector status changes using interrupts and
restore the SCDC status. The typical solution for this is to trigger an
empty modeset in drm_connector_helper_funcs.`detect_ctx()`, like what vc4 does
in `vc4_hdmi_reset_link()`.



#### <a id="c-drm_scdc_readb"></a>`drm_scdc_readb()`

```c
int drm_scdc_readb(struct i2c_adapter *adapter, u8 offset, u8 *value)
```

read a single byte from SCDC

**Parameters**

- `struct i2c_adapter *adapter`: I2C adapter
- `u8 offset`: offset of register to read
- `u8 *value`: return location for the register value

**Description**

Reads a single byte from SCDC. This is a convenience wrapper around the
[`drm_scdc_read()`](#c-drm_scdc_read) function.

**Return**

0 on success or a negative error code on failure.

#### <a id="c-drm_scdc_writeb"></a>`drm_scdc_writeb()`

```c
int drm_scdc_writeb(struct i2c_adapter *adapter, u8 offset, u8 value)
```

write a single byte to SCDC

**Parameters**

- `struct i2c_adapter *adapter`: I2C adapter
- `u8 offset`: offset of register to read
- `u8 value`: return location for the register value

**Description**

Writes a single byte to SCDC. This is a convenience wrapper around the
[`drm_scdc_write()`](#c-drm_scdc_write) function.

**Return**

0 on success or a negative error code on failure.



#### <a id="c-drm_scdc_read"></a>`drm_scdc_read()`

```c
ssize_t drm_scdc_read(struct i2c_adapter *adapter, u8 offset, void *buffer, size_t size)
```

read a block of data from SCDC

**Parameters**

- `struct i2c_adapter *adapter`: I2C controller
- `u8 offset`: start offset of block to read
- `void *buffer`: return location for the block to read
- `size_t size`: size of the block to read

**Description**

Reads a block of data from SCDC, starting at a given offset.

**Return**

0 on success, negative error code on failure.

#### <a id="c-drm_scdc_write"></a>`drm_scdc_write()`

```c
ssize_t drm_scdc_write(struct i2c_adapter *adapter, u8 offset, const void *buffer, size_t size)
```

write a block of data to SCDC

**Parameters**

- `struct i2c_adapter *adapter`: I2C controller
- `u8 offset`: start offset of block to write
- `const void *buffer`: block of data to write
- `size_t size`: size of the block to write

**Description**

Writes a block of data to SCDC, starting at a given offset.

**Return**

0 on success, negative error code on failure.

#### <a id="c-drm_scdc_get_scrambling_status"></a>`drm_scdc_get_scrambling_status()`

```c
bool drm_scdc_get_scrambling_status(struct drm_connector *connector)
```

what is status of scrambling?

**Parameters**

- `struct drm_connector *connector`: connector

**Description**

Reads the scrambler status over SCDC, and checks the
scrambling status.

**Return**

True if the scrambling is enabled, false otherwise.

#### <a id="c-drm_scdc_set_scrambling"></a>`drm_scdc_set_scrambling()`

```c
bool drm_scdc_set_scrambling(struct drm_connector *connector, bool enable)
```

enable scrambling

**Parameters**

- `struct drm_connector *connector`: connector
- `bool enable`: bool to indicate if scrambling is to be enabled/disabled

**Description**

Writes the TMDS config register over SCDC channel, and:
enables scrambling when enable = 1
disables scrambling when enable = 0

**Return**

True if scrambling is set/reset successfully, false otherwise.

#### <a id="c-drm_scdc_set_high_tmds_clock_ratio"></a>`drm_scdc_set_high_tmds_clock_ratio()`

```c
bool drm_scdc_set_high_tmds_clock_ratio(struct drm_connector *connector, bool set)
```

set TMDS clock ratio

**Parameters**

- `struct drm_connector *connector`: connector
- `bool set`: ret or reset the high clock ratio

**Description**

- TMDS clock ratio calculations go like this:
  TMDS character = 10 bit TMDS encoded value

  TMDS character rate = The rate at which TMDS characters are
  transmitted (Mcsc)

  TMDS bit rate = 10x TMDS character rate

- As per the spec:
  TMDS clock rate for pixel clock \< 340 MHz = 1x the character
  rate = 1/10 pixel clock rate

  TMDS clock rate for pixel clock > 340 MHz = 0.25x the character
  rate = 1/40 pixel clock rate

- Writes to the TMDS config register over SCDC channel, and:
  sets TMDS clock ratio to 1/40 when set = 1

  sets TMDS clock ratio to 1/10 when set = 0

**Return**

True if write is successful, false otherwise.


<a id="rst-hdmi-infoframes-helper-reference"></a>

## HDMI Infoframes Helper Reference

Strictly speaking this is not a DRM helper library but generally usable by any driver interfacing with HDMI outputs like v4l or alsa drivers. But it nicely fits into the overall topic of mode setting helper libraries and hence is also included here.


#### <a id="c-struct-hdr_sink_metadata"></a>`struct hdr_sink_metadata`

HDR sink metadata

**Definition**

```c
struct hdr_sink_metadata {
    __u32 metadata_type;
    union {
        struct hdr_static_metadata hdmi_type1;
    };
};
```

**Members**

- `metadata_type`: Static_Metadata_Descriptor_ID.
- `{unnamed_union}`: anonymous
- `hdmi_type1`: HDR Metadata Infoframe.

**Description**

Metadata Information read from Sink's EDID

#### <a id="c-union-hdmi_infoframe"></a>`union hdmi_infoframe`

overall union of all abstract infoframe representations

**Definition**

```c
union hdmi_infoframe {
    struct hdmi_any_infoframe any;
    struct hdmi_avi_infoframe avi;
    struct hdmi_spd_infoframe spd;
    union hdmi_vendor_any_infoframe vendor;
    struct hdmi_audio_infoframe audio;
    struct hdmi_drm_infoframe drm;
};
```

**Members**

- `any`: generic infoframe
- `avi`: avi infoframe
- `spd`: spd infoframe
- `vendor`: union of all vendor infoframes
- `audio`: audio infoframe
- `drm`: Dynamic Range and Mastering infoframe

**Description**

This is used by the generic pack function. This works since all infoframes
have the same header which also indicates which type of infoframe should be
packed.



#### <a id="c-hdmi_avi_infoframe_init"></a>`hdmi_avi_infoframe_init()`

```c
void hdmi_avi_infoframe_init(struct hdmi_avi_infoframe *frame)
```

initialize an HDMI AVI infoframe

**Parameters**

- `struct hdmi_avi_infoframe *frame`: HDMI AVI infoframe

#### <a id="c-hdmi_avi_infoframe_check"></a>`hdmi_avi_infoframe_check()`

```c
int hdmi_avi_infoframe_check(struct hdmi_avi_infoframe *frame)
```

check a HDMI AVI infoframe

**Parameters**

- `struct hdmi_avi_infoframe *frame`: HDMI AVI infoframe

**Description**

Validates that the infoframe is consistent and updates derived fields
(eg. length) based on other fields.

Returns 0 on success or a negative error code on failure.

#### <a id="c-hdmi_avi_infoframe_pack_only"></a>`hdmi_avi_infoframe_pack_only()`

```c
ssize_t hdmi_avi_infoframe_pack_only(const struct hdmi_avi_infoframe *frame, void *buffer, size_t size)
```

write HDMI AVI infoframe to binary buffer

**Parameters**

- `const struct hdmi_avi_infoframe *frame`: HDMI AVI infoframe
- `void *buffer`: destination buffer
- `size_t size`: size of buffer

**Description**

Packs the information contained in the **frame** structure into a binary
representation that can be written into the corresponding controller
registers. Also computes the checksum as required by section 5.3.5 of
the HDMI 1.4 specification.

Returns the number of bytes packed into the binary buffer or a negative
error code on failure.

#### <a id="c-hdmi_avi_infoframe_pack"></a>`hdmi_avi_infoframe_pack()`

```c
ssize_t hdmi_avi_infoframe_pack(struct hdmi_avi_infoframe *frame, void *buffer, size_t size)
```

check a HDMI AVI infoframe, and write it to binary buffer

**Parameters**

- `struct hdmi_avi_infoframe *frame`: HDMI AVI infoframe
- `void *buffer`: destination buffer
- `size_t size`: size of buffer

**Description**

Validates that the infoframe is consistent and updates derived fields
(eg. length) based on other fields, after which it packs the information
contained in the **frame** structure into a binary representation that
can be written into the corresponding controller registers. This function
also computes the checksum as required by section 5.3.5 of the HDMI 1.4
specification.

Returns the number of bytes packed into the binary buffer or a negative
error code on failure.

#### <a id="c-hdmi_spd_infoframe_init"></a>`hdmi_spd_infoframe_init()`

```c
int hdmi_spd_infoframe_init(struct hdmi_spd_infoframe *frame, const char *vendor, const char *product)
```

initialize an HDMI SPD infoframe

**Parameters**

- `struct hdmi_spd_infoframe *frame`: HDMI SPD infoframe
- `const char *vendor`: vendor string
- `const char *product`: product string

**Description**

Returns 0 on success or a negative error code on failure.

#### <a id="c-hdmi_spd_infoframe_check"></a>`hdmi_spd_infoframe_check()`

```c
int hdmi_spd_infoframe_check(struct hdmi_spd_infoframe *frame)
```

check a HDMI SPD infoframe

**Parameters**

- `struct hdmi_spd_infoframe *frame`: HDMI SPD infoframe

**Description**

Validates that the infoframe is consistent and updates derived fields
(eg. length) based on other fields.

Returns 0 on success or a negative error code on failure.

#### <a id="c-hdmi_spd_infoframe_pack_only"></a>`hdmi_spd_infoframe_pack_only()`

```c
ssize_t hdmi_spd_infoframe_pack_only(const struct hdmi_spd_infoframe *frame, void *buffer, size_t size)
```

write HDMI SPD infoframe to binary buffer

**Parameters**

- `const struct hdmi_spd_infoframe *frame`: HDMI SPD infoframe
- `void *buffer`: destination buffer
- `size_t size`: size of buffer

**Description**

Packs the information contained in the **frame** structure into a binary
representation that can be written into the corresponding controller
registers. Also computes the checksum as required by section 5.3.5 of
the HDMI 1.4 specification.

Returns the number of bytes packed into the binary buffer or a negative
error code on failure.

#### <a id="c-hdmi_spd_infoframe_pack"></a>`hdmi_spd_infoframe_pack()`

```c
ssize_t hdmi_spd_infoframe_pack(struct hdmi_spd_infoframe *frame, void *buffer, size_t size)
```

check a HDMI SPD infoframe, and write it to binary buffer

**Parameters**

- `struct hdmi_spd_infoframe *frame`: HDMI SPD infoframe
- `void *buffer`: destination buffer
- `size_t size`: size of buffer

**Description**

Validates that the infoframe is consistent and updates derived fields
(eg. length) based on other fields, after which it packs the information
contained in the **frame** structure into a binary representation that
can be written into the corresponding controller registers. This function
also computes the checksum as required by section 5.3.5 of the HDMI 1.4
specification.

Returns the number of bytes packed into the binary buffer or a negative
error code on failure.

#### <a id="c-hdmi_audio_infoframe_init"></a>`hdmi_audio_infoframe_init()`

```c
int hdmi_audio_infoframe_init(struct hdmi_audio_infoframe *frame)
```

initialize an HDMI audio infoframe

**Parameters**

- `struct hdmi_audio_infoframe *frame`: HDMI audio infoframe

**Description**

Returns 0 on success or a negative error code on failure.

#### <a id="c-hdmi_audio_infoframe_check"></a>`hdmi_audio_infoframe_check()`

```c
int hdmi_audio_infoframe_check(const struct hdmi_audio_infoframe *frame)
```

check a HDMI audio infoframe

**Parameters**

- `const struct hdmi_audio_infoframe *frame`: HDMI audio infoframe

**Description**

Validates that the infoframe is consistent and updates derived fields
(eg. length) based on other fields.

Returns 0 on success or a negative error code on failure.

#### <a id="c-hdmi_audio_infoframe_pack_only"></a>`hdmi_audio_infoframe_pack_only()`

```c
ssize_t hdmi_audio_infoframe_pack_only(const struct hdmi_audio_infoframe *frame, void *buffer, size_t size)
```

write HDMI audio infoframe to binary buffer

**Parameters**

- `const struct hdmi_audio_infoframe *frame`: HDMI audio infoframe
- `void *buffer`: destination buffer
- `size_t size`: size of buffer

**Description**

Packs the information contained in the **frame** structure into a binary
representation that can be written into the corresponding controller
registers. Also computes the checksum as required by section 5.3.5 of
the HDMI 1.4 specification.

Returns the number of bytes packed into the binary buffer or a negative
error code on failure.

#### <a id="c-hdmi_audio_infoframe_pack"></a>`hdmi_audio_infoframe_pack()`

```c
ssize_t hdmi_audio_infoframe_pack(struct hdmi_audio_infoframe *frame, void *buffer, size_t size)
```

check a HDMI Audio infoframe, and write it to binary buffer

**Parameters**

- `struct hdmi_audio_infoframe *frame`: HDMI Audio infoframe
- `void *buffer`: destination buffer
- `size_t size`: size of buffer

**Description**

Validates that the infoframe is consistent and updates derived fields
(eg. length) based on other fields, after which it packs the information
contained in the **frame** structure into a binary representation that
can be written into the corresponding controller registers. This function
also computes the checksum as required by section 5.3.5 of the HDMI 1.4
specification.

Returns the number of bytes packed into the binary buffer or a negative
error code on failure.

#### <a id="c-hdmi_audio_infoframe_pack_for_dp"></a>`hdmi_audio_infoframe_pack_for_dp()`

```c
ssize_t hdmi_audio_infoframe_pack_for_dp(const struct hdmi_audio_infoframe *frame, struct dp_sdp *sdp, u8 dp_version)
```

Pack a HDMI Audio infoframe for DisplayPort

**Parameters**

- `const struct hdmi_audio_infoframe *frame`: HDMI Audio infoframe
- `struct dp_sdp *sdp`: Secondary data packet for DisplayPort.
- `u8 dp_version`: DisplayPort version to be encoded in the header

**Description**

Packs a HDMI Audio Infoframe to be sent over DisplayPort. This function
fills the secondary data packet to be used for DisplayPort.

**Return**

Number of total written bytes or a negative errno on failure.

#### <a id="c-hdmi_vendor_infoframe_init"></a>`hdmi_vendor_infoframe_init()`

```c
int hdmi_vendor_infoframe_init(struct hdmi_vendor_infoframe *frame)
```

initialize an HDMI vendor infoframe

**Parameters**

- `struct hdmi_vendor_infoframe *frame`: HDMI vendor infoframe

**Description**

Returns 0 on success or a negative error code on failure.

#### <a id="c-hdmi_vendor_infoframe_check"></a>`hdmi_vendor_infoframe_check()`

```c
int hdmi_vendor_infoframe_check(struct hdmi_vendor_infoframe *frame)
```

check a HDMI vendor infoframe

**Parameters**

- `struct hdmi_vendor_infoframe *frame`: HDMI infoframe

**Description**

Validates that the infoframe is consistent and updates derived fields
(eg. length) based on other fields.

Returns 0 on success or a negative error code on failure.

#### <a id="c-hdmi_vendor_infoframe_pack_only"></a>`hdmi_vendor_infoframe_pack_only()`

```c
ssize_t hdmi_vendor_infoframe_pack_only(const struct hdmi_vendor_infoframe *frame, void *buffer, size_t size)
```

write a HDMI vendor infoframe to binary buffer

**Parameters**

- `const struct hdmi_vendor_infoframe *frame`: HDMI infoframe
- `void *buffer`: destination buffer
- `size_t size`: size of buffer

**Description**

Packs the information contained in the **frame** structure into a binary
representation that can be written into the corresponding controller
registers. Also computes the checksum as required by section 5.3.5 of
the HDMI 1.4 specification.

Returns the number of bytes packed into the binary buffer or a negative
error code on failure.

#### <a id="c-hdmi_vendor_infoframe_pack"></a>`hdmi_vendor_infoframe_pack()`

```c
ssize_t hdmi_vendor_infoframe_pack(struct hdmi_vendor_infoframe *frame, void *buffer, size_t size)
```

check a HDMI Vendor infoframe, and write it to binary buffer

**Parameters**

- `struct hdmi_vendor_infoframe *frame`: HDMI Vendor infoframe
- `void *buffer`: destination buffer
- `size_t size`: size of buffer

**Description**

Validates that the infoframe is consistent and updates derived fields
(eg. length) based on other fields, after which it packs the information
contained in the **frame** structure into a binary representation that
can be written into the corresponding controller registers. This function
also computes the checksum as required by section 5.3.5 of the HDMI 1.4
specification.

Returns the number of bytes packed into the binary buffer or a negative
error code on failure.

#### <a id="c-hdmi_drm_infoframe_init"></a>`hdmi_drm_infoframe_init()`

```c
int hdmi_drm_infoframe_init(struct hdmi_drm_infoframe *frame)
```

initialize an HDMI Dynaminc Range and mastering infoframe

**Parameters**

- `struct hdmi_drm_infoframe *frame`: HDMI DRM infoframe

**Description**

Returns 0 on success or a negative error code on failure.

#### <a id="c-hdmi_drm_infoframe_check"></a>`hdmi_drm_infoframe_check()`

```c
int hdmi_drm_infoframe_check(struct hdmi_drm_infoframe *frame)
```

check a HDMI DRM infoframe

**Parameters**

- `struct hdmi_drm_infoframe *frame`: HDMI DRM infoframe

**Description**

Validates that the infoframe is consistent.
Returns 0 on success or a negative error code on failure.

#### <a id="c-hdmi_drm_infoframe_pack_only"></a>`hdmi_drm_infoframe_pack_only()`

```c
ssize_t hdmi_drm_infoframe_pack_only(const struct hdmi_drm_infoframe *frame, void *buffer, size_t size)
```

write HDMI DRM infoframe to binary buffer

**Parameters**

- `const struct hdmi_drm_infoframe *frame`: HDMI DRM infoframe
- `void *buffer`: destination buffer
- `size_t size`: size of buffer

**Description**

Packs the information contained in the **frame** structure into a binary
representation that can be written into the corresponding controller
registers. Also computes the checksum as required by section 5.3.5 of
the HDMI 1.4 specification.

Returns the number of bytes packed into the binary buffer or a negative
error code on failure.

#### <a id="c-hdmi_drm_infoframe_pack"></a>`hdmi_drm_infoframe_pack()`

```c
ssize_t hdmi_drm_infoframe_pack(struct hdmi_drm_infoframe *frame, void *buffer, size_t size)
```

check a HDMI DRM infoframe, and write it to binary buffer

**Parameters**

- `struct hdmi_drm_infoframe *frame`: HDMI DRM infoframe
- `void *buffer`: destination buffer
- `size_t size`: size of buffer

**Description**

Validates that the infoframe is consistent and updates derived fields
(eg. length) based on other fields, after which it packs the information
contained in the **frame** structure into a binary representation that
can be written into the corresponding controller registers. This function
also computes the checksum as required by section 5.3.5 of the HDMI 1.4
specification.

Returns the number of bytes packed into the binary buffer or a negative
error code on failure.

#### <a id="c-hdmi_infoframe_pack_only"></a>`hdmi_infoframe_pack_only()`

```c
ssize_t hdmi_infoframe_pack_only(const union hdmi_infoframe *frame, void *buffer, size_t size)
```

write a HDMI infoframe to binary buffer

**Parameters**

- `const union hdmi_infoframe *frame`: HDMI infoframe
- `void *buffer`: destination buffer
- `size_t size`: size of buffer

**Description**

Packs the information contained in the **frame** structure into a binary
representation that can be written into the corresponding controller
registers. Also computes the checksum as required by section 5.3.5 of
the HDMI 1.4 specification.

Returns the number of bytes packed into the binary buffer or a negative
error code on failure.

#### <a id="c-hdmi_infoframe_pack"></a>`hdmi_infoframe_pack()`

```c
ssize_t hdmi_infoframe_pack(union hdmi_infoframe *frame, void *buffer, size_t size)
```

check a HDMI infoframe, and write it to binary buffer

**Parameters**

- `union hdmi_infoframe *frame`: HDMI infoframe
- `void *buffer`: destination buffer
- `size_t size`: size of buffer

**Description**

Validates that the infoframe is consistent and updates derived fields
(eg. length) based on other fields, after which it packs the information
contained in the **frame** structure into a binary representation that
can be written into the corresponding controller registers. This function
also computes the checksum as required by section 5.3.5 of the HDMI 1.4
specification.

Returns the number of bytes packed into the binary buffer or a negative
error code on failure.

#### <a id="c-hdmi_infoframe_log"></a>`hdmi_infoframe_log()`

```c
void hdmi_infoframe_log(const char *level, struct device *dev, const union hdmi_infoframe *frame)
```

log info of HDMI infoframe

**Parameters**

- `const char *level`: logging level
- `struct device *dev`: device
- `const union hdmi_infoframe *frame`: HDMI infoframe

#### <a id="c-hdmi_drm_infoframe_unpack_only"></a>`hdmi_drm_infoframe_unpack_only()`

```c
int hdmi_drm_infoframe_unpack_only(struct hdmi_drm_infoframe *frame, const void *buffer, size_t size)
```

unpack binary buffer of CTA-861-G DRM infoframe DataBytes to a HDMI DRM infoframe

**Parameters**

- `struct hdmi_drm_infoframe *frame`: HDMI DRM infoframe
- `const void *buffer`: source buffer
- `size_t size`: size of buffer

**Description**

Unpacks CTA-861-G DRM infoframe DataBytes contained in the binary **buffer**
into a structured **frame** of the HDMI Dynamic Range and Mastering (DRM)
infoframe.

Returns 0 on success or a negative error code on failure.

#### <a id="c-hdmi_infoframe_unpack"></a>`hdmi_infoframe_unpack()`

```c
int hdmi_infoframe_unpack(union hdmi_infoframe *frame, const void *buffer, size_t size)
```

unpack binary buffer to a HDMI infoframe

**Parameters**

- `union hdmi_infoframe *frame`: HDMI infoframe
- `const void *buffer`: source buffer
- `size_t size`: size of buffer

**Description**

Unpacks the information contained in binary buffer **buffer** into a structured
**frame** of a HDMI infoframe.
Also verifies the checksum as required by section 5.3.5 of the HDMI 1.4
specification.

Returns 0 on success or a negative error code on failure.


<a id="rst-rectangle-utilities-reference"></a>

## Rectangle Utilities Reference


Utility functions to help manage rectangular areas for
clipping, scaling, etc. calculations.



#### <a id="c-struct-drm_rect"></a>`struct drm_rect`

two dimensional rectangle

**Definition**

```c
struct drm_rect {
    int x1, y1, x2, y2;
};
```

**Members**

- `x1`: horizontal starting coordinate (inclusive)
- `y1`: vertical starting coordinate (inclusive)
- `x2`: horizontal ending coordinate (exclusive)
- `y2`: vertical ending coordinate (exclusive)

**Description**

Note that this must match the layout of struct drm_mode_rect or the damage
helpers like [`drm_atomic_helper_damage_iter_init()`](/kernel/hardware/gpu/drm-kms.md#c-drm_atomic_helper_damage_iter_init) break.

#### <a id="c-DRM_RECT_INIT"></a>`DRM_RECT_INIT()`

```c
DRM_RECT_INIT(x, y, w, h)
```

initialize a rectangle from x/y/w/h

**Parameters**

- `x`: x coordinate
- `y`: y coordinate
- `w`: width
- `h`: height

**Return**

A new rectangle of the specified size.

#### <a id="c-DRM_RECT_FMT"></a>`DRM_RECT_FMT`

```c
DRM_RECT_FMT
```

printf string for [`struct drm_rect`](#c-struct-drm_rect)

#### <a id="c-DRM_RECT_ARG"></a>`DRM_RECT_ARG()`

```c
DRM_RECT_ARG(r)
```

printf arguments for [`struct drm_rect`](#c-struct-drm_rect)

**Parameters**

- `r`: rectangle struct

#### <a id="c-DRM_RECT_FP_FMT"></a>`DRM_RECT_FP_FMT`

```c
DRM_RECT_FP_FMT
```

printf string for [`struct drm_rect`](#c-struct-drm_rect) in 16.16 fixed point

#### <a id="c-DRM_RECT_FP_ARG"></a>`DRM_RECT_FP_ARG()`

```c
DRM_RECT_FP_ARG(r)
```

printf arguments for [`struct drm_rect`](#c-struct-drm_rect) in 16.16 fixed point

**Parameters**

- `r`: rectangle struct

**Description**

This is useful for e.g. printing plane source rectangles, which are in 16.16
fixed point.

#### <a id="c-drm_rect_init"></a>`drm_rect_init()`

```c
void drm_rect_init(struct drm_rect *r, int x, int y, int width, int height)
```

initialize the rectangle from x/y/w/h

**Parameters**

- `struct drm_rect *r`: rectangle
- `int x`: x coordinate
- `int y`: y coordinate
- `int width`: width
- `int height`: height

#### <a id="c-drm_rect_adjust_size"></a>`drm_rect_adjust_size()`

```c
void drm_rect_adjust_size(struct drm_rect *r, int dw, int dh)
```

adjust the size of the rectangle

**Parameters**

- `struct drm_rect *r`: rectangle to be adjusted
- `int dw`: horizontal adjustment
- `int dh`: vertical adjustment

**Description**

Change the size of rectangle **r** by **dw** in the horizontal direction,
and by **dh** in the vertical direction, while keeping the center
of **r** stationary.

Positive **dw** and **dh** increase the size, negative values decrease it.

#### <a id="c-drm_rect_translate"></a>`drm_rect_translate()`

```c
void drm_rect_translate(struct drm_rect *r, int dx, int dy)
```

translate the rectangle

**Parameters**

- `struct drm_rect *r`: rectangle to be translated
- `int dx`: horizontal translation
- `int dy`: vertical translation

**Description**

Move rectangle **r** by **dx** in the horizontal direction,
and by **dy** in the vertical direction.

#### <a id="c-drm_rect_translate_to"></a>`drm_rect_translate_to()`

```c
void drm_rect_translate_to(struct drm_rect *r, int x, int y)
```

translate the rectangle to an absolute position

**Parameters**

- `struct drm_rect *r`: rectangle to be translated
- `int x`: horizontal position
- `int y`: vertical position

**Description**

Move rectangle **r** to **x** in the horizontal direction,
and to **y** in the vertical direction.

#### <a id="c-drm_rect_downscale"></a>`drm_rect_downscale()`

```c
void drm_rect_downscale(struct drm_rect *r, int horz, int vert)
```

downscale a rectangle

**Parameters**

- `struct drm_rect *r`: rectangle to be downscaled
- `int horz`: horizontal downscale factor
- `int vert`: vertical downscale factor

**Description**

Divide the coordinates of rectangle **r** by **horz** and **vert**.

#### <a id="c-drm_rect_width"></a>`drm_rect_width()`

```c
int drm_rect_width(const struct drm_rect *r)
```

determine the rectangle width

**Parameters**

- `const struct drm_rect *r`: rectangle whose width is returned

**Return**

The width of the rectangle.

#### <a id="c-drm_rect_height"></a>`drm_rect_height()`

```c
int drm_rect_height(const struct drm_rect *r)
```

determine the rectangle height

**Parameters**

- `const struct drm_rect *r`: rectangle whose height is returned

**Return**

The height of the rectangle.

#### <a id="c-drm_rect_visible"></a>`drm_rect_visible()`

```c
bool drm_rect_visible(const struct drm_rect *r)
```

determine if the rectangle is visible

**Parameters**

- `const struct drm_rect *r`: rectangle whose visibility is returned

**Return**

`true` if the rectangle is visible, `false` otherwise.

#### <a id="c-drm_rect_equals"></a>`drm_rect_equals()`

```c
bool drm_rect_equals(const struct drm_rect *r1, const struct drm_rect *r2)
```

determine if two rectangles are equal

**Parameters**

- `const struct drm_rect *r1`: first rectangle
- `const struct drm_rect *r2`: second rectangle

**Return**

`true` if the rectangles are equal, `false` otherwise.

#### <a id="c-drm_rect_fp_to_int"></a>`drm_rect_fp_to_int()`

```c
void drm_rect_fp_to_int(struct drm_rect *dst, const struct drm_rect *src)
```

Convert a rect in 16.16 fixed point form to int form.

**Parameters**

- `struct drm_rect *dst`: rect to be stored the converted value
- `const struct drm_rect *src`: rect in 16.16 fixed point form

#### <a id="c-drm_rect_overlap"></a>`drm_rect_overlap()`

```c
bool drm_rect_overlap(const struct drm_rect *a, const struct drm_rect *b)
```

Check if two rectangles overlap

**Parameters**

- `const struct drm_rect *a`: first rectangle
- `const struct drm_rect *b`: second rectangle

**Return**

`true` if the rectangles overlap, `false` otherwise.



#### <a id="c-drm_rect_intersect"></a>`drm_rect_intersect()`

```c
bool drm_rect_intersect(struct drm_rect *r1, const struct drm_rect *r2)
```

intersect two rectangles

**Parameters**

- `struct drm_rect *r1`: first rectangle
- `const struct drm_rect *r2`: second rectangle

**Description**

Calculate the intersection of rectangles **r1** and **r2**.
**r1** will be overwritten with the intersection.

**Return**

`true` if rectangle **r1** is still visible after the operation,
`false` otherwise.

#### <a id="c-drm_rect_clip_scaled"></a>`drm_rect_clip_scaled()`

```c
bool drm_rect_clip_scaled(struct drm_rect *src, struct drm_rect *dst, const struct drm_rect *clip)
```

perform a scaled clip operation

**Parameters**

- `struct drm_rect *src`: source window rectangle
- `struct drm_rect *dst`: destination window rectangle
- `const struct drm_rect *clip`: clip rectangle

**Description**

Clip rectangle **dst** by rectangle **clip**. Clip rectangle **src** by
the corresponding amounts, retaining the vertical and horizontal scaling
factors from **src** to **dst**.

**Return**

`true` if rectangle **dst** is still visible after being clipped,
`false` otherwise.

#### <a id="c-drm_rect_calc_hscale"></a>`drm_rect_calc_hscale()`

```c
int drm_rect_calc_hscale(const struct drm_rect *src, const struct drm_rect *dst, int min_hscale, int max_hscale)
```

calculate the horizontal scaling factor

**Parameters**

- `const struct drm_rect *src`: source window rectangle
- `const struct drm_rect *dst`: destination window rectangle
- `int min_hscale`: minimum allowed horizontal scaling factor
- `int max_hscale`: maximum allowed horizontal scaling factor

**Description**

Calculate the horizontal scaling factor as
(**src** width) / (**dst** width).

If the scale is below 1 \<\< 16, round down. If the scale is above
1 \<\< 16, round up. This will calculate the scale with the most
pessimistic limit calculation.

**Return**

The horizontal scaling factor, or errno of out of limits.

#### <a id="c-drm_rect_calc_vscale"></a>`drm_rect_calc_vscale()`

```c
int drm_rect_calc_vscale(const struct drm_rect *src, const struct drm_rect *dst, int min_vscale, int max_vscale)
```

calculate the vertical scaling factor

**Parameters**

- `const struct drm_rect *src`: source window rectangle
- `const struct drm_rect *dst`: destination window rectangle
- `int min_vscale`: minimum allowed vertical scaling factor
- `int max_vscale`: maximum allowed vertical scaling factor

**Description**

Calculate the vertical scaling factor as
(**src** height) / (**dst** height).

If the scale is below 1 \<\< 16, round down. If the scale is above
1 \<\< 16, round up. This will calculate the scale with the most
pessimistic limit calculation.

**Return**

The vertical scaling factor, or errno of out of limits.

#### <a id="c-drm_rect_debug_print"></a>`drm_rect_debug_print()`

```c
void drm_rect_debug_print(const char *prefix, const struct drm_rect *r, bool fixed_point)
```

print the rectangle information

**Parameters**

- `const char *prefix`: prefix string
- `const struct drm_rect *r`: rectangle to print
- `bool fixed_point`: rectangle is in 16.16 fixed point format

#### <a id="c-drm_rect_rotate"></a>`drm_rect_rotate()`

```c
void drm_rect_rotate(struct drm_rect *r, int width, int height, unsigned int rotation)
```

Rotate the rectangle

**Parameters**

- `struct drm_rect *r`: rectangle to be rotated
- `int width`: Width of the coordinate space
- `int height`: Height of the coordinate space
- `unsigned int rotation`: Transformation to be applied

**Description**

Apply **rotation** to the coordinates of rectangle **r**.

**width** and **height** combined with **rotation** define
the location of the new origin.

**width** correcsponds to the horizontal and **height**
to the vertical axis of the untransformed coordinate
space.

#### <a id="c-drm_rect_rotate_inv"></a>`drm_rect_rotate_inv()`

```c
void drm_rect_rotate_inv(struct drm_rect *r, int width, int height, unsigned int rotation)
```

Inverse rotate the rectangle

**Parameters**

- `struct drm_rect *r`: rectangle to be rotated
- `int width`: Width of the coordinate space
- `int height`: Height of the coordinate space
- `unsigned int rotation`: Transformation whose inverse is to be applied

**Description**

Apply the inverse of **rotation** to the coordinates
of rectangle **r**.

**width** and **height** combined with **rotation** define
the location of the new origin.

**width** correcsponds to the horizontal and **height**
to the vertical axis of the original untransformed
coordinate space, so that you never have to flip
them when doing a rotatation and its inverse.
That is, if you do

```text
drm_rect_rotate(&r, width, height, rotation);
drm_rect_rotate_inv(&r, width, height, rotation);
```

you will always get back the original rectangle.


<a id="rst-flip-work-helper-reference"></a>

## Flip-work Helper Reference


Utility to queue up work to run from work-queue context after flip/vblank.
Typically this can be used to defer unref of framebuffer's, cursor
bo's, etc until after vblank. The APIs are all thread-safe. Moreover,
[`drm_flip_work_commit()`](#c-drm_flip_work_commit) can be called in atomic context.



#### <a id="c-struct-drm_flip_work"></a>`struct drm_flip_work`

flip work queue

**Definition**

```c
struct drm_flip_work {
    const char *name;
    drm_flip_func_t func;
    struct work_struct worker;
    struct list_head queued;
    struct list_head commited;
    spinlock_t lock;
};
```

**Members**

- `name`: debug name
- `func`: callback fxn called for each committed item
- `worker`: worker which calls **func**
- `queued`: queued tasks
- `commited`: commited tasks
- `lock`: lock to access queued and commited lists



#### <a id="c-drm_flip_work_queue"></a>`drm_flip_work_queue()`

```c
void drm_flip_work_queue(struct drm_flip_work *work, void *val)
```

queue work

**Parameters**

- `struct drm_flip_work *work`: the flip-work
- `void *val`: the value to queue

**Description**

Queues work, that will later be run (passed back to drm_flip_func_t
func) on a work queue after [`drm_flip_work_commit()`](#c-drm_flip_work_commit) is called.

#### <a id="c-drm_flip_work_commit"></a>`drm_flip_work_commit()`

```c
void drm_flip_work_commit(struct drm_flip_work *work, struct workqueue_struct *wq)
```

commit queued work

**Parameters**

- `struct drm_flip_work *work`: the flip-work
- `struct workqueue_struct *wq`: the work-queue to run the queued work on

**Description**

Trigger work previously queued by [`drm_flip_work_queue()`](#c-drm_flip_work_queue) to run
on a workqueue.  The typical usage would be to queue work (via
[`drm_flip_work_queue()`](#c-drm_flip_work_queue)) at any point (from vblank irq and/or
prior), and then from vblank irq commit the queued work.

#### <a id="c-drm_flip_work_init"></a>`drm_flip_work_init()`

```c
void drm_flip_work_init(struct drm_flip_work *work, const char *name, drm_flip_func_t func)
```

initialize flip-work

**Parameters**

- `struct drm_flip_work *work`: the flip-work to initialize
- `const char *name`: debug name
- `drm_flip_func_t func`: the callback work function

**Description**

Initializes/allocates resources for the flip-work

#### <a id="c-drm_flip_work_cleanup"></a>`drm_flip_work_cleanup()`

```c
void drm_flip_work_cleanup(struct drm_flip_work *work)
```

cleans up flip-work

**Parameters**

- `struct drm_flip_work *work`: the flip-work to cleanup

**Description**

Destroy resources allocated for the flip-work


<a id="rst-auxiliary-modeset-helpers"></a>

## Auxiliary Modeset Helpers


This helper library contains various one-off functions which don't really fit
anywhere else in the DRM modeset helper library.



#### <a id="c-drm_helper_move_panel_connectors_to_head"></a>`drm_helper_move_panel_connectors_to_head()`

```c
void drm_helper_move_panel_connectors_to_head(struct drm_device *dev)
```

move panels to the front in the connector list

**Parameters**

- `struct drm_device *dev`: drm device to operate on

**Description**

Some userspace presumes that the first connected connector is the main
display, where it's supposed to display e.g. the login screen. For
laptops, this should be the main panel. Use this function to sort all
(eDP/LVDS/DSI) panels to the front of the connector list, instead of
painstakingly trying to initialize them in the right order.

#### <a id="c-drm_helper_mode_fill_fb_struct"></a>`drm_helper_mode_fill_fb_struct()`

```c
void drm_helper_mode_fill_fb_struct(struct drm_device *dev, struct drm_framebuffer *fb, const struct drm_format_info *info, const struct drm_mode_fb_cmd2 *mode_cmd)
```

fill out framebuffer metadata

**Parameters**

- `struct drm_device *dev`: DRM device
- `struct drm_framebuffer *fb`: drm_framebuffer object to fill out
- `const struct drm_format_info *info`: pixel format information
- `const struct drm_mode_fb_cmd2 *mode_cmd`: metadata from the userspace fb creation request

**Description**

This helper can be used in a drivers fb_create callback to pre-fill the fb's
metadata fields.

#### <a id="c-drm_crtc_init"></a>`drm_crtc_init()`

```c
int drm_crtc_init(struct drm_device *dev, struct drm_crtc *crtc, const struct drm_crtc_funcs *funcs)
```

Legacy CRTC initialization function

**Parameters**

- `struct drm_device *dev`: DRM device
- `struct drm_crtc *crtc`: CRTC object to init
- `const struct drm_crtc_funcs *funcs`: callbacks for the new CRTC

**Description**

Initialize a CRTC object with a default helper-provided primary plane and no
cursor plane.

Note that we make some assumptions about hardware limitations that may not be
true for all hardware:

1. Primary plane cannot be repositioned.
2. Primary plane cannot be scaled.
3. Primary plane must cover the entire CRTC.
4. Subpixel positioning is not supported.
5. The primary plane must always be on if the CRTC is enabled.

This is purely a backwards compatibility helper for old drivers. Drivers
should instead implement their own primary plane. Atomic drivers must do so.
Drivers with the above hardware restriction can look into using [`struct drm_simple_display_pipe`](#c-struct-drm_simple_display_pipe), which encapsulates the above limitations into a nice
interface.

**Return**

Zero on success, error code on failure.

#### <a id="c-drm_mode_config_helper_suspend"></a>`drm_mode_config_helper_suspend()`

```c
int drm_mode_config_helper_suspend(struct drm_device *dev)
```

Modeset suspend helper

**Parameters**

- `struct drm_device *dev`: DRM device

**Description**

This helper function takes care of suspending the modeset side. It disables
output polling if initialized, suspends fbdev if used and finally calls
[`drm_atomic_helper_suspend()`](#c-drm_atomic_helper_suspend).
If suspending fails, fbdev and polling is re-enabled.

See also:
[`drm_kms_helper_poll_disable()`](#c-drm_kms_helper_poll_disable) and `drm_client_dev_suspend()`.

**Return**

Zero on success, negative error code on error.

#### <a id="c-drm_mode_config_helper_resume"></a>`drm_mode_config_helper_resume()`

```c
int drm_mode_config_helper_resume(struct drm_device *dev)
```

Modeset resume helper

**Parameters**

- `struct drm_device *dev`: DRM device

**Description**

This helper function takes care of resuming the modeset side. It calls
[`drm_atomic_helper_resume()`](#c-drm_atomic_helper_resume), resumes fbdev if used and enables output polling
if initiaized.

See also:
`drm_client_dev_resume()` and [`drm_kms_helper_poll_enable()`](#c-drm_kms_helper_poll_enable).

**Return**

Zero on success, negative error code on error.


<a id="rst-of-dt-helpers"></a>

## OF/DT Helpers


A set of helper functions to aid DRM drivers in parsing standard DT
properties.



#### <a id="c-drm_of_crtc_port_mask"></a>`drm_of_crtc_port_mask()`

```c
uint32_t drm_of_crtc_port_mask(struct drm_device *dev, struct device_node *port)
```

find the mask of a registered CRTC by port OF node

**Parameters**

- `struct drm_device *dev`: DRM device
- `struct device_node *port`: port OF node

**Description**

Given a port OF node, return the possible mask of the corresponding
CRTC within a device's list of CRTCs.  Returns zero if not found.

#### <a id="c-drm_of_find_possible_crtcs"></a>`drm_of_find_possible_crtcs()`

```c
uint32_t drm_of_find_possible_crtcs(struct drm_device *dev, struct device_node *port)
```

find the possible CRTCs for an encoder port

**Parameters**

- `struct drm_device *dev`: DRM device
- `struct device_node *port`: encoder port to scan for endpoints

**Description**

Scan all endpoints attached to a port, locate their attached CRTCs,
and generate the DRM mask of CRTCs which may be attached to this
encoder.

See https://github.com/devicetree-org/dt-schema/blob/main/dtschema/schemas/graph.yaml
for the bindings.

#### <a id="c-drm_of_component_match_add"></a>`drm_of_component_match_add()`

```c
void drm_of_component_match_add(struct device *master, struct component_match **matchptr, int (*compare)(struct device *, void *), struct device_node *node)
```

Add a component helper OF node match rule

**Parameters**

- `struct device *master`: master device
- `struct component_match **matchptr`: component match pointer
- `int (*compare)(struct device *, void *)`: compare function used for matching component
- `struct device_node *node`: of_node

#### <a id="c-drm_of_component_probe"></a>`drm_of_component_probe()`

```c
int drm_of_component_probe(struct device *dev, int (*compare_of)(struct device *, void *), const struct component_master_ops *m_ops)
```

Generic probe function for a component based master

**Parameters**

- `struct device *dev`: master device containing the OF node
- `int (*compare_of)(struct device *, void *)`: compare function used for matching components
- `const struct component_master_ops *m_ops`: component master ops to be used

**Description**

Parse the platform device OF node and bind all the components associated
with the master. Interface ports are added before the encoders in order to
satisfy their .bind requirements

See https://github.com/devicetree-org/dt-schema/blob/main/dtschema/schemas/graph.yaml
for the bindings.

Returns zero if successful, or one of the standard error codes if it fails.

#### <a id="c-drm_of_find_panel_or_bridge"></a>`drm_of_find_panel_or_bridge()`

```c
int drm_of_find_panel_or_bridge(const struct device_node *np, int port, int endpoint, struct drm_panel **panel, struct drm_bridge **bridge)
```

return connected panel or bridge device

**Parameters**

- `const struct device_node *np`: device tree node containing encoder output ports
- `int port`: port in the device tree node
- `int endpoint`: endpoint in the device tree node
- `struct drm_panel **panel`: pointer to hold returned drm_panel
- `struct drm_bridge **bridge`: pointer to hold returned drm_bridge

**Description**

Given a DT node's port and endpoint number, find the connected node and
return either the associated struct drm_panel or drm_bridge device. Either
**panel** or **bridge** must not be NULL.

This function is deprecated and should not be used in new drivers. Use
[`devm_drm_of_get_bridge()`](#c-devm_drm_of_get_bridge) instead.

Returns zero if successful, or one of the standard error codes if it fails.

#### <a id="c-drm_of_lvds_get_dual_link_pixel_order"></a>`drm_of_lvds_get_dual_link_pixel_order()`

```c
int drm_of_lvds_get_dual_link_pixel_order(const struct device_node *port1, const struct device_node *port2)
```

Get LVDS dual-link source pixel order

**Parameters**

- `const struct device_node *port1`: First DT port node of the Dual-link LVDS source
- `const struct device_node *port2`: Second DT port node of the Dual-link LVDS source

**Description**

An LVDS dual-link connection is made of two links, with even pixels
transitting on one link, and odd pixels on the other link. This function
returns, for two ports of an LVDS dual-link source, which port shall transmit
the even and odd pixels, based on the requirements of the connected sink.

The pixel order is determined from the dual-lvds-even-pixels and
dual-lvds-odd-pixels properties in the sink's DT port nodes. If those
properties are not present, or if their usage is not valid, this function
returns -EINVAL.

If either port is not connected, this function returns -EPIPE.

**port1** and **port2** are typically DT sibling nodes, but may have different
parents when, for instance, two separate LVDS encoders carry the even and odd
pixels.

**Return**

* DRM_LVDS_DUAL_LINK_EVEN_ODD_PIXELS - **port1** carries even pixels and **port2**
  carries odd pixels
* DRM_LVDS_DUAL_LINK_ODD_EVEN_PIXELS - **port1** carries odd pixels and **port2**
  carries even pixels
* -EINVAL - **port1** and **port2** are not connected to a dual-link LVDS sink, or
  the sink configuration is invalid
* -EPIPE - when **port1** or **port2** are not connected

#### <a id="c-drm_of_lvds_get_dual_link_pixel_order_sink"></a>`drm_of_lvds_get_dual_link_pixel_order_sink()`

```c
int drm_of_lvds_get_dual_link_pixel_order_sink(struct device_node *port1, struct device_node *port2)
```

Get LVDS dual-link sink pixel order

**Parameters**

- `struct device_node *port1`: First DT port node of the Dual-link LVDS sink
- `struct device_node *port2`: Second DT port node of the Dual-link LVDS sink

**Description**

An LVDS dual-link connection is made of two links, with even pixels
transitting on one link, and odd pixels on the other link. This function
returns, for two ports of an LVDS dual-link sink, which port shall transmit
the even and odd pixels, based on the requirements of the sink.

The pixel order is determined from the dual-lvds-even-pixels and
dual-lvds-odd-pixels properties in the sink's DT port nodes. If those
properties are not present, or if their usage is not valid, this function
returns -EINVAL.

If either port is not connected, this function returns -EPIPE.

**port1** and **port2** are typically DT sibling nodes, but may have different
parents when, for instance, two separate LVDS decoders receive the even and
odd pixels.

**Return**

* DRM_LVDS_DUAL_LINK_EVEN_ODD_PIXELS - **port1** receives even pixels and **port2**
  receives odd pixels
* DRM_LVDS_DUAL_LINK_ODD_EVEN_PIXELS - **port1** receives odd pixels and **port2**
  receives even pixels
* -EINVAL - **port1** or **port2** are NULL
* -EPIPE - when **port1** or **port2** are not connected

#### <a id="c-drm_of_lvds_get_data_mapping"></a>`drm_of_lvds_get_data_mapping()`

```c
int drm_of_lvds_get_data_mapping(const struct device_node *port)
```

Get LVDS data mapping

**Parameters**

- `const struct device_node *port`: DT port node of the LVDS source or sink

**Description**

Convert DT "data-mapping" property string value into media bus format value.

**Return**

* MEDIA_BUS_FMT_RGB666_1X7X3_SPWG - data-mapping is "jeida-18"
* MEDIA_BUS_FMT_RGB888_1X7X4_JEIDA - data-mapping is "jeida-24"
* MEDIA_BUS_FMT_RGB101010_1X7X5_JEIDA - data-mapping is "jeida-30"
* MEDIA_BUS_FMT_RGB888_1X7X4_SPWG - data-mapping is "vesa-24"
* MEDIA_BUS_FMT_RGB101010_1X7X5_SPWG - data-mapping is "vesa-30"
* -EINVAL - the "data-mapping" property is unsupported
* -ENODEV - the "data-mapping" property is missing

#### <a id="c-drm_of_get_data_lanes_count"></a>`drm_of_get_data_lanes_count()`

```c
int drm_of_get_data_lanes_count(const struct device_node *endpoint, const unsigned int min, const unsigned int max)
```

Get DSI/(e)DP data lane count

**Parameters**

- `const struct device_node *endpoint`: DT endpoint node of the DSI/(e)DP source or sink
- `const unsigned int min`: minimum supported number of data lanes
- `const unsigned int max`: maximum supported number of data lanes

**Description**

Count DT "data-lanes" property elements and check for validity.

**Return**

* min..max - positive integer count of "data-lanes" elements
* -ve - the "data-lanes" property is missing or invalid
* -EINVAL - the "data-lanes" property is unsupported

#### <a id="c-drm_of_get_data_lanes_count_ep"></a>`drm_of_get_data_lanes_count_ep()`

```c
int drm_of_get_data_lanes_count_ep(const struct device_node *port, int port_reg, int reg, const unsigned int min, const unsigned int max)
```

Get DSI/(e)DP data lane count by endpoint

**Parameters**

- `const struct device_node *port`: DT port node of the DSI/(e)DP source or sink
- `int port_reg`: identifier (value of reg property) of the parent port node
- `int reg`: identifier (value of reg property) of the endpoint node
- `const unsigned int min`: minimum supported number of data lanes
- `const unsigned int max`: maximum supported number of data lanes

**Description**

Count DT "data-lanes" property elements and check for validity.
This variant uses endpoint specifier.

**Return**

* min..max - positive integer count of "data-lanes" elements
* -EINVAL - the "data-mapping" property is unsupported
* -ENODEV - the "data-mapping" property is missing

#### <a id="c-drm_of_get_dsi_bus"></a>`drm_of_get_dsi_bus()`

```c
struct mipi_dsi_host * drm_of_get_dsi_bus(struct device *dev)
```

find the DSI bus for a given device

**Parameters**

- `struct device *dev`: parent device of display (SPI, I2C)

**Description**

Gets parent DSI bus for a DSI device controlled through a bus other
than MIPI-DCS (SPI, I2C, etc.) using the Device Tree.

This function assumes that the device's port@0 is the DSI input.

Returns pointer to mipi_dsi_host if successful, -EINVAL if the
request is unsupported, -EPROBE_DEFER if the DSI host is found but
not available, or -ENODEV otherwise.


<a id="rst-legacy-plane-helper-reference"></a>

## Legacy Plane Helper Reference


This helper library contains helpers to implement primary plane support on
top of the normal CRTC configuration interface.
Since the legacy [`drm_mode_config_funcs.set_config`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_mode_config_funcs) interface ties the primary
plane together with the CRTC state this does not allow userspace to disable
the primary plane itself. The default primary plane only expose XRBG8888 and
ARGB8888 as valid pixel formats for the attached framebuffer.

Drivers are highly recommended to implement proper support for primary
planes, and newly merged drivers must not rely upon these transitional
helpers.

The plane helpers share the function table structures with other helpers,
specifically also the atomic helpers. See [`struct drm_plane_helper_funcs`](#c-struct-drm_plane_helper_funcs) for
the details.



#### <a id="c-drm_plane_helper_update_primary"></a>`drm_plane_helper_update_primary()`

```c
int drm_plane_helper_update_primary(struct drm_plane *plane, struct drm_crtc *crtc, struct drm_framebuffer *fb, int crtc_x, int crtc_y, unsigned int crtc_w, unsigned int crtc_h, uint32_t src_x, uint32_t src_y, uint32_t src_w, uint32_t src_h, struct drm_modeset_acquire_ctx *ctx)
```

Helper for updating primary planes

**Parameters**

- `struct drm_plane *plane`: plane to update
- `struct drm_crtc *crtc`: the plane's new CRTC
- `struct drm_framebuffer *fb`: the plane's new framebuffer
- `int crtc_x`: x coordinate within CRTC
- `int crtc_y`: y coordinate within CRTC
- `unsigned int crtc_w`: width coordinate within CRTC
- `unsigned int crtc_h`: height coordinate within CRTC
- `uint32_t src_x`: x coordinate within source
- `uint32_t src_y`: y coordinate within source
- `uint32_t src_w`: width coordinate within source
- `uint32_t src_h`: height coordinate within source
- `struct drm_modeset_acquire_ctx *ctx`: modeset locking context

**Description**

This helper validates the given parameters and updates the primary plane.

This function is only useful for non-atomic modesetting. Don't use
it in new drivers.

**Return**

Zero on success, or an errno code otherwise.

#### <a id="c-drm_plane_helper_disable_primary"></a>`drm_plane_helper_disable_primary()`

```c
int drm_plane_helper_disable_primary(struct drm_plane *plane, struct drm_modeset_acquire_ctx *ctx)
```

Helper for disabling primary planes

**Parameters**

- `struct drm_plane *plane`: plane to disable
- `struct drm_modeset_acquire_ctx *ctx`: modeset locking context

**Description**

This helper returns an error when trying to disable the primary
plane.

This function is only useful for non-atomic modesetting. Don't use
it in new drivers.

**Return**

An errno code.

#### <a id="c-drm_plane_helper_destroy"></a>`drm_plane_helper_destroy()`

```c
void drm_plane_helper_destroy(struct drm_plane *plane)
```

Helper for primary plane destruction

**Parameters**

- `struct drm_plane *plane`: plane to destroy

**Description**

Provides a default plane destroy handler for primary planes.  This handler
is called during CRTC destruction.  We disable the primary plane, remove
it from the DRM plane list, and deallocate the plane structure.


<a id="rst-legacy-crtc-modeset-helper-functions-reference"></a>

## Legacy CRTC/Modeset Helper Functions Reference


The CRTC modeset helper library provides a default set_config implementation
in [`drm_crtc_helper_set_config()`](#c-drm_crtc_helper_set_config). Plus a few other convenience functions using
the same callbacks which drivers can use to e.g. restore the modeset
configuration on resume with [`drm_helper_resume_force_mode()`](#c-drm_helper_resume_force_mode).

Note that this helper library doesn't track the current power state of CRTCs
and encoders. It can call callbacks like [`drm_encoder_helper_funcs.dpms`](#c-struct-drm_encoder_helper_funcs) even
though the hardware is already in the desired state. This deficiency has been
fixed in the atomic helpers.

The driver callbacks are mostly compatible with the atomic modeset helpers,
except for the handling of the primary plane: Atomic helpers require that the
primary plane is implemented as a real standalone plane and not directly tied
to the CRTC state. For easier transition this library provides functions to
implement the old semantics required by the CRTC helpers using the new plane
and atomic helper callbacks.

Drivers are strongly urged to convert to the atomic helpers (by way of first
converting to the plane helpers). New drivers must not use these functions
but need to implement the atomic interface instead, potentially using the
atomic helpers for that.

These legacy modeset helpers use the same function table structures as
all other modesetting helpers. See the documentation for struct
[`drm_crtc_helper_funcs`](#c-struct-drm_crtc_helper_funcs), [`struct drm_encoder_helper_funcs`](#c-struct-drm_encoder_helper_funcs) and struct
[`drm_connector_helper_funcs`](#c-struct-drm_connector_helper_funcs).



#### <a id="c-drm_helper_encoder_in_use"></a>`drm_helper_encoder_in_use()`

```c
bool drm_helper_encoder_in_use(struct drm_encoder *encoder)
```

check if a given encoder is in use

**Parameters**

- `struct drm_encoder *encoder`: encoder to check

**Description**

Checks whether **encoder** is with the current mode setting output configuration
in use by any connector. This doesn't mean that it is actually enabled since
the DPMS state is tracked separately.

**Return**

True if **encoder** is used, false otherwise.

#### <a id="c-drm_helper_crtc_in_use"></a>`drm_helper_crtc_in_use()`

```c
bool drm_helper_crtc_in_use(struct drm_crtc *crtc)
```

check if a given CRTC is in a mode_config

**Parameters**

- `struct drm_crtc *crtc`: CRTC to check

**Description**

Checks whether **crtc** is with the current mode setting output configuration
in use by any connector. This doesn't mean that it is actually enabled since
the DPMS state is tracked separately.

**Return**

True if **crtc** is used, false otherwise.

#### <a id="c-drm_helper_disable_unused_functions"></a>`drm_helper_disable_unused_functions()`

```c
void drm_helper_disable_unused_functions(struct drm_device *dev)
```

disable unused objects

**Parameters**

- `struct drm_device *dev`: DRM device

**Description**

This function walks through the entire mode setting configuration of **dev**. It
will remove any CRTC links of unused encoders and encoder links of
disconnected connectors. Then it will disable all unused encoders and CRTCs
either by calling their disable callback if available or by calling their
dpms callback with DRM_MODE_DPMS_OFF.

**NOTE**

This function is part of the legacy modeset helper library and will cause
major confusion with atomic drivers. This is because atomic helpers guarantee
to never call ->`disable()` hooks on a disabled function, or ->`enable()` hooks
on an enabled functions. [`drm_helper_disable_unused_functions()`](#c-drm_helper_disable_unused_functions) on the other
hand throws such guarantees into the wind and calls disable hooks
unconditionally on unused functions.

#### <a id="c-drm_crtc_helper_set_mode"></a>`drm_crtc_helper_set_mode()`

```c
bool drm_crtc_helper_set_mode(struct drm_crtc *crtc, struct drm_display_mode *mode, int x, int y, struct drm_framebuffer *old_fb)
```

internal helper to set a mode

**Parameters**

- `struct drm_crtc *crtc`: CRTC to program
- `struct drm_display_mode *mode`: mode to use
- `int x`: horizontal offset into the surface
- `int y`: vertical offset into the surface
- `struct drm_framebuffer *old_fb`: old framebuffer, for cleanup

**Description**

Try to set **mode** on **crtc**.  Give **crtc** and its associated connectors a chance
to fixup or reject the mode prior to trying to set it. This is an internal
helper that drivers could e.g. use to update properties that require the
entire output pipe to be disabled and re-enabled in a new configuration. For
example for changing whether audio is enabled on a hdmi link or for changing
panel fitter or dither attributes. It is also called by the
[`drm_crtc_helper_set_config()`](#c-drm_crtc_helper_set_config) helper function to drive the mode setting
sequence.

**Return**

True if the mode was set successfully, false otherwise.

#### <a id="c-drm_crtc_helper_atomic_check"></a>`drm_crtc_helper_atomic_check()`

```c
int drm_crtc_helper_atomic_check(struct drm_crtc *crtc, struct drm_atomic_state *state)
```

Helper to check CRTC atomic-state

**Parameters**

- `struct drm_crtc *crtc`: CRTC to check
- `struct drm_atomic_state *state`: atomic state object

**Description**

Provides a default CRTC-state check handler for CRTCs that only have
one primary plane attached to it. This is often the case for the CRTC
of simple framebuffers.

**Return**

Zero on success, or an errno code otherwise.

#### <a id="c-drm_crtc_helper_set_config"></a>`drm_crtc_helper_set_config()`

```c
int drm_crtc_helper_set_config(struct drm_mode_set *set, struct drm_modeset_acquire_ctx *ctx)
```

set a new config from userspace

**Parameters**

- `struct drm_mode_set *set`: mode set configuration
- `struct drm_modeset_acquire_ctx *ctx`: lock acquire context, not used here

**Description**

The [`drm_crtc_helper_set_config()`](#c-drm_crtc_helper_set_config) helper function implements the of
[`drm_crtc_funcs.set_config`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_crtc_funcs) callback for drivers using the legacy CRTC
helpers.

It first tries to locate the best encoder for each connector by calling the
connector **drm_connector_helper_funcs.best_encoder** helper operation.

After locating the appropriate encoders, the helper function will call the
mode_fixup encoder and CRTC helper operations to adjust the requested mode,
or reject it completely in which case an error will be returned to the
application. If the new configuration after mode adjustment is identical to
the current configuration the helper function will return without performing
any other operation.

If the adjusted mode is identical to the current mode but changes to the
frame buffer need to be applied, the [`drm_crtc_helper_set_config()`](#c-drm_crtc_helper_set_config) function
will call the CRTC [`drm_crtc_helper_funcs.mode_set_base`](#c-struct-drm_crtc_helper_funcs) helper operation.

If the adjusted mode differs from the current mode, or if the
->`mode_set_base()` helper operation is not provided, the helper function
performs a full mode set sequence by calling the ->`prepare()`, ->`mode_set()`
and ->`commit()` CRTC and encoder helper operations, in that order.
Alternatively it can also use the dpms and disable helper operations. For
details see [`struct drm_crtc_helper_funcs`](#c-struct-drm_crtc_helper_funcs) and struct
[`drm_encoder_helper_funcs`](#c-struct-drm_encoder_helper_funcs).

This function is deprecated.  New drivers must implement atomic modeset
support, for which this function is unsuitable. Instead drivers should use
[`drm_atomic_helper_set_config()`](#c-drm_atomic_helper_set_config).

**Return**

Returns 0 on success, negative errno numbers on failure.

#### <a id="c-drm_helper_connector_dpms"></a>`drm_helper_connector_dpms()`

```c
int drm_helper_connector_dpms(struct drm_connector *connector, int mode)
```

connector dpms helper implementation

**Parameters**

- `struct drm_connector *connector`: affected connector
- `int mode`: DPMS mode

**Description**

The [`drm_helper_connector_dpms()`](#c-drm_helper_connector_dpms) helper function implements the
[`drm_connector_funcs.dpms`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_connector_funcs) callback for drivers using the legacy CRTC
helpers.

This is the main helper function provided by the CRTC helper framework for
implementing the DPMS connector attribute. It computes the new desired DPMS
state for all encoders and CRTCs in the output mesh and calls the
[`drm_crtc_helper_funcs.dpms`](#c-struct-drm_crtc_helper_funcs) and [`drm_encoder_helper_funcs.dpms`](#c-struct-drm_encoder_helper_funcs) callbacks
provided by the driver.

This function is deprecated.  New drivers must implement atomic modeset
support, where DPMS is handled in the DRM core.

**Return**

Always returns 0.

#### <a id="c-drm_helper_resume_force_mode"></a>`drm_helper_resume_force_mode()`

```c
void drm_helper_resume_force_mode(struct drm_device *dev)
```

force-restore mode setting configuration

**Parameters**

- `struct drm_device *dev`: drm_device which should be restored

**Description**

Drivers which use the mode setting helpers can use this function to
force-restore the mode setting configuration e.g. on resume or when something
else might have trampled over the hw state (like some overzealous old BIOSen
tended to do).

This helper doesn't provide a error return value since restoring the old
config should never fail due to resource allocation issues since the driver
has successfully set the restored configuration already. Hence this should
boil down to the equivalent of a few dpms on calls, which also don't provide
an error code.

Drivers where simply restoring an old configuration again might fail (e.g.
due to slight differences in allocating shared resources when the
configuration is restored in a different order than when userspace set it up)
need to use their own restore logic.

This function is deprecated. New drivers should implement atomic mode-
setting and use the atomic suspend/resume helpers.

See also:
[`drm_atomic_helper_suspend()`](#c-drm_atomic_helper_suspend), [`drm_atomic_helper_resume()`](#c-drm_atomic_helper_resume)

#### <a id="c-drm_helper_force_disable_all"></a>`drm_helper_force_disable_all()`

```c
int drm_helper_force_disable_all(struct drm_device *dev)
```

Forcibly turn off all enabled CRTCs

**Parameters**

- `struct drm_device *dev`: DRM device whose CRTCs to turn off

**Description**

Drivers may want to call this on unload to ensure that all displays are
unlit and the GPU is in a consistent, low power state. Takes modeset locks.

**Note**

This should only be used by non-atomic legacy drivers. For an atomic
version look at [`drm_atomic_helper_shutdown()`](#c-drm_atomic_helper_shutdown).

**Return**

Zero on success, error code on failure.


<a id="rst-privacy-screen-class"></a>

## Privacy-screen class


This class allows non KMS drivers, from e.g. drivers/platform/x86 to
register a privacy-screen device, which the KMS drivers can then use
to implement the standard privacy-screen properties, see
Standard Connector Properties.

KMS drivers using a privacy-screen class device are advised to use the
[`drm_connector_attach_privacy_screen_provider()`](/kernel/hardware/gpu/drm-kms.md#c-drm_connector_attach_privacy_screen_provider) and
[`drm_connector_update_privacy_screen()`](/kernel/hardware/gpu/drm-kms.md#c-drm_connector_update_privacy_screen) helpers for dealing with this.



#### <a id="c-struct-drm_privacy_screen_ops"></a>`struct drm_privacy_screen_ops`

drm_privacy_screen operations

**Definition**

```c
struct drm_privacy_screen_ops {
    int (*set_sw_state)(struct drm_privacy_screen *priv, enum drm_privacy_screen_status sw_state);
    void (*get_hw_state)(struct drm_privacy_screen *priv);
};
```

**Members**

- `set_sw_state`: Called to request a change of the privacy-screen
  state. The privacy-screen class code contains a check to avoid this
  getting called when the hw_state reports the state is locked.
  It is the driver's responsibility to update sw_state and hw_state.
  This is always called with the drm_privacy_screen's lock held.
- `get_hw_state`: Called to request that the driver gets the current
  privacy-screen state from the hardware and then updates sw_state and
  hw_state accordingly. This will be called by the core just before
  the privacy-screen is registered in sysfs.

**Description**

Defines the operations which the privacy-screen class code may call.
These functions should be implemented by the privacy-screen driver.

#### <a id="c-struct-drm_privacy_screen"></a>`struct drm_privacy_screen`

central privacy-screen structure

**Definition**

```c
struct drm_privacy_screen {
    struct device dev;
    struct mutex lock;
    struct list_head list;
    struct blocking_notifier_head notifier_head;
    const struct drm_privacy_screen_ops *ops;
    enum drm_privacy_screen_status sw_state;
    enum drm_privacy_screen_status hw_state;
    void *drvdata;
};
```

**Members**

- `dev`: device used to register the privacy-screen in sysfs.
- `lock`: mutex protection all fields in this struct.
- `list`: privacy-screen devices list list-entry.
- `notifier_head`: privacy-screen notifier head.
- `ops`: [`struct drm_privacy_screen_ops`](#c-struct-drm_privacy_screen_ops) for this privacy-screen.
  This is NULL if the driver has unregistered the privacy-screen.
- `sw_state`: The privacy-screen's software state, see
  Standard Connector Properties
  for more info.
- `hw_state`: The privacy-screen's hardware state, see
  Standard Connector Properties
  for more info.
- `drvdata`: Private data owned by the privacy screen provider

**Description**

Central privacy-screen structure, this contains the struct device used
to register the screen in sysfs, the screen's state, ops, etc.



#### <a id="c-struct-drm_privacy_screen_lookup"></a>`struct drm_privacy_screen_lookup`

static privacy-screen lookup list entry

**Definition**

```c
struct drm_privacy_screen_lookup {
    struct list_head list;
    const char *dev_id;
    const char *con_id;
    const char *provider;
};
```

**Members**

- `list`: Lookup list list-entry.
- `dev_id`: Consumer device name or NULL to match all devices.
- `con_id`: Consumer connector name or NULL to match all connectors.
- `provider`: [`dev_name()`](/kernel/hardware/driver-api/fundamentals/infrastructure.md#c-dev_name) of the privacy_screen provider.

**Description**

Used for the static lookup-list for mapping privacy-screen consumer
dev-connector pairs to a privacy-screen provider.



#### <a id="c-drm_privacy_screen_lookup_add"></a>`drm_privacy_screen_lookup_add()`

```c
void drm_privacy_screen_lookup_add(struct drm_privacy_screen_lookup *lookup)
```

add an entry to the static privacy-screen lookup list

**Parameters**

- `struct drm_privacy_screen_lookup *lookup`: lookup list entry to add

**Description**

Add an entry to the static privacy-screen lookup list. Note the
`struct list_head` which is part of the [`struct drm_privacy_screen_lookup`](#c-struct-drm_privacy_screen_lookup)
gets added to a list owned by the privacy-screen core. So the passed in
[`struct drm_privacy_screen_lookup`](#c-struct-drm_privacy_screen_lookup) must not be free-ed until it is removed
from the lookup list by calling [`drm_privacy_screen_lookup_remove()`](#c-drm_privacy_screen_lookup_remove).

#### <a id="c-drm_privacy_screen_lookup_remove"></a>`drm_privacy_screen_lookup_remove()`

```c
void drm_privacy_screen_lookup_remove(struct drm_privacy_screen_lookup *lookup)
```

remove an entry to the static privacy-screen lookup list

**Parameters**

- `struct drm_privacy_screen_lookup *lookup`: lookup list entry to remove

**Description**

Remove an entry previously added with [`drm_privacy_screen_lookup_add()`](#c-drm_privacy_screen_lookup_add)
from the static privacy-screen lookup list.

#### <a id="c-drm_privacy_screen_get"></a>`drm_privacy_screen_get()`

```c
struct drm_privacy_screen * drm_privacy_screen_get(struct device *dev, const char *con_id)
```

get a privacy-screen provider

**Parameters**

- `struct device *dev`: consumer-device for which to get a privacy-screen provider
- `const char *con_id`: (video)connector name for which to get a privacy-screen provider

**Description**

Get a privacy-screen provider for a privacy-screen attached to the
display described by the **dev** and **con_id** parameters.

**Return**

* A pointer to a [`struct drm_privacy_screen`](#c-struct-drm_privacy_screen) on success.
* ERR_PTR(-ENODEV) if no matching privacy-screen is found
* ERR_PTR(-EPROBE_DEFER) if there is a matching privacy-screen,
  but it has not been registered yet.

#### <a id="c-drm_privacy_screen_put"></a>`drm_privacy_screen_put()`

```c
void drm_privacy_screen_put(struct drm_privacy_screen *priv)
```

release a privacy-screen reference

**Parameters**

- `struct drm_privacy_screen *priv`: privacy screen reference to release

**Description**

Release a privacy-screen provider reference gotten through
[`drm_privacy_screen_get()`](#c-drm_privacy_screen_get). May be called with a NULL or ERR_PTR,
in which case it is a no-op.

#### <a id="c-drm_privacy_screen_set_sw_state"></a>`drm_privacy_screen_set_sw_state()`

```c
int drm_privacy_screen_set_sw_state(struct drm_privacy_screen *priv, enum drm_privacy_screen_status sw_state)
```

set a privacy-screen's sw-state

**Parameters**

- `struct drm_privacy_screen *priv`: privacy screen to set the sw-state for
- `enum drm_privacy_screen_status sw_state`: new sw-state value to set

**Description**

Set the sw-state of a privacy screen. If the privacy-screen is not
in a locked hw-state, then the actual and hw-state of the privacy-screen
will be immediately updated to the new value. If the privacy-screen is
in a locked hw-state, then the new sw-state will be remembered as the
requested state to put the privacy-screen in when it becomes unlocked.

**Return**

0 on success, negative error code on failure.

#### <a id="c-drm_privacy_screen_get_state"></a>`drm_privacy_screen_get_state()`

```c
void drm_privacy_screen_get_state(struct drm_privacy_screen *priv, enum drm_privacy_screen_status *sw_state_ret, enum drm_privacy_screen_status *hw_state_ret)
```

get privacy-screen's current state

**Parameters**

- `struct drm_privacy_screen *priv`: privacy screen to get the state for
- `enum drm_privacy_screen_status *sw_state_ret`: address where to store the privacy-screens current sw-state
- `enum drm_privacy_screen_status *hw_state_ret`: address where to store the privacy-screens current hw-state

**Description**

Get the current state of a privacy-screen, both the sw-state and the
hw-state.

#### <a id="c-drm_privacy_screen_register_notifier"></a>`drm_privacy_screen_register_notifier()`

```c
int drm_privacy_screen_register_notifier(struct drm_privacy_screen *priv, struct notifier_block *nb)
```

register a notifier

**Parameters**

- `struct drm_privacy_screen *priv`: Privacy screen to register the notifier with
- `struct notifier_block *nb`: Notifier-block for the notifier to register

**Description**

Register a notifier with the privacy-screen to be notified of changes made
to the privacy-screen state from outside of the privacy-screen class.
E.g. the state may be changed by the hardware itself in response to a
hotkey press.

The notifier is called with no locks held. The new hw_state and sw_state
can be retrieved using the [`drm_privacy_screen_get_state()`](#c-drm_privacy_screen_get_state) function.
A pointer to the drm_privacy_screen's struct is passed as the `void *data`
argument of the notifier_block's notifier_call.

The notifier will NOT be called when changes are made through
[`drm_privacy_screen_set_sw_state()`](#c-drm_privacy_screen_set_sw_state). It is only called for external changes.

**Return**

0 on success, negative error code on failure.

#### <a id="c-drm_privacy_screen_unregister_notifier"></a>`drm_privacy_screen_unregister_notifier()`

```c
int drm_privacy_screen_unregister_notifier(struct drm_privacy_screen *priv, struct notifier_block *nb)
```

unregister a notifier

**Parameters**

- `struct drm_privacy_screen *priv`: Privacy screen to register the notifier with
- `struct notifier_block *nb`: Notifier-block for the notifier to register

**Description**

Unregister a notifier registered with [`drm_privacy_screen_register_notifier()`](#c-drm_privacy_screen_register_notifier).

**Return**

0 on success, negative error code on failure.

#### <a id="c-drm_privacy_screen_register"></a>`drm_privacy_screen_register()`

```c
struct drm_privacy_screen * drm_privacy_screen_register(struct device *parent, const struct drm_privacy_screen_ops *ops, void *data)
```

register a privacy-screen

**Parameters**

- `struct device *parent`: parent-device for the privacy-screen
- `const struct drm_privacy_screen_ops *ops`: [`struct drm_privacy_screen_ops`](#c-struct-drm_privacy_screen_ops) pointer with ops for the privacy-screen
- `void *data`: Private data owned by the privacy screen provider

**Description**

Create and register a privacy-screen.

**Return**

* A pointer to the created privacy-screen on success.
* An ERR_PTR(errno) on failure.

#### <a id="c-drm_privacy_screen_unregister"></a>`drm_privacy_screen_unregister()`

```c
void drm_privacy_screen_unregister(struct drm_privacy_screen *priv)
```

unregister privacy-screen

**Parameters**

- `struct drm_privacy_screen *priv`: privacy-screen to unregister

**Description**

Unregister a privacy-screen registered with [`drm_privacy_screen_register()`](#c-drm_privacy_screen_register).
May be called with a NULL or ERR_PTR, in which case it is a no-op.

#### <a id="c-drm_privacy_screen_call_notifier_chain"></a>`drm_privacy_screen_call_notifier_chain()`

```c
void drm_privacy_screen_call_notifier_chain(struct drm_privacy_screen *priv)
```

notify consumers of state change

**Parameters**

- `struct drm_privacy_screen *priv`: Privacy screen to register the notifier with

**Description**

A privacy-screen provider driver can call this functions upon external
changes to the privacy-screen state. E.g. the state may be changed by the
hardware itself in response to a hotkey press.
This function must be called without holding the privacy-screen lock.
the driver must update sw_state and hw_state to reflect the new state before
calling this function.
The expected behavior from the driver upon receiving an external state
change event is: 1. Take the lock; 2. Update sw_state and hw_state;
3. Release the lock. 4. Call [`drm_privacy_screen_call_notifier_chain()`](#c-drm_privacy_screen_call_notifier_chain).

---

# Kernel Mode Setting (KMS)

_Peios Kernel / Hardware and drivers / Graphics_

> Drivers must initialize the mode setting core by calling drmm_mode_config_init() on the DRM device. The function initializes the struct drm_device <drm_device> mode_config field and never fails. Once done, mode configuration must be setup…

<a id="rst-kernel-mode-setting-kms"></a>

Drivers must initialize the mode setting core by calling drmm\_mode\_config\_init() on the DRM device. The function initializes the `struct drm_device <drm_device>` mode\_config field and never fails. Once done, mode configuration must be setup by initializing the following fields.

- int min\_width, min\_height; int max\_width, max\_height; Minimum and maximum width and height of the frame buffers in pixel units.

- struct drm\_mode\_config\_funcs \*funcs; Mode setting functions.

<a id="rst-overview"></a>

## Overview

```mermaid
flowchart TB
  subgraph g0["Static Objects"]
    n0["drm_plane A"]
    n1["drm_crtc"]
    n2["drm_plane B"]
    n3["drm_encoder A"]
    n4["drm_encoder B"]
  end
  subgraph g1["Userspace-Created"]
    n5(["drm_framebuffer 1"])
    n6(["drm_framebuffer 2"])
  end
  subgraph g2["Hotpluggable"]
    n7["drm_connector A"]
    n8["drm_connector B"]
  end
  n0 --> n1
  n2 --> n1
  n1 --> n3
  n1 --> n4
  n5 --> n0
  n6 --> n2
  n3 --> n7
  n4 --> n8
  style g0 stroke-dasharray:6 4
  style g1 stroke-dasharray:6 4
  style g2 stroke-dasharray:6 4
```

KMS Display Pipeline

KMS Display Pipeline Overview

The basic object structure KMS presents to userspace is fairly simple. Framebuffers (represented by `struct drm_framebuffer <drm_framebuffer>`, see [Frame Buffer Abstraction](<#rst-frame-buffer-abstraction>)) feed into planes. Planes are represented by `struct drm_plane <drm_plane>`, see [Plane Abstraction](<#rst-plane-abstraction>) for more details. One or more (or even no) planes feed their pixel data into a CRTC (represented by `struct drm_crtc <drm_crtc>`, see [CRTC Abstraction](<#rst-crtc-abstraction>)) for blending. The precise blending step is explained in more detail in [Plane Composition Properties](<#rst-plane-composition-properties-1>) and related chapters.

For the output routing the first step is encoders (represented by `struct drm_encoder <drm_encoder>`, see [Encoder Abstraction](<#rst-encoder-abstraction>)). Those are really just internal artifacts of the helper libraries used to implement KMS drivers. Besides that they make it unnecessarily more complicated for userspace to figure out which connections between a CRTC and a connector are possible, and what kind of cloning is supported, they serve no purpose in the userspace API. Unfortunately encoders have been exposed to userspace, hence can't remove them at this point.  Furthermore the exposed restrictions are often wrongly set by drivers, and in many cases not powerful enough to express the real restrictions. A CRTC can be connected to multiple encoders, and for an active CRTC there must be at least one encoder.

The final, and real, endpoint in the display chain is the connector (represented by `struct drm_connector <drm_connector>`, see [Connector Abstraction](<#rst-connector-abstraction>)). Connectors can have different possible encoders, but the kernel driver selects which encoder to use for each connector. The use case is DVI, which could switch between an analog and a digital encoder. Encoders can also drive multiple different connectors. There is exactly one active connector for every active encoder.

Internally the output pipeline is a bit more complex and matches today's hardware more closely:

```mermaid
flowchart TB
  n0["drm_crtc"]
  subgraph g0["Internal Pipeline"]
    n1["drm_encoder A"]
    n2["drm_encoder B"]
    n3["drm_encoder C"]
    n4["drm_bridge B"]
    n5["drm_bridge C1"]
    n6["drm_bridge C2"]
  end
  subgraph g1["Outputs"]
    n7["drm_connector A"]
    n8["drm_connector B"]
    n9["drm_connector C"]
    n10["drm_panel"]
  end
  n2 --> n4
  n3 --> n5
  n5 --> n6
  n0 --> n1
  n0 --> n2
  n0 --> n3
  n1 --> n7
  n4 --> n8
  n6 --> n9
  style g0 stroke-dasharray:6 4
  style g1 stroke-dasharray:6 4
```

KMS Output Pipeline

KMS Output Pipeline

Internally two additional helper objects come into play. First, to be able to share code for encoders (sometimes on the same SoC, sometimes off-chip) one or more [drm\_bridges](</kernel/hardware/gpu/drm-kms-helpers.md#rst-drm-bridges>) (represented by `struct drm_bridge <drm_bridge>`) can be linked to an encoder. This link is static and cannot be changed, which means the cross-bar (if there is any) needs to be mapped between the CRTC and any encoders. Often for drivers with bridges there's no code left at the encoder level. Atomic drivers can leave out all the encoder callbacks to essentially only leave a dummy routing object behind, which is needed for backwards compatibility since encoders are exposed to userspace.

The second object is for panels, represented by `struct drm_panel <drm_panel>`, see [drm\_panel\_helper](</kernel/hardware/gpu/drm-kms-helpers.md#rst-drm-panel-helper>). Panels do not have a fixed binding point, but are generally linked to the driver private structure that embeds `struct drm_connector <drm_connector>`.

Note that currently the bridge chaining and interactions with connectors and panels are still in-flux and not really fully sorted out yet.

<a id="rst-kms-core-structures-and-functions"></a>

## KMS Core Structures and Functions


#### <a id="c-struct-drm_mode_config_funcs"></a>`struct drm_mode_config_funcs`

basic driver provided mode setting functions

**Definition**

```c
struct drm_mode_config_funcs {
    struct drm_framebuffer *(*fb_create)(struct drm_device *dev, struct drm_file *file_priv, const struct drm_format_info *info, const struct drm_mode_fb_cmd2 *mode_cmd);
    const struct drm_format_info *(*get_format_info)(u32 pixel_format, u64 modifier);
    enum drm_mode_status (*mode_valid)(struct drm_device *dev, const struct drm_display_mode *mode);
    int (*atomic_check)(struct drm_device *dev, struct drm_atomic_state *state);
    int (*atomic_commit)(struct drm_device *dev, struct drm_atomic_state *state, bool nonblock);
    struct drm_atomic_state *(*atomic_state_alloc)(struct drm_device *dev);
    void (*atomic_state_clear)(struct drm_atomic_state *state);
    void (*atomic_state_free)(struct drm_atomic_state *state);
};
```

**Members**

- `fb_create`: Create a new framebuffer object. The core does basic checks on the
  requested metadata, but most of that is left to the driver. See
  [`struct drm_mode_fb_cmd2`](/kernel/hardware/gpu/drm-uapi.md#c-struct-drm_mode_fb_cmd2) for details.

  To validate the pixel format and modifier drivers can use
  [`drm_any_plane_has_format()`](#c-drm_any_plane_has_format) to make sure at least one plane supports
  the requested values. Note that the driver must first determine the
  actual modifier used if the request doesn't have it specified,
  ie. when (**mode_cmd->flags** & DRM_MODE_FB_MODIFIERS) == 0.

  IMPORTANT: These implied modifiers for legacy userspace must be
  stored in struct [`drm_framebuffer`](#c-struct-drm_framebuffer), including all relevant metadata
  like [`drm_framebuffer.pitches`](#c-struct-drm_framebuffer) and [`drm_framebuffer.offsets`](#c-struct-drm_framebuffer) if the
  modifier enables additional planes beyond the fourcc pixel format
  code. This is required by the GETFB2 ioctl.

  If the parameters are deemed valid and the backing storage objects in
  the underlying memory manager all exist, then the driver allocates
  a new [`drm_framebuffer`](#c-struct-drm_framebuffer) structure, subclassed to contain
  driver-specific information (like the internal native buffer object
  references). It also needs to fill out all relevant metadata, which
  should be done by calling [`drm_helper_mode_fill_fb_struct()`](/kernel/hardware/gpu/drm-kms-helpers.md#c-drm_helper_mode_fill_fb_struct).

  The initialization is finalized by calling [`drm_framebuffer_init()`](#c-drm_framebuffer_init),
  which registers the framebuffer and makes it accessible to other
  threads.

  RETURNS:

  A new framebuffer with an initial reference count of 1 or a negative
  error code encoded with [`ERR_PTR()`](/kernel/internals/core-api/kernel-api.md#c-ERR_PTR).
- `get_format_info`: Allows a driver to return custom format information for special
  fb layouts (eg. ones with auxiliary compression control planes).

  RETURNS:

  The format information specific to the given fb metadata, or
  NULL if none is found.
- `mode_valid`: Device specific validation of display modes. Can be used to reject
  modes that can never be supported. Only device wide constraints can
  be checked here. crtc/encoder/bridge/connector specific constraints
  should be checked in the .`mode_valid()` hook for each specific object.
- `atomic_check`: This is the only hook to validate an atomic modeset update. This
  function must reject any modeset and state changes which the hardware
  or driver doesn't support. This includes but is of course not limited
  to:

  - Checking that the modes, framebuffers, scaling and placement
    requirements and so on are within the limits of the hardware.

  - Checking that any hidden shared resources are not oversubscribed.
    This can be shared PLLs, shared lanes, overall memory bandwidth,
    display fifo space (where shared between planes or maybe even
    CRTCs).

  - Checking that virtualized resources exported to userspace are not
    oversubscribed. For various reasons it can make sense to expose
    more planes, crtcs or encoders than which are physically there. One
    example is dual-pipe operations (which generally should be hidden
    from userspace if when lockstepped in hardware, exposed otherwise),
    where a plane might need 1 hardware plane (if it's just on one
    pipe), 2 hardware planes (when it spans both pipes) or maybe even
    shared a hardware plane with a 2nd plane (if there's a compatible
    plane requested on the area handled by the other pipe).

  - Check that any transitional state is possible and that if
    requested, the update can indeed be done in the vblank period
    without temporarily disabling some functions.

  - Check any other constraints the driver or hardware might have.

  - This callback also needs to correctly fill out the [`drm_crtc_state`](#c-struct-drm_crtc_state)
    in this update to make sure that [`drm_atomic_crtc_needs_modeset()`](#c-drm_atomic_crtc_needs_modeset)
    reflects the nature of the possible update and returns true if and
    only if the update cannot be applied without tearing within one
    vblank on that CRTC. The core uses that information to reject
    updates which require a full modeset (i.e. blanking the screen, or
    at least pausing updates for a substantial amount of time) if
    userspace has disallowed that in its request.

  - The driver also does not need to repeat basic input validation
    like done for the corresponding legacy entry points. The core does
    that before calling this hook.

  See the documentation of **atomic_commit** for an exhaustive list of
  error conditions which don't have to be checked at the in this
  callback.

  See the documentation for [`struct drm_atomic_state`](#c-struct-drm_atomic_state) for how exactly
  an atomic modeset update is described.

  Drivers using the atomic helpers can implement this hook using
  [`drm_atomic_helper_check()`](/kernel/hardware/gpu/drm-kms-helpers.md#c-drm_atomic_helper_check), or one of the exported sub-functions of
  it.

  RETURNS:

  0 on success or one of the below negative error codes:

  - -EINVAL, if any of the above constraints are violated.

  - -EDEADLK, when returned from an attempt to acquire an additional
    [`drm_modeset_lock`](#c-drm_modeset_lock) through [`drm_modeset_lock()`](#c-drm_modeset_lock).

  - -ENOMEM, if allocating additional state sub-structures failed due
    to lack of memory.

  - -EINTR, -EAGAIN or -ERESTARTSYS, if the IOCTL should be restarted.
    This can either be due to a pending signal, or because the driver
    needs to completely bail out to recover from an exceptional
    situation like a GPU hang. From a userspace point all errors are
    treated equally.
- `atomic_commit`: This is the only hook to commit an atomic modeset update. The core
  guarantees that **atomic_check** has been called successfully before
  calling this function, and that nothing has been changed in the
  interim.

  See the documentation for [`struct drm_atomic_state`](#c-struct-drm_atomic_state) for how exactly
  an atomic modeset update is described.

  Drivers using the atomic helpers can implement this hook using
  [`drm_atomic_helper_commit()`](/kernel/hardware/gpu/drm-kms-helpers.md#c-drm_atomic_helper_commit), or one of the exported sub-functions of
  it.

  Nonblocking commits (as indicated with the nonblock parameter) must
  do any preparatory work which might result in an unsuccessful commit
  in the context of this callback. The only exceptions are hardware
  errors resulting in -EIO. But even in that case the driver must
  ensure that the display pipe is at least running, to avoid
  compositors crashing when pageflips don't work. Anything else,
  specifically committing the update to the hardware, should be done
  without blocking the caller. For updates which do not require a
  modeset this must be guaranteed.

  The driver must wait for any pending rendering to the new
  framebuffers to complete before executing the flip. It should also
  wait for any pending rendering from other drivers if the underlying
  buffer is a shared dma-buf. Nonblocking commits must not wait for
  rendering in the context of this callback.

  An application can request to be notified when the atomic commit has
  completed. These events are per-CRTC and can be distinguished by the
  CRTC index supplied in [`drm_event`](/kernel/hardware/gpu/drm-uapi.md#c-struct-drm_event) to userspace.

  The drm core will supply a [`struct drm_event`](/kernel/hardware/gpu/drm-uapi.md#c-struct-drm_event) in each CRTC's
  [`drm_crtc_state.event`](#c-struct-drm_crtc_state). See the documentation for
  [`drm_crtc_state.event`](#c-struct-drm_crtc_state) for more details about the precise semantics of
  this event.

  NOTE:

  Drivers are not allowed to shut down any display pipe successfully
  enabled through an atomic commit on their own. Doing so can result in
  compositors crashing if a page flip is suddenly rejected because the
  pipe is off.

  RETURNS:

  0 on success or one of the below negative error codes:

  - -EBUSY, if a nonblocking updated is requested and there is
    an earlier updated pending. Drivers are allowed to support a queue
    of outstanding updates, but currently no driver supports that.
    Note that drivers must wait for preceding updates to complete if a
    synchronous update is requested, they are not allowed to fail the
    commit in that case.

  - -ENOMEM, if the driver failed to allocate memory. Specifically
    this can happen when trying to pin framebuffers, which must only
    be done when committing the state.

  - -ENOSPC, as a refinement of the more generic -ENOMEM to indicate
    that the driver has run out of vram, iommu space or similar GPU
    address space needed for framebuffer.

  - -EIO, if the hardware completely died.

  - -EINTR, -EAGAIN or -ERESTARTSYS, if the IOCTL should be restarted.
    This can either be due to a pending signal, or because the driver
    needs to completely bail out to recover from an exceptional
    situation like a GPU hang. From a userspace point of view all errors are
    treated equally.

  This list is exhaustive. Specifically this hook is not allowed to
  return -EINVAL (any invalid requests should be caught in
  **atomic_check**) or -EDEADLK (this function must not acquire
  additional modeset locks).
- `atomic_state_alloc`: This optional hook can be used by drivers that want to subclass struct
  [`drm_atomic_state`](#c-struct-drm_atomic_state) to be able to track their own driver-private global
  state easily. If this hook is implemented, drivers must also
  implement **atomic_state_clear** and **atomic_state_free**.

  Subclassing of [`drm_atomic_state`](#c-struct-drm_atomic_state) is deprecated in favour of using
  [`drm_private_state`](#c-struct-drm_private_state) and [`drm_private_obj`](#c-struct-drm_private_obj).

  RETURNS:

  A new [`drm_atomic_state`](#c-struct-drm_atomic_state) on success or NULL on failure.
- `atomic_state_clear`: This hook must clear any driver private state duplicated into the
  passed-in [`drm_atomic_state`](#c-struct-drm_atomic_state). This hook is called when the caller
  encountered a [`drm_modeset_lock`](#c-drm_modeset_lock) deadlock and needs to drop all
  already acquired locks as part of the deadlock avoidance dance
  implemented in [`drm_modeset_backoff()`](#c-drm_modeset_backoff).

  Any duplicated state must be invalidated since a concurrent atomic
  update might change it, and the drm atomic interfaces always apply
  updates as relative changes to the current state.

  Drivers that implement this must call [`drm_atomic_state_default_clear()`](#c-drm_atomic_state_default_clear)
  to clear common state.

  Subclassing of [`drm_atomic_state`](#c-struct-drm_atomic_state) is deprecated in favour of using
  [`drm_private_state`](#c-struct-drm_private_state) and [`drm_private_obj`](#c-struct-drm_private_obj).
- `atomic_state_free`: This hook needs driver private resources and the [`drm_atomic_state`](#c-struct-drm_atomic_state)
  itself. Note that the core first calls [`drm_atomic_state_clear()`](#c-drm_atomic_state_clear) to
  avoid code duplicate between the clear and free hooks.

  Drivers that implement this must call
  [`drm_atomic_state_default_release()`](#c-drm_atomic_state_default_release) to release common resources.

  Subclassing of [`drm_atomic_state`](#c-struct-drm_atomic_state) is deprecated in favour of using
  [`drm_private_state`](#c-struct-drm_private_state) and [`drm_private_obj`](#c-struct-drm_private_obj).

**Description**

Some global (i.e. not per-CRTC, connector, etc) mode setting functions that
involve drivers.

#### <a id="c-struct-drm_mode_config"></a>`struct drm_mode_config`

Mode configuration control structure

**Definition**

```c
struct drm_mode_config {
    struct mutex mutex;
    struct drm_modeset_lock connection_mutex;
    struct drm_modeset_acquire_ctx *acquire_ctx;
    struct mutex idr_mutex;
    struct idr object_idr;
    struct idr tile_idr;
    struct mutex fb_lock;
    int num_fb;
    struct list_head fb_list;
    spinlock_t connector_list_lock;
    int num_connector;
    struct ida connector_ida;
    struct list_head connector_list;
    struct llist_head connector_free_list;
    struct work_struct connector_free_work;
    int num_encoder;
    struct list_head encoder_list;
    int num_total_plane;
    struct list_head plane_list;
    struct raw_spinlock panic_lock;
    int num_colorop;
    struct list_head colorop_list;
    int num_crtc;
    struct list_head crtc_list;
    struct list_head property_list;
    struct list_head privobj_list;
    unsigned int min_width, min_height;
    unsigned int max_width, max_height;
    const struct drm_mode_config_funcs *funcs;
    bool poll_enabled;
    bool poll_running;
    bool delayed_event;
    struct delayed_work output_poll_work;
    struct mutex blob_lock;
    struct list_head property_blob_list;
    struct drm_property *edid_property;
    struct drm_property *dpms_property;
    struct drm_property *path_property;
    struct drm_property *tile_property;
    struct drm_property *link_status_property;
    struct drm_property *plane_type_property;
    struct drm_property *prop_src_x;
    struct drm_property *prop_src_y;
    struct drm_property *prop_src_w;
    struct drm_property *prop_src_h;
    struct drm_property *prop_crtc_x;
    struct drm_property *prop_crtc_y;
    struct drm_property *prop_crtc_w;
    struct drm_property *prop_crtc_h;
    struct drm_property *prop_fb_id;
    struct drm_property *prop_in_fence_fd;
    struct drm_property *prop_out_fence_ptr;
    struct drm_property *prop_crtc_id;
    struct drm_property *prop_fb_damage_clips;
    struct drm_property *prop_active;
    struct drm_property *prop_mode_id;
    struct drm_property *prop_vrr_enabled;
    struct drm_property *dvi_i_subconnector_property;
    struct drm_property *dvi_i_select_subconnector_property;
    struct drm_property *dp_subconnector_property;
    struct drm_property *tv_subconnector_property;
    struct drm_property *tv_select_subconnector_property;
    struct drm_property *legacy_tv_mode_property;
    struct drm_property *tv_mode_property;
    struct drm_property *tv_left_margin_property;
    struct drm_property *tv_right_margin_property;
    struct drm_property *tv_top_margin_property;
    struct drm_property *tv_bottom_margin_property;
    struct drm_property *tv_brightness_property;
    struct drm_property *tv_contrast_property;
    struct drm_property *tv_flicker_reduction_property;
    struct drm_property *tv_overscan_property;
    struct drm_property *tv_saturation_property;
    struct drm_property *tv_hue_property;
    struct drm_property *scaling_mode_property;
    struct drm_property *aspect_ratio_property;
    struct drm_property *content_type_property;
    struct drm_property *degamma_lut_property;
    struct drm_property *degamma_lut_size_property;
    struct drm_property *ctm_property;
    struct drm_property *gamma_lut_property;
    struct drm_property *gamma_lut_size_property;
    struct drm_property *suggested_x_property;
    struct drm_property *suggested_y_property;
    struct drm_property *non_desktop_property;
    struct drm_property *panel_orientation_property;
    struct drm_property *writeback_fb_id_property;
    struct drm_property *writeback_pixel_formats_property;
    struct drm_property *writeback_out_fence_ptr_property;
    struct drm_property *hdr_output_metadata_property;
    struct drm_property *content_protection_property;
    struct drm_property *hdcp_content_type_property;
    uint32_t preferred_depth, prefer_shadow;
    bool quirk_addfb_prefer_xbgr_30bpp;
    bool quirk_addfb_prefer_host_byte_order;
    bool async_page_flip;
    bool fb_modifiers_not_supported;
    bool normalize_zpos;
    struct drm_property *modifiers_property;
    struct drm_property *async_modifiers_property;
    struct drm_property *size_hints_property;
    uint32_t cursor_width, cursor_height;
    struct drm_atomic_state *suspend_state;
    const struct drm_mode_config_helper_funcs *helper_private;
};
```

**Members**

- `mutex`: This is the big scary modeset BKL which protects everything that
  isn't protect otherwise. Scope is unclear and fuzzy, try to remove
  anything from under its protection and move it into more well-scoped
  locks.

  The one important thing this protects is the use of **acquire_ctx**.
- `connection_mutex`: This protects connector state and the connector to encoder to CRTC
  routing chain.

  For atomic drivers specifically this protects [`drm_connector.state`](#c-struct-drm_connector).
- `acquire_ctx`: Global implicit acquire context used by atomic drivers for legacy
  IOCTLs. Deprecated, since implicit locking contexts make it
  impossible to use driver-private [`struct drm_modeset_lock`](#c-struct-drm_modeset_lock). Users of
  this must hold **mutex**.
- `idr_mutex`: Mutex for KMS ID allocation and management. Protects both **object_idr**
  and **tile_idr**.
- `object_idr`: Main KMS ID tracking object. Use this idr for all IDs, fb, crtc,
  connector, modes - just makes life easier to have only one.
- `tile_idr`: Use this idr for allocating new IDs for tiled sinks like use in some
  high-res DP MST screens.
- `fb_lock`: Mutex to protect fb the global **fb_list** and **num_fb**.
- `num_fb`: Number of entries on **fb_list**.
- `fb_list`: List of all [`struct drm_framebuffer`](#c-struct-drm_framebuffer).
- `connector_list_lock`: Protects **num_connector** and
  **connector_list** and **connector_free_list**.
- `num_connector`: Number of connectors on this device. Protected by
  **connector_list_lock**.
- `connector_ida`: ID allocator for connector indices.
- `connector_list`: List of connector objects linked with [`drm_connector.head`](#c-struct-drm_connector). Protected
  by **connector_list_lock**. Only use [`drm_for_each_connector_iter()`](#c-drm_for_each_connector_iter) and
  [`struct drm_connector_list_iter`](#c-struct-drm_connector_list_iter) to walk this list.
- `connector_free_list`: List of connector objects linked with [`drm_connector.free_head`](#c-struct-drm_connector).
  Protected by **connector_list_lock**. Used by
  [`drm_for_each_connector_iter()`](#c-drm_for_each_connector_iter) and
  [`struct drm_connector_list_iter`](#c-struct-drm_connector_list_iter) to savely free connectors using
  **connector_free_work**.
- `connector_free_work`: Work to clean up **connector_free_list**.
- `num_encoder`: Number of encoders on this device. This is invariant over the
  lifetime of a device and hence doesn't need any locks.
- `encoder_list`: List of encoder objects linked with [`drm_encoder.head`](#c-struct-drm_encoder). This is
  invariant over the lifetime of a device and hence doesn't need any
  locks.
- `num_total_plane`: Number of universal (i.e. with primary/curso) planes on this device.
  This is invariant over the lifetime of a device and hence doesn't
  need any locks.
- `plane_list`: List of plane objects linked with [`drm_plane.head`](#c-struct-drm_plane). This is invariant
  over the lifetime of a device and hence doesn't need any locks.
- `panic_lock`: Raw spinlock used to protect critical sections of code that access
  the display hardware or modeset software state, which the panic
  printing code must be protected against. See [`drm_panic_trylock()`](#c-drm_panic_trylock),
  [`drm_panic_lock()`](#c-drm_panic_lock) and [`drm_panic_unlock()`](#c-drm_panic_unlock).
- `num_colorop`: Number of colorop objects on this device.
  This is invariant over the lifetime of a device and hence doesn't
  need any locks.
- `colorop_list`: List of colorop objects linked with [`drm_colorop.head`](#c-struct-drm_colorop). This is
  invariant over the lifetime of a device and hence doesn't need any
  locks.
- `num_crtc`: Number of CRTCs on this device linked with [`drm_crtc.head`](#c-struct-drm_crtc). This is invariant over the lifetime
  of a device and hence doesn't need any locks.
- `crtc_list`: List of CRTC objects linked with [`drm_crtc.head`](#c-struct-drm_crtc). This is invariant
  over the lifetime of a device and hence doesn't need any locks.
- `property_list`: List of property type objects linked with [`drm_property.head`](#c-struct-drm_property). This is
  invariant over the lifetime of a device and hence doesn't need any
  locks.
- `privobj_list`: List of private objects linked with [`drm_private_obj.head`](#c-struct-drm_private_obj). This is
  invariant over the lifetime of a device and hence doesn't need any
  locks.
- `min_width`: minimum fb pixel width on this device
- `min_height`: minimum fb pixel height on this device
- `max_width`: maximum fb pixel width on this device
- `max_height`: maximum fb pixel height on this device
- `funcs`: core driver provided mode setting functions
- `poll_enabled`: track polling support for this device
- `poll_running`: track polling status for this device
- `delayed_event`: track delayed poll uevent deliver for this device
- `output_poll_work`: delayed work for polling in process context
- `blob_lock`: Mutex for blob property allocation and management, protects
  **property_blob_list** and [`drm_file.blobs`](/kernel/hardware/gpu/drm-internals.md#c-struct-drm_file).
- `property_blob_list`: List of all the blob property objects linked with
  [`drm_property_blob.head`](#c-struct-drm_property_blob). Protected by **blob_lock**.
- `edid_property`: Default connector property to hold the EDID of the
  currently connected sink, if any.
- `dpms_property`: Default connector property to control the
  connector's DPMS state.
- `path_property`: Default connector property to hold the DP MST path
  for the port.
- `tile_property`: Default connector property to store the tile
  position of a tiled screen, for sinks which need to be driven with
  multiple CRTCs.
- `link_status_property`: Default connector property for link status
  of a connector
- `plane_type_property`: Default plane property to differentiate
  CURSOR, PRIMARY and OVERLAY legacy uses of planes.
- `prop_src_x`: Default atomic plane property for the plane source
  position in the connected [`drm_framebuffer`](#c-struct-drm_framebuffer).
- `prop_src_y`: Default atomic plane property for the plane source
  position in the connected [`drm_framebuffer`](#c-struct-drm_framebuffer).
- `prop_src_w`: Default atomic plane property for the plane source
  position in the connected [`drm_framebuffer`](#c-struct-drm_framebuffer).
- `prop_src_h`: Default atomic plane property for the plane source
  position in the connected [`drm_framebuffer`](#c-struct-drm_framebuffer).
- `prop_crtc_x`: Default atomic plane property for the plane destination
  position in the [`drm_crtc`](#c-struct-drm_crtc) is being shown on.
- `prop_crtc_y`: Default atomic plane property for the plane destination
  position in the [`drm_crtc`](#c-struct-drm_crtc) is being shown on.
- `prop_crtc_w`: Default atomic plane property for the plane destination
  position in the [`drm_crtc`](#c-struct-drm_crtc) is being shown on.
- `prop_crtc_h`: Default atomic plane property for the plane destination
  position in the [`drm_crtc`](#c-struct-drm_crtc) is being shown on.
- `prop_fb_id`: Default atomic plane property to specify the
  [`drm_framebuffer`](#c-struct-drm_framebuffer).
- `prop_in_fence_fd`: Sync File fd representing the incoming fences
  for a Plane.
- `prop_out_fence_ptr`: Sync File fd pointer representing the
  outgoing fences for a CRTC. Userspace should provide a pointer to a
  value of type s32, and then cast that pointer to u64.
- `prop_crtc_id`: Default atomic plane property to specify the
  [`drm_crtc`](#c-struct-drm_crtc).
- `prop_fb_damage_clips`: Optional plane property to mark damaged
  regions on the plane in framebuffer coordinates of the framebuffer
  attached to the plane.

  The layout of blob data is simply an array of [`drm_mode_rect`](/kernel/hardware/gpu/drm-uapi.md#c-struct-drm_mode_rect). Unlike
  plane src coordinates, damage clips are not in 16.16 fixed point.
- `prop_active`: Default atomic CRTC property to control the active
  state, which is the simplified implementation for DPMS in atomic
  drivers.
- `prop_mode_id`: Default atomic CRTC property to set the mode for a
  CRTC. A 0 mode implies that the CRTC is entirely disabled - all
  connectors must be of and active must be set to disabled, too.
- `prop_vrr_enabled`: Default atomic CRTC property to indicate
  whether variable refresh rate should be enabled on the CRTC.
- `dvi_i_subconnector_property`: Optional DVI-I property to
  differentiate between analog or digital mode.
- `dvi_i_select_subconnector_property`: Optional DVI-I property to
  select between analog or digital mode.
- `dp_subconnector_property`: Optional DP property to differentiate
  between different DP downstream port types.
- `tv_subconnector_property`: Optional TV property to differentiate
  between different TV connector types.
- `tv_select_subconnector_property`: Optional TV property to select
  between different TV connector types.
- `legacy_tv_mode_property`: Optional TV property to select
  the output TV mode.

  Superseded by **tv_mode_property**
- `tv_mode_property`: Optional TV property to select the TV
  standard output on the connector.
- `tv_left_margin_property`: Optional TV property to set the left
  margin (expressed in pixels).
- `tv_right_margin_property`: Optional TV property to set the right
  margin (expressed in pixels).
- `tv_top_margin_property`: Optional TV property to set the right
  margin (expressed in pixels).
- `tv_bottom_margin_property`: Optional TV property to set the right
  margin (expressed in pixels).
- `tv_brightness_property`: Optional TV property to set the
  brightness.
- `tv_contrast_property`: Optional TV property to set the
  contrast.
- `tv_flicker_reduction_property`: Optional TV property to control the
  flicker reduction mode.
- `tv_overscan_property`: Optional TV property to control the overscan
  setting.
- `tv_saturation_property`: Optional TV property to set the
  saturation.
- `tv_hue_property`: Optional TV property to set the hue.
- `scaling_mode_property`: Optional connector property to control the
  upscaling, mostly used for built-in panels.
- `aspect_ratio_property`: Optional connector property to control the
  HDMI infoframe aspect ratio setting.
- `content_type_property`: Optional connector property to control the
  HDMI infoframe content type setting.
- `degamma_lut_property`: Optional CRTC property to set the LUT used to
  convert the framebuffer's colors to linear gamma.
- `degamma_lut_size_property`: Optional CRTC property for the size of
  the degamma LUT as supported by the driver (read-only).
- `ctm_property`: Optional CRTC property to set the
  matrix used to convert colors after the lookup in the
  degamma LUT.
- `gamma_lut_property`: Optional CRTC property to set the LUT used to
  convert the colors, after the CTM matrix, to the gamma space of the
  connected screen.
- `gamma_lut_size_property`: Optional CRTC property for the size of the
  gamma LUT as supported by the driver (read-only).
- `suggested_x_property`: Optional connector property with a hint for
  the position of the output on the host's screen.
- `suggested_y_property`: Optional connector property with a hint for
  the position of the output on the host's screen.
- `non_desktop_property`: Optional connector property with a hint
  that device isn't a standard display, and the console/desktop,
  should not be displayed on it.
- `panel_orientation_property`: Optional connector property indicating
  how the lcd-panel is mounted inside the casing (e.g. normal or
  upside-down).
- `writeback_fb_id_property`: Property for writeback connectors, storing
  the ID of the output framebuffer.
  See also: [`drm_writeback_connector_init()`](#c-drm_writeback_connector_init)
- `writeback_pixel_formats_property`: Property for writeback connectors,
  storing an array of the supported pixel formats for the writeback
  engine (read-only).
  See also: [`drm_writeback_connector_init()`](#c-drm_writeback_connector_init)
- `writeback_out_fence_ptr_property`: Property for writeback connectors,
  fd pointer representing the outgoing fences for a writeback
  connector. Userspace should provide a pointer to a value of type s32,
  and then cast that pointer to u64.
  See also: [`drm_writeback_connector_init()`](#c-drm_writeback_connector_init)
- `hdr_output_metadata_property`: Connector property containing hdr
  metatada. This will be provided by userspace compositors based
  on HDR content
- `content_protection_property`: DRM ENUM property for content
  protection. See [`drm_connector_attach_content_protection_property()`](/kernel/hardware/gpu/drm-kms-helpers.md#c-drm_connector_attach_content_protection_property).
- `hdcp_content_type_property`: DRM ENUM property for type of
  Protected Content.
- `preferred_depth`: preferred RBG pixel depth, used by fb helpers
- `prefer_shadow`: hint to userspace to prefer shadow-fb rendering
- `quirk_addfb_prefer_xbgr_30bpp`: Special hack for legacy ADDFB to keep nouveau userspace happy. Should
  only ever be set by the nouveau kernel driver.
- `quirk_addfb_prefer_host_byte_order`: When set to true `drm_mode_addfb()` will pick host byte order
  pixel_format when calling `drm_mode_addfb2()`.  This is how
  `drm_mode_addfb()` should have worked from day one.  It
  didn't though, so we ended up with quirks in both kernel
  and userspace drivers to deal with the broken behavior.
  Simply fixing `drm_mode_addfb()` unconditionally would break
  these drivers, so add a quirk bit here to allow drivers
  opt-in.
- `async_page_flip`: Does this device support async flips on the primary
  plane?
- `fb_modifiers_not_supported`: When this flag is set, the DRM device will not expose modifier
  support to userspace. This is only used by legacy drivers that infer
  the buffer layout through heuristics without using modifiers. New
  drivers shall not set fhis flag.
- `normalize_zpos`: If true the drm core will call [`drm_atomic_normalize_zpos()`](#c-drm_atomic_normalize_zpos) as part of
  atomic mode checking from [`drm_atomic_helper_check()`](/kernel/hardware/gpu/drm-kms-helpers.md#c-drm_atomic_helper_check)
- `modifiers_property`: Plane property to list support modifier/format
  combination.
- `async_modifiers_property`: Plane property to list support modifier/format
  combination for asynchronous flips.
- `size_hints_property`: Plane SIZE_HINTS property.
- `cursor_width`: hint to userspace for max cursor width
- `cursor_height`: hint to userspace for max cursor height
- `suspend_state`: Atomic state when suspended.
  Set by [`drm_mode_config_helper_suspend()`](/kernel/hardware/gpu/drm-kms-helpers.md#c-drm_mode_config_helper_suspend) and cleared by
  [`drm_mode_config_helper_resume()`](/kernel/hardware/gpu/drm-kms-helpers.md#c-drm_mode_config_helper_resume).
- `helper_private`: mid-layer private data

**Description**

Core mode resource tracking structure.  All CRTC, encoders, and connectors
enumerated by the driver are added here, as are global properties.  Some
global restrictions are also here, e.g. dimension restrictions.

Framebuffer sizes refer to the virtual screen that can be displayed by
the CRTC. This can be different from the physical resolution programmed.
The minimum width and height, stored in **min_width** and **min_height**,
describe the smallest size of the framebuffer. It correlates to the
minimum programmable resolution.
The maximum width, stored in **max_width**, is typically limited by the
maximum pitch between two adjacent scanlines. The maximum height, stored
in **max_height**, is usually only limited by the amount of addressable video
memory. For hardware that has no real maximum, drivers should pick a
reasonable default.

See also **DRM_SHADOW_PLANE_MAX_WIDTH** and **DRM_SHADOW_PLANE_MAX_HEIGHT**.

#### <a id="c-drm_mode_config_init"></a>`drm_mode_config_init()`

```c
int drm_mode_config_init(struct drm_device *dev)
```

DRM mode_configuration structure initialization

**Parameters**

- `struct drm_device *dev`: DRM device

**Description**

This is the unmanaged version of [`drmm_mode_config_init()`](#c-drmm_mode_config_init) for drivers which
still explicitly call [`drm_mode_config_cleanup()`](#c-drm_mode_config_cleanup).

FIXME: This function is deprecated and drivers should be converted over to
[`drmm_mode_config_init()`](#c-drmm_mode_config_init).



#### <a id="c-drm_mode_config_reset"></a>`drm_mode_config_reset()`

```c
void drm_mode_config_reset(struct drm_device *dev)
```

call ->reset callbacks

**Parameters**

- `struct drm_device *dev`: drm device

**Description**

This functions calls all the crtc's, encoder's and connector's ->reset
callback. Drivers can use this in e.g. their driver load or resume code to
reset hardware and software state.

#### <a id="c-drmm_mode_config_init"></a>`drmm_mode_config_init()`

```c
int drmm_mode_config_init(struct drm_device *dev)
```

managed DRM mode_configuration structure initialization

**Parameters**

- `struct drm_device *dev`: DRM device

**Description**

Initialize **dev**'s mode_config structure, used for tracking the graphics
configuration of **dev**.

Since this initializes the modeset locks, no locking is possible. Which is no
problem, since this should happen single threaded at init time. It is the
driver's problem to ensure this guarantee.

Cleanup is automatically handled through registering drm_mode_config_cleanup
with [`drmm_add_action()`](/kernel/hardware/gpu/drm-internals.md#c-drmm_add_action).

**Return**

0 on success, negative error value on failure.

#### <a id="c-drm_mode_config_cleanup"></a>`drm_mode_config_cleanup()`

```c
void drm_mode_config_cleanup(struct drm_device *dev)
```

free up DRM mode_config info

**Parameters**

- `struct drm_device *dev`: DRM device

**Description**

Free up all the connectors and CRTCs associated with this DRM device, then
free up the framebuffers and associated buffer objects.

Note that since this /should/ happen single-threaded at driver/device
teardown time, no locking is required. It's the driver's job to ensure that
this guarantee actually holds true.

FIXME: With the managed [`drmm_mode_config_init()`](#c-drmm_mode_config_init) it is no longer necessary for
drivers to explicitly call this function.


<a id="rst-modeset-base-object-abstraction"></a>
<a id="rst-kms-base-object-abstraction"></a>

## Modeset Base Object Abstraction

```mermaid
flowchart TB
  n0["drm_property A"]
  n1["drm_mode_object A"]
  n2["drm_mode_object B"]
  n3["drm_property B"]
  n0 --> n1
  n0 --> n2
  n3 --> n1
```

Mode Objects and Properties

Mode Objects and Properties

The base structure for all KMS objects is `struct drm_mode_object <drm_mode_object>`. One of the base services it provides is tracking properties, which are especially important for the atomic IOCTL (see [Atomic Mode Setting](<#rst-atomic-mode-setting>)). The somewhat surprising part here is that properties are not directly instantiated on each object, but free-standing mode objects themselves, represented by `struct drm_property <drm_property>`, which only specify the type and value range of a property. Any given property can be attached multiple times to different objects using drm\_object\_attach\_property().


#### <a id="c-struct-drm_mode_object"></a>`struct drm_mode_object`

base structure for modeset objects

**Definition**

```c
struct drm_mode_object {
    uint32_t id;
    uint32_t type;
    struct drm_object_properties *properties;
    struct kref refcount;
    void (*free_cb)(struct kref *kref);
};
```

**Members**

- `id`: userspace visible identifier
- `type`: type of the object, one of DRM_MODE_OBJECT\_\*
- `properties`: properties attached to this object, including values
- `refcount`: reference count for objects with dynamic lifetime
- `free_cb`: free function callback, only set for objects with dynamic lifetime

**Description**

Base structure for modeset objects visible to userspace. Objects can be
looked up using [`drm_mode_object_find()`](#c-drm_mode_object_find). Besides basic uapi interface
properties like **id** and **type** it provides two services:

- It tracks attached properties and their values. This is used by [`drm_crtc`](#c-struct-drm_crtc),
  [`drm_plane`](#c-struct-drm_plane) and [`drm_connector`](#c-struct-drm_connector). Properties are attached by calling
  [`drm_object_attach_property()`](#c-drm_object_attach_property) before the object is visible to userspace.

- For objects with dynamic lifetimes (as indicated by a non-NULL **free_cb**) it
  provides reference counting through [`drm_mode_object_get()`](#c-drm_mode_object_get) and
  [`drm_mode_object_put()`](#c-drm_mode_object_put). This is used by [`drm_framebuffer`](#c-struct-drm_framebuffer), [`drm_connector`](#c-struct-drm_connector)
  and [`drm_property_blob`](#c-struct-drm_property_blob). These objects provide specialized reference
  counting wrappers.

#### <a id="c-struct-drm_object_properties"></a>`struct drm_object_properties`

property tracking for [`drm_mode_object`](#c-struct-drm_mode_object)

**Definition**

```c
struct drm_object_properties {
    int count;
    struct drm_property *properties[DRM_OBJECT_MAX_PROPERTY];
    uint64_t values[DRM_OBJECT_MAX_PROPERTY];
};
```

**Members**

- `count`: number of valid properties, must be less than or equal to
  DRM_OBJECT_MAX_PROPERTY.
- `properties`: Array of pointers to [`drm_property`](#c-struct-drm_property).

  NOTE: if we ever start dynamically destroying properties (ie.
  not at [`drm_mode_config_cleanup()`](#c-drm_mode_config_cleanup) time), then we'd have to do
  a better job of detaching property from mode objects to avoid
  dangling property pointers:
- `values`: Array to store the property values, matching **properties**. Do
  not read/write values directly, but use
  [`drm_object_property_get_value()`](#c-drm_object_property_get_value) and [`drm_object_property_set_value()`](#c-drm_object_property_set_value).

  Note that atomic drivers do not store mutable properties in this
  array, but only the decoded values in the corresponding state
  structure. The decoding is done using the [`drm_crtc.atomic_get_property`](#c-struct-drm_crtc) and
  [`drm_crtc.atomic_set_property`](#c-struct-drm_crtc) hooks for [`struct drm_crtc`](#c-struct-drm_crtc). For
  [`struct drm_plane`](#c-struct-drm_plane) the hooks are [`drm_plane_funcs.atomic_get_property`](#c-struct-drm_plane_funcs) and
  [`drm_plane_funcs.atomic_set_property`](#c-struct-drm_plane_funcs). And for [`struct drm_connector`](#c-struct-drm_connector)
  the hooks are [`drm_connector_funcs.atomic_get_property`](#c-struct-drm_connector_funcs) and
  [`drm_connector_funcs.atomic_set_property`](#c-struct-drm_connector_funcs) .

  Hence atomic drivers should not use [`drm_object_property_set_value()`](#c-drm_object_property_set_value)
  and [`drm_object_property_get_value()`](#c-drm_object_property_get_value) on mutable objects, i.e. those
  without the DRM_MODE_PROP_IMMUTABLE flag set.

  For atomic drivers the default value of properties is stored in this
  array, so drm_object_property_get_default_value can be used to
  retrieve it.



#### <a id="c-drm_mode_object_find"></a>`drm_mode_object_find()`

```c
struct drm_mode_object * drm_mode_object_find(struct drm_device *dev, struct drm_file *file_priv, uint32_t id, uint32_t type)
```

look up a drm object with static lifetime

**Parameters**

- `struct drm_device *dev`: drm device
- `struct drm_file *file_priv`: drm file
- `uint32_t id`: id of the mode object
- `uint32_t type`: type of the mode object

**Description**

This function is used to look up a modeset object. It will acquire a
reference for reference counted objects. This reference must be dropped again
by callind [`drm_mode_object_put()`](#c-drm_mode_object_put).

#### <a id="c-drm_mode_object_put"></a>`drm_mode_object_put()`

```c
void drm_mode_object_put(struct drm_mode_object *obj)
```

release a mode object reference

**Parameters**

- `struct drm_mode_object *obj`: DRM mode object

**Description**

This function decrements the object's refcount if it is a refcounted modeset
object. It is a no-op on any other object. This is used to drop references
acquired with [`drm_mode_object_get()`](#c-drm_mode_object_get).

#### <a id="c-drm_mode_object_get"></a>`drm_mode_object_get()`

```c
void drm_mode_object_get(struct drm_mode_object *obj)
```

acquire a mode object reference

**Parameters**

- `struct drm_mode_object *obj`: DRM mode object

**Description**

This function increments the object's refcount if it is a refcounted modeset
object. It is a no-op on any other object. References should be dropped again
by calling [`drm_mode_object_put()`](#c-drm_mode_object_put).

#### <a id="c-drm_object_attach_property"></a>`drm_object_attach_property()`

```c
void drm_object_attach_property(struct drm_mode_object *obj, struct drm_property *property, uint64_t init_val)
```

attach a property to a modeset object

**Parameters**

- `struct drm_mode_object *obj`: drm modeset object
- `struct drm_property *property`: property to attach
- `uint64_t init_val`: initial value of the property

**Description**

This attaches the given property to the modeset object with the given initial
value. Currently this function cannot fail since the properties are stored in
a statically sized array.

Note that all properties must be attached before the object itself is
registered and accessible from userspace.

#### <a id="c-drm_object_property_set_value"></a>`drm_object_property_set_value()`

```c
int drm_object_property_set_value(struct drm_mode_object *obj, struct drm_property *property, uint64_t val)
```

set the value of a property

**Parameters**

- `struct drm_mode_object *obj`: drm mode object to set property value for
- `struct drm_property *property`: property to set
- `uint64_t val`: value the property should be set to

**Description**

This function sets a given property on a given object. This function only
changes the software state of the property, it does not call into the
driver's ->set_property callback.

Note that atomic drivers should not have any need to call this, the core will
ensure consistency of values reported back to userspace through the
appropriate ->atomic_get_property callback. Only legacy drivers should call
this function to update the tracked value (after clamping and other
restrictions have been applied).

**Return**

Zero on success, error code on failure.

#### <a id="c-drm_object_property_get_value"></a>`drm_object_property_get_value()`

```c
int drm_object_property_get_value(struct drm_mode_object *obj, struct drm_property *property, uint64_t *val)
```

retrieve the value of a property

**Parameters**

- `struct drm_mode_object *obj`: drm mode object to get property value from
- `struct drm_property *property`: property to retrieve
- `uint64_t *val`: storage for the property value

**Description**

This function retrieves the softare state of the given property for the given
property. Since there is no driver callback to retrieve the current property
value this might be out of sync with the hardware, depending upon the driver
and property.

Atomic drivers should never call this function directly, the core will read
out property values through the various ->atomic_get_property callbacks.

**Return**

Zero on success, error code on failure.

#### <a id="c-drm_object_property_get_default_value"></a>`drm_object_property_get_default_value()`

```c
int drm_object_property_get_default_value(struct drm_mode_object *obj, struct drm_property *property, uint64_t *val)
```

retrieve the default value of a property when in atomic mode.

**Parameters**

- `struct drm_mode_object *obj`: drm mode object to get property value from
- `struct drm_property *property`: property to retrieve
- `uint64_t *val`: storage for the property value

**Description**

This function retrieves the default state of the given property as passed in
to drm_object_attach_property

Only atomic drivers should call this function directly, as for non-atomic
drivers it will return the current value.

**Return**

Zero on success, error code on failure.

#### <a id="c-drm_object_immutable_property_get_value"></a>`drm_object_immutable_property_get_value()`

```c
int drm_object_immutable_property_get_value(struct drm_mode_object *obj, struct drm_property *property, uint64_t *val)
```

retrieve the value of a property

**Parameters**

- `struct drm_mode_object *obj`: drm mode object to get property value from
- `struct drm_property *property`: property to retrieve
- `uint64_t *val`: storage for the property value

**Description**

This function retrieves the software state of the given immutable property
for the given mode object.

This function can be called by both atomic and non-atomic drivers.

**Return**

Zero on success, error code on failure.


<a id="rst-atomic-mode-setting"></a>

## Atomic Mode Setting

```mermaid
flowchart TB
  subgraph g0["Free-standing state"]
    n0["drm_atomic_state"]
    n1["duplicated drm_plane_state A"]
    n2["duplicated drm_plane_state B"]
    n3["duplicated drm_crtc_state"]
    n4["duplicated drm_connector_state"]
    n5["duplicated driver private state"]
  end
  subgraph g1["Current state"]
    n6["drm_device"]
    n7["drm_plane A"]
    n8["drm_plane B"]
    n9["drm_crtc"]
    n10["drm_connector"]
    n11["driver private object"]
    n12["drm_plane_state A"]
    n13["drm_plane_state B"]
    n14["drm_crtc_state"]
    n15["drm_connector_state"]
    n16["driver private state"]
  end
  n0 --> n1
  n0 --> n2
  n0 --> n3
  n0 --> n4
  n0 --> n5
  n6 --> n7
  n6 --> n8
  n6 --> n9
  n6 --> n10
  n6 --> n11
  n7 --> n12
  n8 --> n13
  n9 --> n14
  n10 --> n15
  n11 --> n16
  n0 -->|"atomic_commit"| n6
  style g0 stroke-dasharray:6 4
  style g1 stroke-dasharray:6 4
```

Mode Objects and Properties

Mode Objects and Properties

Atomic provides transactional modeset (including planes) updates, but a bit differently from the usual transactional approach of try-commit and rollback:

- Firstly, no hardware changes are allowed when the commit would fail. This allows us to implement the DRM\_MODE\_ATOMIC\_TEST\_ONLY mode, which allows userspace to explore whether certain configurations would work or not.

- This would still allow setting and rollback of just the software state, simplifying conversion of existing drivers. But auditing drivers for correctness of the atomic\_check code becomes really hard with that: Rolling back changes in data structures all over the place is hard to get right.

- Lastly, for backwards compatibility and to support all use-cases, atomic updates need to be incremental and be able to execute in parallel. Hardware doesn't always allow it, but where possible plane updates on different CRTCs should not interfere, and not get stalled due to output routing changing on different CRTCs.

Taken all together there's two consequences for the atomic design:

- The overall state is split up into per-object state structures: `struct drm_plane_state <drm_plane_state>` for planes, `struct drm_crtc_state <drm_crtc_state>` for CRTCs and `struct drm_connector_state <drm_connector_state>` for connectors. These are the only objects with userspace-visible and settable state. For internal state drivers can subclass these structures through embedding, or add entirely new state structures for their globally shared hardware functions, see `struct drm_private_state<drm_private_state>`.

- An atomic update is assembled and validated as an entirely free-standing pile of structures within the `drm_atomic_state <drm_atomic_state>` container. Driver private state structures are also tracked in the same structure; see the next chapter.  Only when a state is committed is it applied to the driver and modeset objects. This way rolling back an update boils down to releasing memory and unreferencing objects like framebuffers.

Locking of atomic state structures is internally using `struct drm_modeset_lock <drm_modeset_lock>`. As a general rule the locking shouldn't be exposed to drivers, instead the right locks should be automatically acquired by any function that duplicates or peeks into a state, like e.g. drm\_atomic\_get\_crtc\_state().  Locking only protects the software data structure, ordering of committing state changes to hardware is sequenced using `struct drm_crtc_commit <drm_crtc_commit>`.

Read on in this chapter, and also in [drm\_atomic\_helper](</kernel/hardware/gpu/drm-kms-helpers.md#rst-drm-atomic-helper>) for more detailed coverage of specific topics.

<a id="rst-handling-driver-private-state"></a>

### Handling Driver Private State


Very often the DRM objects exposed to userspace in the atomic modeset api
([`drm_connector`](#c-struct-drm_connector), [`drm_crtc`](#c-struct-drm_crtc) and [`drm_plane`](#c-struct-drm_plane)) do not map neatly to the
underlying hardware. Especially for any kind of shared resources (e.g. shared
clocks, scaler units, bandwidth and fifo limits shared among a group of
planes or CRTCs, and so on) it makes sense to model these as independent
objects. Drivers then need to do similar state tracking and commit ordering for
such private (since not exposed to userspace) objects as the atomic core and
helpers already provide for connectors, planes and CRTCs.

To make this easier on drivers the atomic core provides some support to track
driver private state objects using struct [`drm_private_obj`](#c-struct-drm_private_obj), with the
associated state struct [`drm_private_state`](#c-struct-drm_private_state).

Similar to userspace-exposed objects, private state structures can be
acquired by calling [`drm_atomic_get_private_obj_state()`](#c-drm_atomic_get_private_obj_state). This also takes care
of locking, hence drivers should not have a need to call [`drm_modeset_lock()`](#c-drm_modeset_lock)
directly. Sequence of the actual hardware state commit is not handled,
drivers might need to keep track of struct drm_crtc_commit within subclassed
structure of [`drm_private_state`](#c-struct-drm_private_state) as necessary, e.g. similar to
[`drm_plane_state.commit`](#c-struct-drm_plane_state). See also [`drm_atomic_state.fake_commit`](#c-struct-drm_atomic_state).

All private state structures contained in a [`drm_atomic_state`](#c-struct-drm_atomic_state) update can be
iterated using [`for_each_oldnew_private_obj_in_state()`](#c-for_each_oldnew_private_obj_in_state),
[`for_each_new_private_obj_in_state()`](#c-for_each_new_private_obj_in_state) and [`for_each_old_private_obj_in_state()`](#c-for_each_old_private_obj_in_state).
Drivers are recommended to wrap these for each type of driver private state
object they have, filtering on [`drm_private_obj.funcs`](#c-struct-drm_private_obj) using [`for_each_if()`](/kernel/hardware/driver-api/fundamentals/basics.md#c-for_each_if), at
least if they want to iterate over all objects of a given type.

An earlier way to handle driver private state was by subclassing struct
[`drm_atomic_state`](#c-struct-drm_atomic_state). But since that encourages non-standard ways to implement
the check/commit split atomic requires (by using e.g. "check and rollback or
commit instead" of "duplicate state, check, then either commit or release
duplicated state) it is deprecated in favour of using [`drm_private_state`](#c-struct-drm_private_state).


<a id="rst-atomic-mode-setting-function-reference"></a>

### Atomic Mode Setting Function Reference


#### <a id="c-struct-drm_crtc_commit"></a>`struct drm_crtc_commit`

track modeset commits on a CRTC

**Definition**

```c
struct drm_crtc_commit {
    struct drm_crtc *crtc;
    struct kref ref;
    struct completion flip_done;
    struct completion hw_done;
    struct completion cleanup_done;
    struct list_head commit_entry;
    struct drm_pending_vblank_event *event;
    bool abort_completion;
};
```

**Members**

- `crtc`: DRM CRTC for this commit.
- `ref`: Reference count for this structure. Needed to allow blocking on
  completions without the risk of the completion disappearing
  meanwhile.
- `flip_done`: Will be signaled when the hardware has flipped to the new set of
  buffers. Signals at the same time as when the drm event for this
  commit is sent to userspace, or when an out-fence is singalled. Note
  that for most hardware, in most cases this happens after **hw_done** is
  signalled.

  Completion of this stage is signalled implicitly by calling
  [`drm_crtc_send_vblank_event()`](#c-drm_crtc_send_vblank_event) on [`drm_crtc_state.event`](#c-struct-drm_crtc_state).
- `hw_done`: Will be signalled when all hw register changes for this commit have
  been written out. Especially when disabling a pipe this can be much
  later than **flip_done**, since that can signal already when the
  screen goes black, whereas to fully shut down a pipe more register
  I/O is required.

  Note that this does not need to include separately reference-counted
  resources like backing storage buffer pinning, or runtime pm
  management.

  Drivers should call [`drm_atomic_helper_commit_hw_done()`](/kernel/hardware/gpu/drm-kms-helpers.md#c-drm_atomic_helper_commit_hw_done) to signal
  completion of this stage.
- `cleanup_done`: Will be signalled after old buffers have been cleaned up by calling
  [`drm_atomic_helper_cleanup_planes()`](/kernel/hardware/gpu/drm-kms-helpers.md#c-drm_atomic_helper_cleanup_planes). Since this can only happen after
  a vblank wait completed it might be a bit later. This completion is
  useful to throttle updates and avoid hardware updates getting ahead
  of the buffer cleanup too much.

  Drivers should call [`drm_atomic_helper_commit_cleanup_done()`](/kernel/hardware/gpu/drm-kms-helpers.md#c-drm_atomic_helper_commit_cleanup_done) to signal
  completion of this stage.
- `commit_entry`: Entry on the per-CRTC [`drm_crtc.commit_list`](#c-struct-drm_crtc). Protected by
  $drm_crtc.commit_lock.
- `event`: [`drm_pending_vblank_event`](#c-struct-drm_pending_vblank_event) pointer to clean up private events.
- `abort_completion`: A flag that's set after [`drm_atomic_helper_setup_commit()`](/kernel/hardware/gpu/drm-kms-helpers.md#c-drm_atomic_helper_setup_commit) takes a
  second reference for the completion of $drm_crtc_state.event. It's
  used by the free code to remove the second reference if commit fails.

**Description**

This structure is used to track pending modeset changes and atomic commit on
a per-CRTC basis. Since updating the list should never block, this structure
is reference counted to allow waiters to safely wait on an event to complete,
without holding any locks.

It has 3 different events in total to allow a fine-grained synchronization
between outstanding updates:

```text
atomic commit thread                    hardware

write new state into hardware   ---->   ...
signal hw_done
                                        switch to new state on next
...                                     v/hblank

wait for buffers to show up             ...

...                                     send completion irq
                                        irq handler signals flip_done
cleanup old buffers

signal cleanup_done

wait for flip_done              <----
clean up atomic state
```

The important bit to know is that `cleanup_done` is the terminal event, but the
ordering between `flip_done` and `hw_done` is entirely up to the specific driver
and modeset state change.

For an implementation of how to use this look at
[`drm_atomic_helper_setup_commit()`](/kernel/hardware/gpu/drm-kms-helpers.md#c-drm_atomic_helper_setup_commit) from the atomic helper library.

See also [`drm_crtc_commit_wait()`](#c-drm_crtc_commit_wait).

#### <a id="c-struct-drm_private_state_funcs"></a>`struct drm_private_state_funcs`

atomic state functions for private objects

**Definition**

```c
struct drm_private_state_funcs {
    struct drm_private_state *(*atomic_duplicate_state)(struct drm_private_obj *obj);
    void (*atomic_destroy_state)(struct drm_private_obj *obj, struct drm_private_state *state);
    void (*atomic_print_state)(struct drm_printer *p, const struct drm_private_state *state);
};
```

**Members**

- `atomic_duplicate_state`: Duplicate the current state of the private object and return it. It
  is an error to call this before obj->state has been initialized.

  RETURNS:

  Duplicated atomic state or NULL when obj->state is not
  initialized or allocation failed.
- `atomic_destroy_state`: Frees the private object state created with **atomic_duplicate_state**.
- `atomic_print_state`: If driver subclasses [`struct drm_private_state`](#c-struct-drm_private_state), it should implement
  this optional hook for printing additional driver specific state.

  Do not call this directly, use `drm_atomic_private_obj_print_state()`
  instead.

**Description**

These hooks are used by atomic helpers to create, swap and destroy states of
private objects. The structure itself is used as a vtable to identify the
associated private object type. Each private object type that needs to be
added to the atomic states is expected to have an implementation of these
hooks and pass a pointer to its drm_private_state_funcs struct to
[`drm_atomic_get_private_obj_state()`](#c-drm_atomic_get_private_obj_state).

#### <a id="c-struct-drm_private_obj"></a>`struct drm_private_obj`

base struct for driver private atomic object

**Definition**

```c
struct drm_private_obj {
    struct drm_device *dev;
    struct list_head head;
    struct drm_modeset_lock lock;
    struct drm_private_state *state;
    const struct drm_private_state_funcs *funcs;
};
```

**Members**

- `dev`: parent DRM device
- `head`: List entry used to attach a private object to a [`drm_device`](/kernel/hardware/gpu/drm-internals.md#c-struct-drm_device)
  (queued to [`drm_mode_config.privobj_list`](#c-struct-drm_mode_config)).
- `lock`: Modeset lock to protect the state object.
- `state`: Current atomic state for this driver private object.
- `funcs`: Functions to manipulate the state of this driver private object, see
  [`drm_private_state_funcs`](#c-struct-drm_private_state_funcs).

**Description**

A driver private object is initialized by calling
[`drm_atomic_private_obj_init()`](#c-drm_atomic_private_obj_init) and cleaned up by calling
[`drm_atomic_private_obj_fini()`](#c-drm_atomic_private_obj_fini).

Currently only tracks the state update functions and the opaque driver
private state itself, but in the future might also track which
[`drm_modeset_lock`](#c-drm_modeset_lock) is required to duplicate and update this object's state.

All private objects must be initialized before the DRM device they are
attached to is registered to the DRM subsystem (call to [`drm_dev_register()`](/kernel/hardware/gpu/drm-internals.md#c-drm_dev_register))
and should stay around until this DRM device is unregistered (call to
[`drm_dev_unregister()`](/kernel/hardware/gpu/drm-internals.md#c-drm_dev_unregister)). In other words, private objects lifetime is tied
to the DRM device lifetime. This implies that:

- 1/ all calls to [`drm_atomic_private_obj_init()`](#c-drm_atomic_private_obj_init) must be done before calling

  [`drm_dev_register()`](/kernel/hardware/gpu/drm-internals.md#c-drm_dev_register)
- 2/ all calls to [`drm_atomic_private_obj_fini()`](#c-drm_atomic_private_obj_fini) must be done after calling

  [`drm_dev_unregister()`](/kernel/hardware/gpu/drm-internals.md#c-drm_dev_unregister)

If that private object is used to store a state shared by multiple
CRTCs, proper care must be taken to ensure that non-blocking commits are
properly ordered to avoid a use-after-free issue.

Indeed, assuming a sequence of two non-blocking [`drm_atomic_commit`](#c-drm_atomic_commit) on two
different [`drm_crtc`](#c-struct-drm_crtc) using different [`drm_plane`](#c-struct-drm_plane) and [`drm_connector`](#c-struct-drm_connector), so with no
resources shared, there's no guarantee on which commit is going to happen
first. However, the second [`drm_atomic_commit`](#c-drm_atomic_commit) will consider the first
[`drm_private_obj`](#c-struct-drm_private_obj) its old state, and will be in charge of freeing it whenever
the second [`drm_atomic_commit`](#c-drm_atomic_commit) is done.

If the first [`drm_atomic_commit`](#c-drm_atomic_commit) happens after it, it will consider its
[`drm_private_obj`](#c-struct-drm_private_obj) the new state and will be likely to access it, resulting in
an access to a freed memory region. Drivers should store (and get a reference
to) the [`drm_crtc_commit`](#c-struct-drm_crtc_commit) structure in our private state in
[`drm_mode_config_helper_funcs.atomic_commit_setup`](/kernel/hardware/gpu/drm-kms-helpers.md#c-struct-drm_mode_config_helper_funcs), and then wait for that
commit to complete as the first step of
[`drm_mode_config_helper_funcs.atomic_commit_tail`](/kernel/hardware/gpu/drm-kms-helpers.md#c-struct-drm_mode_config_helper_funcs), similar to
[`drm_atomic_helper_wait_for_dependencies()`](/kernel/hardware/gpu/drm-kms-helpers.md#c-drm_atomic_helper_wait_for_dependencies).

#### <a id="c-drm_for_each_privobj"></a>`drm_for_each_privobj()`

```c
drm_for_each_privobj(privobj, dev)
```

private object iterator

**Parameters**

- `privobj`: pointer to the current private object. Updated after each
  iteration
- `dev`: the DRM device we want get private objects from

**Description**

Allows one to iterate over all private objects attached to **dev**

#### <a id="c-struct-drm_private_state"></a>`struct drm_private_state`

base struct for driver private object state

**Definition**

```c
struct drm_private_state {
    struct drm_atomic_state *state;
    struct drm_private_obj *obj;
};
```

**Members**

- `state`: backpointer to global drm_atomic_state
- `obj`: backpointer to the private object

**Description**

Currently only contains a backpointer to the overall atomic update,
and the relevant private object but in the future also might hold
synchronization information similar to e.g. [`drm_crtc.commit`](#c-struct-drm_crtc).

#### <a id="c-struct-drm_atomic_state"></a>`struct drm_atomic_state`

Atomic commit structure

**Definition**

```c
struct drm_atomic_state {
    struct kref ref;
    struct drm_device *dev;
    bool allow_modeset : 1;
    bool legacy_cursor_update : 1;
    bool async_update : 1;
    bool duplicated : 1;
    bool checked : 1;
    bool plane_color_pipeline : 1;
    struct __drm_colorops_state *colorops;
    struct __drm_planes_state *planes;
    struct __drm_crtcs_state *crtcs;
    int num_connector;
    struct __drm_connnectors_state *connectors;
    int num_private_objs;
    struct __drm_private_objs_state *private_objs;
    struct drm_modeset_acquire_ctx *acquire_ctx;
    struct drm_crtc_commit *fake_commit;
    struct work_struct commit_work;
};
```

**Members**

- `ref`: Count of all references to this update (will not be freed until zero).
- `dev`: Parent DRM Device.
- `allow_modeset`: Allow full modeset. This is used by the ATOMIC IOCTL handler to
  implement the DRM_MODE_ATOMIC_ALLOW_MODESET flag. Drivers should
  generally not consult this flag, but instead look at the output of
  [`drm_atomic_crtc_needs_modeset()`](#c-drm_atomic_crtc_needs_modeset). The detailed rules are:

  - Drivers must not consult **allow_modeset** in the atomic commit path.
    Use [`drm_atomic_crtc_needs_modeset()`](#c-drm_atomic_crtc_needs_modeset) instead.

  - Drivers must consult **allow_modeset** before adding unrelated struct
    drm_crtc_state to this commit by calling
    [`drm_atomic_get_crtc_state()`](#c-drm_atomic_get_crtc_state). See also the warning in the
    documentation for that function.

  - Drivers must never change this flag, it is under the exclusive
    control of userspace.

  - Drivers may consult **allow_modeset** in the atomic check path, if
    they have the choice between an optimal hardware configuration
    which requires a modeset, and a less optimal configuration which
    can be committed without a modeset. An example would be suboptimal
    scanout FIFO allocation resulting in increased idle power
    consumption. This allows userspace to avoid flickering and delays
    for the normal composition loop at reasonable cost.
- `legacy_cursor_update`: Hint to enforce legacy cursor IOCTL semantics.

  WARNING: This is thoroughly broken and pretty much impossible to
  implement correctly. Drivers must ignore this and should instead
  implement [`drm_plane_helper_funcs.atomic_async_check`](/kernel/hardware/gpu/drm-kms-helpers.md#c-struct-drm_plane_helper_funcs) and
  [`drm_plane_helper_funcs.atomic_async_commit`](/kernel/hardware/gpu/drm-kms-helpers.md#c-struct-drm_plane_helper_funcs) hooks. New users of this
  flag are not allowed.
- `async_update`: hint for asynchronous plane update
- `duplicated`: Indicates whether or not this atomic state was duplicated using
  [`drm_atomic_helper_duplicate_state()`](/kernel/hardware/gpu/drm-kms-helpers.md#c-drm_atomic_helper_duplicate_state). Drivers and atomic helpers
  should use this to fixup normal  inconsistencies in duplicated
  states.
- `checked`: Indicates the state has been checked and thus must no longer
  be mutated. For internal use only, do not consult from drivers.
- `plane_color_pipeline`: Indicates whether this atomic state originated with a client that
  set the DRM_CLIENT_CAP_PLANE_COLOR_PIPELINE.

  Drivers and helper functions should use this to ignore legacy
  properties that are incompatible with the drm_plane COLOR_PIPELINE
  behavior, such as:

  - COLOR_RANGE
  - COLOR_ENCODING

  or any other driver-specific properties that might affect pixel
  values.
- `colorops`: Pointer to array of **drm_colorop** and **drm_colorop_state** part of this
  update.
- `planes`: Pointer to array of **drm_plane** and **drm_plane_state** part of this
  update.
- `crtcs`: Pointer to array of **drm_crtc** and **drm_crtc_state** part of this
  update.
- `num_connector`: size of the **connectors** array
- `connectors`: Pointer to array of **drm_connector** and **drm_connector_state** part of
  this update.
- `num_private_objs`: size of the **private_objs** array
- `private_objs`: Pointer to array of **drm_private_obj** and **drm_private_obj_state** part
  of this update.
- `acquire_ctx`: acquire context for this atomic modeset state update
- `fake_commit`: Used for signaling unbound planes/connectors.
  When a connector or plane is not bound to any CRTC, it's still important
  to preserve linearity to prevent the atomic states from being freed too early.

  This commit (if set) is not bound to any CRTC, but will be completed when
  [`drm_atomic_helper_commit_hw_done()`](/kernel/hardware/gpu/drm-kms-helpers.md#c-drm_atomic_helper_commit_hw_done) is called.
- `commit_work`: Work item which can be used by the driver or helpers to execute the
  commit without blocking.

**Description**

This structure is the kernel counterpart of **drm_mode_atomic** and represents
an atomic commit that transitions from an old to a new display state. It
contains all the objects affected by the atomic commit and both the new
state structures and pointers to the old state structures for
these.

States are added to an atomic update by calling [`drm_atomic_get_crtc_state()`](#c-drm_atomic_get_crtc_state),
[`drm_atomic_get_plane_state()`](#c-drm_atomic_get_plane_state), [`drm_atomic_get_connector_state()`](#c-drm_atomic_get_connector_state), or for
private state structures, [`drm_atomic_get_private_obj_state()`](#c-drm_atomic_get_private_obj_state).

**NOTE**

struct drm_atomic_state first started as a single collection of
entities state pointers (drm_plane_state, drm_crtc_state, etc.).

At atomic_check time, you could get the state about to be committed
from drm_atomic_state, and the one currently running from the
entities state pointer (drm_crtc.state, for example). After the call
to [`drm_atomic_helper_swap_state()`](/kernel/hardware/gpu/drm-kms-helpers.md#c-drm_atomic_helper_swap_state), the entities state pointer would
contain the state previously checked, and the drm_atomic_state
structure the old state.

Over time, and in order to avoid confusion, drm_atomic_state has
grown to have both the old state (ie, the state we replace) and the
new state (ie, the state we want to apply). Those names are stable
during the commit process, which makes it easier to reason about.

You can still find some traces of that evolution through some hooks
or callbacks taking a drm_atomic_state parameter called names like
"old_state". This doesn't necessarily mean that the previous
drm_atomic_state is passed, but rather that this used to be the state
collection we were replacing after [`drm_atomic_helper_swap_state()`](/kernel/hardware/gpu/drm-kms-helpers.md#c-drm_atomic_helper_swap_state),
but the variable name was never updated.

Some atomic operations implementations followed a similar process. We
first started to pass the entity state only. However, it was pretty
cumbersome for drivers, and especially CRTCs, to retrieve the states
of other components. Thus, we switched to passing the whole
drm_atomic_state as a parameter to those operations. Similarly, the
transition isn't complete yet, and one might still find atomic
operations taking a drm_atomic_state pointer, or a component state
pointer. The former is the preferred form.

#### <a id="c-drm_crtc_commit_get"></a>`drm_crtc_commit_get()`

```c
struct drm_crtc_commit * drm_crtc_commit_get(struct drm_crtc_commit *commit)
```

acquire a reference to the CRTC commit

**Parameters**

- `struct drm_crtc_commit *commit`: CRTC commit

**Description**

Increases the reference of **commit**.

**Return**

The pointer to **commit**, with reference increased.

#### <a id="c-drm_crtc_commit_put"></a>`drm_crtc_commit_put()`

```c
void drm_crtc_commit_put(struct drm_crtc_commit *commit)
```

release a reference to the CRTC commmit

**Parameters**

- `struct drm_crtc_commit *commit`: CRTC commit

**Description**

This releases a reference to **commit** which is freed after removing the
final reference. No locking required and callable from any context.

#### <a id="c-drm_atomic_state_get"></a>`drm_atomic_state_get()`

```c
struct drm_atomic_state * drm_atomic_state_get(struct drm_atomic_state *state)
```

acquire a reference to the atomic state

**Parameters**

- `struct drm_atomic_state *state`: The atomic state

**Description**

Returns a new reference to the **state**

#### <a id="c-drm_atomic_state_put"></a>`drm_atomic_state_put()`

```c
void drm_atomic_state_put(struct drm_atomic_state *state)
```

release a reference to the atomic state

**Parameters**

- `struct drm_atomic_state *state`: The atomic state

**Description**

This releases a reference to **state** which is freed after removing the
final reference. No locking required and callable from any context.

#### <a id="c-drm_atomic_get_old_crtc_state"></a>`drm_atomic_get_old_crtc_state()`

```c
struct drm_crtc_state * drm_atomic_get_old_crtc_state(const struct drm_atomic_state *state, struct drm_crtc *crtc)
```

get old CRTC state, if it exists

**Parameters**

- `const struct drm_atomic_state *state`: global atomic state object
- `struct drm_crtc *crtc`: CRTC to grab

**Description**

This function returns the old CRTC state for the given CRTC, or
NULL if the CRTC is not part of the global atomic state.

#### <a id="c-drm_atomic_get_new_crtc_state"></a>`drm_atomic_get_new_crtc_state()`

```c
struct drm_crtc_state * drm_atomic_get_new_crtc_state(const struct drm_atomic_state *state, struct drm_crtc *crtc)
```

get new CRTC state, if it exists

**Parameters**

- `const struct drm_atomic_state *state`: global atomic state object
- `struct drm_crtc *crtc`: CRTC to grab

**Description**

This function returns the new CRTC state for the given CRTC, or
NULL if the CRTC is not part of the global atomic state.

#### <a id="c-drm_atomic_get_old_plane_state"></a>`drm_atomic_get_old_plane_state()`

```c
struct drm_plane_state * drm_atomic_get_old_plane_state(const struct drm_atomic_state *state, struct drm_plane *plane)
```

get plane state, if it exists

**Parameters**

- `const struct drm_atomic_state *state`: global atomic state object
- `struct drm_plane *plane`: plane to grab

**Description**

This function returns the old plane state for the given plane, or
NULL if the plane is not part of the global atomic state.

#### <a id="c-drm_atomic_get_new_plane_state"></a>`drm_atomic_get_new_plane_state()`

```c
struct drm_plane_state * drm_atomic_get_new_plane_state(const struct drm_atomic_state *state, struct drm_plane *plane)
```

get plane state, if it exists

**Parameters**

- `const struct drm_atomic_state *state`: global atomic state object
- `struct drm_plane *plane`: plane to grab

**Description**

This function returns the new plane state for the given plane, or
NULL if the plane is not part of the global atomic state.

#### <a id="c-drm_atomic_get_old_connector_state"></a>`drm_atomic_get_old_connector_state()`

```c
struct drm_connector_state * drm_atomic_get_old_connector_state(const struct drm_atomic_state *state, struct drm_connector *connector)
```

get connector state, if it exists

**Parameters**

- `const struct drm_atomic_state *state`: global atomic state object
- `struct drm_connector *connector`: connector to grab

**Description**

This function returns the old connector state for the given connector,
or NULL if the connector is not part of the global atomic state.

#### <a id="c-drm_atomic_get_new_connector_state"></a>`drm_atomic_get_new_connector_state()`

```c
struct drm_connector_state * drm_atomic_get_new_connector_state(const struct drm_atomic_state *state, struct drm_connector *connector)
```

get connector state, if it exists

**Parameters**

- `const struct drm_atomic_state *state`: global atomic state object
- `struct drm_connector *connector`: connector to grab

**Description**

This function returns the new connector state for the given connector,
or NULL if the connector is not part of the global atomic state.

#### <a id="c-__drm_atomic_get_current_plane_state"></a>`__drm_atomic_get_current_plane_state()`

```c
const struct drm_plane_state * __drm_atomic_get_current_plane_state(const struct drm_atomic_state *state, struct drm_plane *plane)
```

get current plane state

**Parameters**

- `const struct drm_atomic_state *state`: global atomic state object
- `struct drm_plane *plane`: plane to grab

**Description**

This function returns the plane state for the given plane, either the
new plane state from **state**, or if the plane isn't part of the atomic
state update, from **plane**. This is useful in atomic check callbacks,
when drivers need to peek at, but not change, state of other planes,
since it avoids threading an error code back up the call chain.

WARNING:

Note that this function is in general unsafe since it doesn't check for the
required locking for access state structures. Drivers must ensure that it is
safe to access the returned state structure through other means. One common
example is when planes are fixed to a single CRTC, and the driver knows that
the CRTC lock is held already. In that case holding the CRTC lock gives a
read-lock on all planes connected to that CRTC. But if planes can be
reassigned things get more tricky. In that case it's better to use
drm_atomic_get_plane_state and wire up full error handling.

Read-only pointer to the current plane state.

#### <a id="c-for_each_oldnew_connector_in_state"></a>`for_each_oldnew_connector_in_state()`

```c
for_each_oldnew_connector_in_state(__state, connector, old_connector_state, new_connector_state, __i)
```

iterate over all connectors in an atomic update

**Parameters**

- `__state`: [`struct drm_atomic_state`](#c-struct-drm_atomic_state) pointer
- `connector`: [`struct drm_connector`](#c-struct-drm_connector) iteration cursor
- `old_connector_state`: [`struct drm_connector_state`](#c-struct-drm_connector_state) iteration cursor for the
  old state
- `new_connector_state`: [`struct drm_connector_state`](#c-struct-drm_connector_state) iteration cursor for the
  new state
- `__i`: int iteration cursor, for macro-internal use

**Description**

This iterates over all connectors in an atomic update, tracking both old and
new state. This is useful in places where the state delta needs to be
considered, for example in atomic check functions.

#### <a id="c-for_each_old_connector_in_state"></a>`for_each_old_connector_in_state()`

```c
for_each_old_connector_in_state(__state, connector, old_connector_state, __i)
```

iterate over all connectors in an atomic update

**Parameters**

- `__state`: [`struct drm_atomic_state`](#c-struct-drm_atomic_state) pointer
- `connector`: [`struct drm_connector`](#c-struct-drm_connector) iteration cursor
- `old_connector_state`: [`struct drm_connector_state`](#c-struct-drm_connector_state) iteration cursor for the
  old state
- `__i`: int iteration cursor, for macro-internal use

**Description**

This iterates over all connectors in an atomic update, tracking only the old
state. This is useful in disable functions, where we need the old state the
hardware is still in.

#### <a id="c-for_each_new_connector_in_state"></a>`for_each_new_connector_in_state()`

```c
for_each_new_connector_in_state(__state, connector, new_connector_state, __i)
```

iterate over all connectors in an atomic update

**Parameters**

- `__state`: [`struct drm_atomic_state`](#c-struct-drm_atomic_state) pointer
- `connector`: [`struct drm_connector`](#c-struct-drm_connector) iteration cursor
- `new_connector_state`: [`struct drm_connector_state`](#c-struct-drm_connector_state) iteration cursor for the
  new state
- `__i`: int iteration cursor, for macro-internal use

**Description**

This iterates over all connectors in an atomic update, tracking only the new
state. This is useful in enable functions, where we need the new state the
hardware should be in when the atomic commit operation has completed.

#### <a id="c-for_each_oldnew_crtc_in_state"></a>`for_each_oldnew_crtc_in_state()`

```c
for_each_oldnew_crtc_in_state(__state, crtc, old_crtc_state, new_crtc_state, __i)
```

iterate over all CRTCs in an atomic update

**Parameters**

- `__state`: [`struct drm_atomic_state`](#c-struct-drm_atomic_state) pointer
- `crtc`: [`struct drm_crtc`](#c-struct-drm_crtc) iteration cursor
- `old_crtc_state`: [`struct drm_crtc_state`](#c-struct-drm_crtc_state) iteration cursor for the old state
- `new_crtc_state`: [`struct drm_crtc_state`](#c-struct-drm_crtc_state) iteration cursor for the new state
- `__i`: int iteration cursor, for macro-internal use

**Description**

This iterates over all CRTCs in an atomic update, tracking both old and
new state. This is useful in places where the state delta needs to be
considered, for example in atomic check functions.

#### <a id="c-for_each_old_crtc_in_state"></a>`for_each_old_crtc_in_state()`

```c
for_each_old_crtc_in_state(__state, crtc, old_crtc_state, __i)
```

iterate over all CRTCs in an atomic update

**Parameters**

- `__state`: [`struct drm_atomic_state`](#c-struct-drm_atomic_state) pointer
- `crtc`: [`struct drm_crtc`](#c-struct-drm_crtc) iteration cursor
- `old_crtc_state`: [`struct drm_crtc_state`](#c-struct-drm_crtc_state) iteration cursor for the old state
- `__i`: int iteration cursor, for macro-internal use

**Description**

This iterates over all CRTCs in an atomic update, tracking only the old
state. This is useful in disable functions, where we need the old state the
hardware is still in.

#### <a id="c-for_each_new_crtc_in_state"></a>`for_each_new_crtc_in_state()`

```c
for_each_new_crtc_in_state(__state, crtc, new_crtc_state, __i)
```

iterate over all CRTCs in an atomic update

**Parameters**

- `__state`: [`struct drm_atomic_state`](#c-struct-drm_atomic_state) pointer
- `crtc`: [`struct drm_crtc`](#c-struct-drm_crtc) iteration cursor
- `new_crtc_state`: [`struct drm_crtc_state`](#c-struct-drm_crtc_state) iteration cursor for the new state
- `__i`: int iteration cursor, for macro-internal use

**Description**

This iterates over all CRTCs in an atomic update, tracking only the new
state. This is useful in enable functions, where we need the new state the
hardware should be in when the atomic commit operation has completed.

#### <a id="c-for_each_oldnew_colorop_in_state"></a>`for_each_oldnew_colorop_in_state()`

```c
for_each_oldnew_colorop_in_state(__state, colorop, old_colorop_state, new_colorop_state, __i)
```

iterate over all colorops in an atomic update

**Parameters**

- `__state`: [`struct drm_atomic_state`](#c-struct-drm_atomic_state) pointer
- `colorop`: [`struct drm_colorop`](#c-struct-drm_colorop) iteration cursor
- `old_colorop_state`: [`struct drm_colorop_state`](#c-struct-drm_colorop_state) iteration cursor for the old state
- `new_colorop_state`: [`struct drm_colorop_state`](#c-struct-drm_colorop_state) iteration cursor for the new state
- `__i`: int iteration cursor, for macro-internal use

**Description**

This iterates over all colorops in an atomic update, tracking both old and
new state. This is useful in places where the state delta needs to be
considered, for example in atomic check functions.

#### <a id="c-for_each_new_colorop_in_state"></a>`for_each_new_colorop_in_state()`

```c
for_each_new_colorop_in_state(__state, colorop, new_colorop_state, __i)
```

iterate over all colorops in an atomic update

**Parameters**

- `__state`: [`struct drm_atomic_state`](#c-struct-drm_atomic_state) pointer
- `colorop`: [`struct drm_colorop`](#c-struct-drm_colorop) iteration cursor
- `new_colorop_state`: [`struct drm_colorop_state`](#c-struct-drm_colorop_state) iteration cursor for the new state
- `__i`: int iteration cursor, for macro-internal use

**Description**

This iterates over all colorops in an atomic update, tracking new state. This is
useful in places where the state delta needs to be considered, for example in
atomic check functions.

#### <a id="c-for_each_oldnew_plane_in_state"></a>`for_each_oldnew_plane_in_state()`

```c
for_each_oldnew_plane_in_state(__state, plane, old_plane_state, new_plane_state, __i)
```

iterate over all planes in an atomic update

**Parameters**

- `__state`: [`struct drm_atomic_state`](#c-struct-drm_atomic_state) pointer
- `plane`: [`struct drm_plane`](#c-struct-drm_plane) iteration cursor
- `old_plane_state`: [`struct drm_plane_state`](#c-struct-drm_plane_state) iteration cursor for the old state
- `new_plane_state`: [`struct drm_plane_state`](#c-struct-drm_plane_state) iteration cursor for the new state
- `__i`: int iteration cursor, for macro-internal use

**Description**

This iterates over all planes in an atomic update, tracking both old and
new state. This is useful in places where the state delta needs to be
considered, for example in atomic check functions.

#### <a id="c-for_each_oldnew_plane_in_state_reverse"></a>`for_each_oldnew_plane_in_state_reverse()`

```c
for_each_oldnew_plane_in_state_reverse(__state, plane, old_plane_state, new_plane_state, __i)
```

iterate over all planes in an atomic update in reverse order

**Parameters**

- `__state`: [`struct drm_atomic_state`](#c-struct-drm_atomic_state) pointer
- `plane`: [`struct drm_plane`](#c-struct-drm_plane) iteration cursor
- `old_plane_state`: [`struct drm_plane_state`](#c-struct-drm_plane_state) iteration cursor for the old state
- `new_plane_state`: [`struct drm_plane_state`](#c-struct-drm_plane_state) iteration cursor for the new state
- `__i`: int iteration cursor, for macro-internal use

**Description**

This iterates over all planes in an atomic update in reverse order,
tracking both old and  new state. This is useful in places where the
state delta needs to be considered, for example in atomic check functions.

#### <a id="c-for_each_new_plane_in_state_reverse"></a>`for_each_new_plane_in_state_reverse()`

```c
for_each_new_plane_in_state_reverse(__state, plane, new_plane_state, __i)
```

other than only tracking new state, it's the same as for_each_oldnew_plane_in_state_reverse

**Parameters**

- `__state`: [`struct drm_atomic_state`](#c-struct-drm_atomic_state) pointer
- `plane`: [`struct drm_plane`](#c-struct-drm_plane) iteration cursor
- `new_plane_state`: [`struct drm_plane_state`](#c-struct-drm_plane_state) iteration cursor for the new state
- `__i`: int iteration cursor, for macro-internal use

#### <a id="c-for_each_old_plane_in_state"></a>`for_each_old_plane_in_state()`

```c
for_each_old_plane_in_state(__state, plane, old_plane_state, __i)
```

iterate over all planes in an atomic update

**Parameters**

- `__state`: [`struct drm_atomic_state`](#c-struct-drm_atomic_state) pointer
- `plane`: [`struct drm_plane`](#c-struct-drm_plane) iteration cursor
- `old_plane_state`: [`struct drm_plane_state`](#c-struct-drm_plane_state) iteration cursor for the old state
- `__i`: int iteration cursor, for macro-internal use

**Description**

This iterates over all planes in an atomic update, tracking only the old
state. This is useful in disable functions, where we need the old state the
hardware is still in.

#### <a id="c-for_each_new_plane_in_state"></a>`for_each_new_plane_in_state()`

```c
for_each_new_plane_in_state(__state, plane, new_plane_state, __i)
```

iterate over all planes in an atomic update

**Parameters**

- `__state`: [`struct drm_atomic_state`](#c-struct-drm_atomic_state) pointer
- `plane`: [`struct drm_plane`](#c-struct-drm_plane) iteration cursor
- `new_plane_state`: [`struct drm_plane_state`](#c-struct-drm_plane_state) iteration cursor for the new state
- `__i`: int iteration cursor, for macro-internal use

**Description**

This iterates over all planes in an atomic update, tracking only the new
state. This is useful in enable functions, where we need the new state the
hardware should be in when the atomic commit operation has completed.

#### <a id="c-for_each_oldnew_private_obj_in_state"></a>`for_each_oldnew_private_obj_in_state()`

```c
for_each_oldnew_private_obj_in_state(__state, obj, old_obj_state, new_obj_state, __i)
```

iterate over all private objects in an atomic update

**Parameters**

- `__state`: [`struct drm_atomic_state`](#c-struct-drm_atomic_state) pointer
- `obj`: [`struct drm_private_obj`](#c-struct-drm_private_obj) iteration cursor
- `old_obj_state`: [`struct drm_private_state`](#c-struct-drm_private_state) iteration cursor for the old state
- `new_obj_state`: [`struct drm_private_state`](#c-struct-drm_private_state) iteration cursor for the new state
- `__i`: int iteration cursor, for macro-internal use

**Description**

This iterates over all private objects in an atomic update, tracking both
old and new state. This is useful in places where the state delta needs
to be considered, for example in atomic check functions.

#### <a id="c-for_each_old_private_obj_in_state"></a>`for_each_old_private_obj_in_state()`

```c
for_each_old_private_obj_in_state(__state, obj, old_obj_state, __i)
```

iterate over all private objects in an atomic update

**Parameters**

- `__state`: [`struct drm_atomic_state`](#c-struct-drm_atomic_state) pointer
- `obj`: [`struct drm_private_obj`](#c-struct-drm_private_obj) iteration cursor
- `old_obj_state`: [`struct drm_private_state`](#c-struct-drm_private_state) iteration cursor for the old state
- `__i`: int iteration cursor, for macro-internal use

**Description**

This iterates over all private objects in an atomic update, tracking only
the old state. This is useful in disable functions, where we need the old
state the hardware is still in.

#### <a id="c-for_each_new_private_obj_in_state"></a>`for_each_new_private_obj_in_state()`

```c
for_each_new_private_obj_in_state(__state, obj, new_obj_state, __i)
```

iterate over all private objects in an atomic update

**Parameters**

- `__state`: [`struct drm_atomic_state`](#c-struct-drm_atomic_state) pointer
- `obj`: [`struct drm_private_obj`](#c-struct-drm_private_obj) iteration cursor
- `new_obj_state`: [`struct drm_private_state`](#c-struct-drm_private_state) iteration cursor for the new state
- `__i`: int iteration cursor, for macro-internal use

**Description**

This iterates over all private objects in an atomic update, tracking only
the new state. This is useful in enable functions, where we need the new state the
hardware should be in when the atomic commit operation has completed.

#### <a id="c-drm_atomic_crtc_needs_modeset"></a>`drm_atomic_crtc_needs_modeset()`

```c
bool drm_atomic_crtc_needs_modeset(const struct drm_crtc_state *state)
```

compute combined modeset need

**Parameters**

- `const struct drm_crtc_state *state`: [`drm_crtc_state`](#c-struct-drm_crtc_state) for the CRTC

**Description**

To give drivers flexibility [`struct drm_crtc_state`](#c-struct-drm_crtc_state) has 3 booleans to track
whether the state CRTC changed enough to need a full modeset cycle:
mode_changed, active_changed and connectors_changed. This helper simply
combines these three to compute the overall need for a modeset for **state**.

The atomic helper code sets these booleans, but drivers can and should
change them appropriately to accurately represent whether a modeset is
really needed. In general, drivers should avoid full modesets whenever
possible.

For example if the CRTC mode has changed, and the hardware is able to enact
the requested mode change without going through a full modeset, the driver
should clear mode_changed in its [`drm_mode_config_funcs.atomic_check`](#c-struct-drm_mode_config_funcs)
implementation.

#### <a id="c-drm_atomic_crtc_effectively_active"></a>`drm_atomic_crtc_effectively_active()`

```c
bool drm_atomic_crtc_effectively_active(const struct drm_crtc_state *state)
```

compute whether CRTC is actually active

**Parameters**

- `const struct drm_crtc_state *state`: [`drm_crtc_state`](#c-struct-drm_crtc_state) for the CRTC

**Description**

When in self refresh mode, the crtc_state->active value will be false, since
the CRTC is off. However in some cases we're interested in whether the CRTC
is active, or effectively active (ie: it's connected to an active display).
In these cases, use this function instead of just checking active.

#### <a id="c-struct-drm_bus_cfg"></a>`struct drm_bus_cfg`

bus configuration

**Definition**

```c
struct drm_bus_cfg {
    u32 format;
    u32 flags;
};
```

**Members**

- `format`: format used on this bus (one of the MEDIA_BUS_FMT_* format)

  This field should not be directly modified by drivers
  (`drm_atomic_bridge_chain_select_bus_fmts()` takes care of the bus
  format negotiation).
- `flags`: DRM_BUS_* flags used on this bus

**Description**

This structure stores the configuration of a physical bus between two
components in an output pipeline, usually between two bridges, an encoder
and a bridge, or a bridge and a connector.

The bus configuration is stored in [`drm_bridge_state`](#c-struct-drm_bridge_state) separately for the
input and output buses, as seen from the point of view of each bridge. The
bus configuration of a bridge output is usually identical to the
configuration of the next bridge's input, but may differ if the signals are
modified between the two bridges, for instance by an inverter on the board.
The input and output configurations of a bridge may differ if the bridge
modifies the signals internally, for instance by performing format
conversion, or modifying signals polarities.

#### <a id="c-struct-drm_bridge_state"></a>`struct drm_bridge_state`

Atomic bridge state object

**Definition**

```c
struct drm_bridge_state {
    struct drm_private_state base;
    struct drm_bridge *bridge;
    struct drm_bus_cfg input_bus_cfg;
    struct drm_bus_cfg output_bus_cfg;
};
```

**Members**

- `base`: inherit from [`drm_private_state`](#c-struct-drm_private_state)
- `bridge`: the bridge this state refers to
- `input_bus_cfg`: input bus configuration
- `output_bus_cfg`: output bus configuration



#### <a id="c-drm_crtc_commit_wait"></a>`drm_crtc_commit_wait()`

```c
int drm_crtc_commit_wait(struct drm_crtc_commit *commit)
```

Waits for a commit to complete

**Parameters**

- `struct drm_crtc_commit *commit`: [`drm_crtc_commit`](#c-struct-drm_crtc_commit) to wait for

**Description**

Waits for a given [`drm_crtc_commit`](#c-struct-drm_crtc_commit) to be programmed into the
hardware and flipped to.

**Return**

0 on success, a negative error code otherwise.

#### <a id="c-drm_atomic_state_default_release"></a>`drm_atomic_state_default_release()`

```c
void drm_atomic_state_default_release(struct drm_atomic_state *state)
```

release memory initialized by drm_atomic_state_init

**Parameters**

- `struct drm_atomic_state *state`: atomic state

**Description**

Free all the memory allocated by drm_atomic_state_init.
This should only be used by drivers which are still subclassing
[`drm_atomic_state`](#c-struct-drm_atomic_state) and haven't switched to [`drm_private_state`](#c-struct-drm_private_state) yet.

#### <a id="c-drm_atomic_state_init"></a>`drm_atomic_state_init()`

```c
int drm_atomic_state_init(struct drm_device *dev, struct drm_atomic_state *state)
```

init new atomic state

**Parameters**

- `struct drm_device *dev`: DRM device
- `struct drm_atomic_state *state`: atomic state

**Description**

Default implementation for filling in a new atomic state.
This should only be used by drivers which are still subclassing
[`drm_atomic_state`](#c-struct-drm_atomic_state) and haven't switched to [`drm_private_state`](#c-struct-drm_private_state) yet.

#### <a id="c-drm_atomic_state_alloc"></a>`drm_atomic_state_alloc()`

```c
struct drm_atomic_state * drm_atomic_state_alloc(struct drm_device *dev)
```

allocate atomic state

**Parameters**

- `struct drm_device *dev`: DRM device

**Description**

This allocates an empty atomic state to track updates.

#### <a id="c-drm_atomic_state_default_clear"></a>`drm_atomic_state_default_clear()`

```c
void drm_atomic_state_default_clear(struct drm_atomic_state *state)
```

clear base atomic state

**Parameters**

- `struct drm_atomic_state *state`: atomic state

**Description**

Default implementation for clearing atomic state.
This should only be used by drivers which are still subclassing
[`drm_atomic_state`](#c-struct-drm_atomic_state) and haven't switched to [`drm_private_state`](#c-struct-drm_private_state) yet.

#### <a id="c-drm_atomic_state_clear"></a>`drm_atomic_state_clear()`

```c
void drm_atomic_state_clear(struct drm_atomic_state *state)
```

clear state object

**Parameters**

- `struct drm_atomic_state *state`: atomic state

**Description**

When the w/w mutex algorithm detects a deadlock we need to back off and drop
all locks. So someone else could sneak in and change the current modeset
configuration. Which means that all the state assembled in **state** is no
longer an atomic update to the current state, but to some arbitrary earlier
state. Which could break assumptions the driver's
[`drm_mode_config_funcs.atomic_check`](#c-struct-drm_mode_config_funcs) likely relies on.

Hence we must clear all cached state and completely start over, using this
function.

#### <a id="c-__drm_atomic_state_free"></a>`__drm_atomic_state_free()`

```c
void __drm_atomic_state_free(struct kref *ref)
```

free all memory for an atomic state

**Parameters**

- `struct kref *ref`: This atomic state to deallocate

**Description**

This frees all memory associated with an atomic state, including all the
per-object state for planes, CRTCs and connectors.

#### <a id="c-drm_atomic_get_crtc_state"></a>`drm_atomic_get_crtc_state()`

```c
struct drm_crtc_state * drm_atomic_get_crtc_state(struct drm_atomic_state *state, struct drm_crtc *crtc)
```

get CRTC state

**Parameters**

- `struct drm_atomic_state *state`: global atomic state object
- `struct drm_crtc *crtc`: CRTC to get state object for

**Description**

This function returns the CRTC state for the given CRTC, allocating it if
needed. It will also grab the relevant CRTC lock to make sure that the state
is consistent.

WARNING: Drivers may only add new CRTC states to a **state** if
drm_atomic_state.allow_modeset is set, or if it's a driver-internal commit
not created by userspace through an IOCTL call.

**Return**

Either the allocated state or the error code encoded into the pointer. When
the error is EDEADLK then the w/w mutex code has detected a deadlock and the
entire atomic sequence must be restarted. All other errors are fatal.

#### <a id="c-drm_atomic_get_plane_state"></a>`drm_atomic_get_plane_state()`

```c
struct drm_plane_state * drm_atomic_get_plane_state(struct drm_atomic_state *state, struct drm_plane *plane)
```

get plane state

**Parameters**

- `struct drm_atomic_state *state`: global atomic state object
- `struct drm_plane *plane`: plane to get state object for

**Description**

This function returns the plane state for the given plane, allocating it if
needed. It will also grab the relevant plane lock to make sure that the state
is consistent.

**Return**

Either the allocated state or the error code encoded into the pointer. When
the error is EDEADLK then the w/w mutex code has detected a deadlock and the
entire atomic sequence must be restarted. All other errors are fatal.

#### <a id="c-drm_atomic_get_colorop_state"></a>`drm_atomic_get_colorop_state()`

```c
struct drm_colorop_state * drm_atomic_get_colorop_state(struct drm_atomic_state *state, struct drm_colorop *colorop)
```

get colorop state

**Parameters**

- `struct drm_atomic_state *state`: global atomic state object
- `struct drm_colorop *colorop`: colorop to get state object for

**Description**

This function returns the colorop state for the given colorop, allocating it
if needed. It will also grab the relevant plane lock to make sure that the
state is consistent.

Either the allocated state or the error code encoded into the pointer. When
the error is EDEADLK then the w/w mutex code has detected a deadlock and the
entire atomic sequence must be restarted. All other errors are fatal.

#### <a id="c-drm_atomic_get_old_colorop_state"></a>`drm_atomic_get_old_colorop_state()`

```c
struct drm_colorop_state * drm_atomic_get_old_colorop_state(struct drm_atomic_state *state, struct drm_colorop *colorop)
```

get colorop state, if it exists

**Parameters**

- `struct drm_atomic_state *state`: global atomic state object
- `struct drm_colorop *colorop`: colorop to grab

**Description**

This function returns the old colorop state for the given colorop, or
NULL if the colorop is not part of the global atomic state.

#### <a id="c-drm_atomic_get_new_colorop_state"></a>`drm_atomic_get_new_colorop_state()`

```c
struct drm_colorop_state * drm_atomic_get_new_colorop_state(struct drm_atomic_state *state, struct drm_colorop *colorop)
```

get colorop state, if it exists

**Parameters**

- `struct drm_atomic_state *state`: global atomic state object
- `struct drm_colorop *colorop`: colorop to grab

**Description**

This function returns the new colorop state for the given colorop, or
NULL if the colorop is not part of the global atomic state.

#### <a id="c-drm_atomic_private_obj_init"></a>`drm_atomic_private_obj_init()`

```c
void drm_atomic_private_obj_init(struct drm_device *dev, struct drm_private_obj *obj, struct drm_private_state *state, const struct drm_private_state_funcs *funcs)
```

initialize private object

**Parameters**

- `struct drm_device *dev`: DRM device this object will be attached to
- `struct drm_private_obj *obj`: private object
- `struct drm_private_state *state`: initial private object state
- `const struct drm_private_state_funcs *funcs`: pointer to the struct of function pointers that identify the object
  type

**Description**

Initialize the private object, which can be embedded into any
driver private object that needs its own atomic state.

#### <a id="c-drm_atomic_private_obj_fini"></a>`drm_atomic_private_obj_fini()`

```c
void drm_atomic_private_obj_fini(struct drm_private_obj *obj)
```

finalize private object

**Parameters**

- `struct drm_private_obj *obj`: private object

**Description**

Finalize the private object.

#### <a id="c-drm_atomic_get_private_obj_state"></a>`drm_atomic_get_private_obj_state()`

```c
struct drm_private_state * drm_atomic_get_private_obj_state(struct drm_atomic_state *state, struct drm_private_obj *obj)
```

get private object state

**Parameters**

- `struct drm_atomic_state *state`: global atomic state
- `struct drm_private_obj *obj`: private object to get the state for

**Description**

This function returns the private object state for the given private object,
allocating the state if needed. It will also grab the relevant private
object lock to make sure that the state is consistent.

**Return**

Either the allocated state or the error code encoded into a pointer.

#### <a id="c-drm_atomic_get_old_private_obj_state"></a>`drm_atomic_get_old_private_obj_state()`

```c
struct drm_private_state * drm_atomic_get_old_private_obj_state(const struct drm_atomic_state *state, struct drm_private_obj *obj)
```

**Parameters**

- `const struct drm_atomic_state *state`: global atomic state object
- `struct drm_private_obj *obj`: private_obj to grab

**Description**

This function returns the old private object state for the given private_obj,
or NULL if the private_obj is not part of the global atomic state.

#### <a id="c-drm_atomic_get_new_private_obj_state"></a>`drm_atomic_get_new_private_obj_state()`

```c
struct drm_private_state * drm_atomic_get_new_private_obj_state(const struct drm_atomic_state *state, struct drm_private_obj *obj)
```

**Parameters**

- `const struct drm_atomic_state *state`: global atomic state object
- `struct drm_private_obj *obj`: private_obj to grab

**Description**

This function returns the new private object state for the given private_obj,
or NULL if the private_obj is not part of the global atomic state.

#### <a id="c-drm_atomic_get_old_connector_for_encoder"></a>`drm_atomic_get_old_connector_for_encoder()`

```c
struct drm_connector * drm_atomic_get_old_connector_for_encoder(const struct drm_atomic_state *state, struct drm_encoder *encoder)
```

Get old connector for an encoder

**Parameters**

- `const struct drm_atomic_state *state`: Atomic state
- `struct drm_encoder *encoder`: The encoder to fetch the connector state for

**Description**

This function finds and returns the connector that was connected to **encoder**
as specified by the **state**.

If there is no connector in **state** which previously had **encoder** connected to
it, this function will return NULL. While this may seem like an invalid use
case, it is sometimes useful to differentiate commits which had no prior
connectors attached to **encoder** vs ones that did (and to inspect their
state). This is especially true in enable hooks because the pipeline has
changed.

If you don't have access to the atomic state, see
[`drm_atomic_get_connector_for_encoder()`](#c-drm_atomic_get_connector_for_encoder).

**Return**

The old connector connected to **encoder**, or NULL if the encoder is
not connected.

#### <a id="c-drm_atomic_get_new_connector_for_encoder"></a>`drm_atomic_get_new_connector_for_encoder()`

```c
struct drm_connector * drm_atomic_get_new_connector_for_encoder(const struct drm_atomic_state *state, struct drm_encoder *encoder)
```

Get new connector for an encoder

**Parameters**

- `const struct drm_atomic_state *state`: Atomic state
- `struct drm_encoder *encoder`: The encoder to fetch the connector state for

**Description**

This function finds and returns the connector that will be connected to
**encoder** as specified by the **state**.

If there is no connector in **state** which will have **encoder** connected to it,
this function will return NULL. While this may seem like an invalid use case,
it is sometimes useful to differentiate commits which have no connectors
attached to **encoder** vs ones that do (and to inspect their state). This is
especially true in disable hooks because the pipeline will change.

If you don't have access to the atomic state, see
[`drm_atomic_get_connector_for_encoder()`](#c-drm_atomic_get_connector_for_encoder).

**Return**

The new connector connected to **encoder**, or NULL if the encoder is
not connected.

#### <a id="c-drm_atomic_get_connector_for_encoder"></a>`drm_atomic_get_connector_for_encoder()`

```c
struct drm_connector * drm_atomic_get_connector_for_encoder(const struct drm_encoder *encoder, struct drm_modeset_acquire_ctx *ctx)
```

Get connector currently assigned to an encoder

**Parameters**

- `const struct drm_encoder *encoder`: The encoder to find the connector of
- `struct drm_modeset_acquire_ctx *ctx`: Modeset locking context

**Description**

This function finds and returns the connector currently assigned to
an **encoder**.

It is similar to the [`drm_atomic_get_old_connector_for_encoder()`](#c-drm_atomic_get_old_connector_for_encoder) and
[`drm_atomic_get_new_connector_for_encoder()`](#c-drm_atomic_get_new_connector_for_encoder) helpers, but doesn't
require access to the atomic state. If you have access to it, prefer
using these. This helper is typically useful in situations where you
don't have access to the atomic state, like detect, link repair,
threaded interrupt handlers, or hooks from other frameworks (ALSA,
CEC, etc.).

**Return**

The connector connected to **encoder**, or an error pointer otherwise.
When the error is EDEADLK, a deadlock has been detected and the
sequence must be restarted.

#### <a id="c-drm_atomic_get_old_crtc_for_encoder"></a>`drm_atomic_get_old_crtc_for_encoder()`

```c
struct drm_crtc * drm_atomic_get_old_crtc_for_encoder(struct drm_atomic_state *state, struct drm_encoder *encoder)
```

Get old crtc for an encoder

**Parameters**

- `struct drm_atomic_state *state`: Atomic state
- `struct drm_encoder *encoder`: The encoder to fetch the crtc state for

**Description**

This function finds and returns the crtc that was connected to **encoder**
as specified by the **state**.

**Return**

The old crtc connected to **encoder**, or NULL if the encoder is
not connected.

#### <a id="c-drm_atomic_get_new_crtc_for_encoder"></a>`drm_atomic_get_new_crtc_for_encoder()`

```c
struct drm_crtc * drm_atomic_get_new_crtc_for_encoder(struct drm_atomic_state *state, struct drm_encoder *encoder)
```

Get new crtc for an encoder

**Parameters**

- `struct drm_atomic_state *state`: Atomic state
- `struct drm_encoder *encoder`: The encoder to fetch the crtc state for

**Description**

This function finds and returns the crtc that will be connected to **encoder**
as specified by the **state**.

**Return**

The new crtc connected to **encoder**, or NULL if the encoder is
not connected.

#### <a id="c-drm_atomic_get_connector_state"></a>`drm_atomic_get_connector_state()`

```c
struct drm_connector_state * drm_atomic_get_connector_state(struct drm_atomic_state *state, struct drm_connector *connector)
```

get connector state

**Parameters**

- `struct drm_atomic_state *state`: global atomic state object
- `struct drm_connector *connector`: connector to get state object for

**Description**

This function returns the connector state for the given connector,
allocating it if needed. It will also grab the relevant connector lock to
make sure that the state is consistent.

**Return**

Either the allocated state or the error code encoded into the pointer. When
the error is EDEADLK then the w/w mutex code has detected a deadlock and the
entire atomic sequence must be restarted. All other errors are fatal.

#### <a id="c-drm_atomic_get_bridge_state"></a>`drm_atomic_get_bridge_state()`

```c
struct drm_bridge_state * drm_atomic_get_bridge_state(struct drm_atomic_state *state, struct drm_bridge *bridge)
```

get bridge state

**Parameters**

- `struct drm_atomic_state *state`: global atomic state object
- `struct drm_bridge *bridge`: bridge to get state object for

**Description**

This function returns the bridge state for the given bridge, allocating it
if needed. It will also grab the relevant bridge lock to make sure that the
state is consistent.

**Return**

Either the allocated state or the error code encoded into the pointer. When
the error is EDEADLK then the w/w mutex code has detected a deadlock and the
entire atomic sequence must be restarted.

#### <a id="c-drm_atomic_get_old_bridge_state"></a>`drm_atomic_get_old_bridge_state()`

```c
struct drm_bridge_state * drm_atomic_get_old_bridge_state(const struct drm_atomic_state *state, struct drm_bridge *bridge)
```

get old bridge state, if it exists

**Parameters**

- `const struct drm_atomic_state *state`: global atomic state object
- `struct drm_bridge *bridge`: bridge to grab

**Description**

This function returns the old bridge state for the given bridge, or NULL if
the bridge is not part of the global atomic state.

#### <a id="c-drm_atomic_get_new_bridge_state"></a>`drm_atomic_get_new_bridge_state()`

```c
struct drm_bridge_state * drm_atomic_get_new_bridge_state(const struct drm_atomic_state *state, struct drm_bridge *bridge)
```

get new bridge state, if it exists

**Parameters**

- `const struct drm_atomic_state *state`: global atomic state object
- `struct drm_bridge *bridge`: bridge to grab

**Description**

This function returns the new bridge state for the given bridge, or NULL if
the bridge is not part of the global atomic state.

#### <a id="c-drm_atomic_add_encoder_bridges"></a>`drm_atomic_add_encoder_bridges()`

```c
int drm_atomic_add_encoder_bridges(struct drm_atomic_state *state, struct drm_encoder *encoder)
```

add bridges attached to an encoder

**Parameters**

- `struct drm_atomic_state *state`: atomic state
- `struct drm_encoder *encoder`: DRM encoder

**Description**

This function adds all bridges attached to **encoder**. This is needed to add
bridge states to **state** and make them available when
[`drm_bridge_funcs.atomic_check()`](/kernel/hardware/gpu/drm-kms-helpers.md#c-struct-drm_bridge_funcs), [`drm_bridge_funcs.atomic_pre_enable()`](/kernel/hardware/gpu/drm-kms-helpers.md#c-struct-drm_bridge_funcs),
[`drm_bridge_funcs.atomic_enable()`](/kernel/hardware/gpu/drm-kms-helpers.md#c-struct-drm_bridge_funcs),
[`drm_bridge_funcs.atomic_disable_post_disable()`](/kernel/hardware/gpu/drm-kms-helpers.md#c-struct-drm_bridge_funcs) are called.

**Return**

0 on success or can fail with -EDEADLK or -ENOMEM. When the error is EDEADLK
then the w/w mutex code has detected a deadlock and the entire atomic
sequence must be restarted. All other errors are fatal.

#### <a id="c-drm_atomic_add_affected_connectors"></a>`drm_atomic_add_affected_connectors()`

```c
int drm_atomic_add_affected_connectors(struct drm_atomic_state *state, struct drm_crtc *crtc)
```

add connectors for CRTC

**Parameters**

- `struct drm_atomic_state *state`: atomic state
- `struct drm_crtc *crtc`: DRM CRTC

**Description**

This function walks the current configuration and adds all connectors
currently using **crtc** to the atomic configuration **state**. Note that this
function must acquire the connection mutex. This can potentially cause
unneeded serialization if the update is just for the planes on one CRTC. Hence
drivers and helpers should only call this when really needed (e.g. when a
full modeset needs to happen due to some change).

**Return**

0 on success or can fail with -EDEADLK or -ENOMEM. When the error is EDEADLK
then the w/w mutex code has detected a deadlock and the entire atomic
sequence must be restarted. All other errors are fatal.

#### <a id="c-drm_atomic_add_affected_planes"></a>`drm_atomic_add_affected_planes()`

```c
int drm_atomic_add_affected_planes(struct drm_atomic_state *state, struct drm_crtc *crtc)
```

add planes for CRTC

**Parameters**

- `struct drm_atomic_state *state`: atomic state
- `struct drm_crtc *crtc`: DRM CRTC

**Description**

This function walks the current configuration and adds all planes
currently used by **crtc** to the atomic configuration **state**. This is useful
when an atomic commit also needs to check all currently enabled plane on
**crtc**, e.g. when changing the mode. It's also useful when re-enabling a CRTC
to avoid special code to force-enable all planes.

Since acquiring a plane state will always also acquire the w/w mutex of the
current CRTC for that plane (if there is any) adding all the plane states for
a CRTC will not reduce parallelism of atomic updates.

**Return**

0 on success or can fail with -EDEADLK or -ENOMEM. When the error is EDEADLK
then the w/w mutex code has detected a deadlock and the entire atomic
sequence must be restarted. All other errors are fatal.

#### <a id="c-drm_atomic_add_affected_colorops"></a>`drm_atomic_add_affected_colorops()`

```c
int drm_atomic_add_affected_colorops(struct drm_atomic_state *state, struct drm_plane *plane)
```

add colorops for plane

**Parameters**

- `struct drm_atomic_state *state`: atomic state
- `struct drm_plane *plane`: DRM plane

**Description**

This function walks the current configuration and adds all colorops
currently used by **plane** to the atomic configuration **state**. This is useful
when an atomic commit also needs to check all currently enabled colorop on
**plane**, e.g. when changing the mode. It's also useful when re-enabling a plane
to avoid special code to force-enable all colorops.

Since acquiring a colorop state will always also acquire the w/w mutex of the
current plane for that colorop (if there is any) adding all the colorop states for
a plane will not reduce parallelism of atomic updates.

**Return**

0 on success or can fail with -EDEADLK or -ENOMEM. When the error is EDEADLK
then the w/w mutex code has detected a deadlock and the entire atomic
sequence must be restarted. All other errors are fatal.

#### <a id="c-drm_atomic_check_only"></a>`drm_atomic_check_only()`

```c
int drm_atomic_check_only(struct drm_atomic_state *state)
```

check whether a given config would work

**Parameters**

- `struct drm_atomic_state *state`: atomic configuration to check

**Description**

Note that this function can return -EDEADLK if the driver needed to acquire
more locks but encountered a deadlock. The caller must then do the usual w/w
backoff dance and restart. All other errors are fatal.

**Return**

0 on success, negative error code on failure.

#### <a id="c-drm_atomic_commit"></a>`drm_atomic_commit()`

```c
int drm_atomic_commit(struct drm_atomic_state *state)
```

commit configuration atomically

**Parameters**

- `struct drm_atomic_state *state`: atomic configuration to check

**Description**

Note that this function can return -EDEADLK if the driver needed to acquire
more locks but encountered a deadlock. The caller must then do the usual w/w
backoff dance and restart. All other errors are fatal.

This function will take its own reference on **state**.
Callers should always release their reference with [`drm_atomic_state_put()`](#c-drm_atomic_state_put).

**Return**

0 on success, negative error code on failure.

#### <a id="c-drm_atomic_nonblocking_commit"></a>`drm_atomic_nonblocking_commit()`

```c
int drm_atomic_nonblocking_commit(struct drm_atomic_state *state)
```

atomic nonblocking commit

**Parameters**

- `struct drm_atomic_state *state`: atomic configuration to check

**Description**

Note that this function can return -EDEADLK if the driver needed to acquire
more locks but encountered a deadlock. The caller must then do the usual w/w
backoff dance and restart. All other errors are fatal.

This function will take its own reference on **state**.
Callers should always release their reference with [`drm_atomic_state_put()`](#c-drm_atomic_state_put).

**Return**

0 on success, negative error code on failure.

#### <a id="c-drm_atomic_print_new_state"></a>`drm_atomic_print_new_state()`

```c
void drm_atomic_print_new_state(const struct drm_atomic_state *state, struct drm_printer *p)
```

prints drm atomic state

**Parameters**

- `const struct drm_atomic_state *state`: atomic configuration to check
- `struct drm_printer *p`: drm printer

**Description**

This functions prints the drm atomic state snapshot using the drm printer
which is passed to it. This snapshot can be used for debugging purposes.

Note that this function looks into the new state objects and hence its not
safe to be used after the call to [`drm_atomic_helper_commit_hw_done()`](/kernel/hardware/gpu/drm-kms-helpers.md#c-drm_atomic_helper_commit_hw_done).

#### <a id="c-drm_state_dump"></a>`drm_state_dump()`

```c
void drm_state_dump(struct drm_device *dev, struct drm_printer *p)
```

dump entire device atomic state

**Parameters**

- `struct drm_device *dev`: the drm device
- `struct drm_printer *p`: where to print the state to

**Description**

Just for debugging.  Drivers might want an option to dump state
to dmesg in case of error irq's.  (Hint, you probably want to
ratelimit this!)

The caller must wrap this [`drm_modeset_lock_all_ctx()`](#c-drm_modeset_lock_all_ctx) and
[`drm_modeset_drop_locks()`](#c-drm_modeset_drop_locks). If this is called from error irq handler, it should
not be enabled by default - if you are debugging errors you might
not care that this is racey, but calling this without all modeset locks held
is inherently unsafe.


<a id="rst-atomic-mode-setting-ioctl-and-uapi-functions"></a>

### Atomic Mode Setting IOCTL and UAPI Functions


This file contains the marshalling and demarshalling glue for the atomic UAPI
in all its forms: The monster ATOMIC IOCTL itself, code for GET_PROPERTY and
SET_PROPERTY IOCTLs. Plus interface functions for compatibility helpers and
drivers which have special needs to construct their own atomic updates, e.g.
for load detect or similar.



#### <a id="c-drm_atomic_set_mode_for_crtc"></a>`drm_atomic_set_mode_for_crtc()`

```c
int drm_atomic_set_mode_for_crtc(struct drm_crtc_state *state, const struct drm_display_mode *mode)
```

set mode for CRTC

**Parameters**

- `struct drm_crtc_state *state`: the CRTC whose incoming state to update
- `const struct drm_display_mode *mode`: kernel-internal mode to use for the CRTC, or NULL to disable

**Description**

Set a mode (originating from the kernel) on the desired CRTC state and update
the enable property.

**Return**

Zero on success, error code on failure. Cannot return -EDEADLK.

#### <a id="c-drm_atomic_set_mode_prop_for_crtc"></a>`drm_atomic_set_mode_prop_for_crtc()`

```c
int drm_atomic_set_mode_prop_for_crtc(struct drm_crtc_state *state, struct drm_property_blob *blob)
```

set mode for CRTC

**Parameters**

- `struct drm_crtc_state *state`: the CRTC whose incoming state to update
- `struct drm_property_blob *blob`: pointer to blob property to use for mode

**Description**

Set a mode (originating from a blob property) on the desired CRTC state.
This function will take a reference on the blob property for the CRTC state,
and release the reference held on the state's existing mode property, if any
was set.

**Return**

Zero on success, error code on failure. Cannot return -EDEADLK.

#### <a id="c-drm_atomic_set_crtc_for_plane"></a>`drm_atomic_set_crtc_for_plane()`

```c
int drm_atomic_set_crtc_for_plane(struct drm_plane_state *plane_state, struct drm_crtc *crtc)
```

set CRTC for plane

**Parameters**

- `struct drm_plane_state *plane_state`: the plane whose incoming state to update
- `struct drm_crtc *crtc`: CRTC to use for the plane

**Description**

Changing the assigned CRTC for a plane requires us to grab the lock and state
for the new CRTC, as needed. This function takes care of all these details
besides updating the pointer in the state object itself.

**Return**

0 on success or can fail with -EDEADLK or -ENOMEM. When the error is EDEADLK
then the w/w mutex code has detected a deadlock and the entire atomic
sequence must be restarted. All other errors are fatal.

#### <a id="c-drm_atomic_set_fb_for_plane"></a>`drm_atomic_set_fb_for_plane()`

```c
void drm_atomic_set_fb_for_plane(struct drm_plane_state *plane_state, struct drm_framebuffer *fb)
```

set framebuffer for plane

**Parameters**

- `struct drm_plane_state *plane_state`: atomic state object for the plane
- `struct drm_framebuffer *fb`: fb to use for the plane

**Description**

Changing the assigned framebuffer for a plane requires us to grab a reference
to the new fb and drop the reference to the old fb, if there is one. This
function takes care of all these details besides updating the pointer in the
state object itself.

#### <a id="c-drm_atomic_set_colorop_for_plane"></a>`drm_atomic_set_colorop_for_plane()`

```c
void drm_atomic_set_colorop_for_plane(struct drm_plane_state *plane_state, struct drm_colorop *colorop)
```

set colorop for plane

**Parameters**

- `struct drm_plane_state *plane_state`: atomic state object for the plane
- `struct drm_colorop *colorop`: colorop to use for the plane

**Description**

Helper function to select the color pipeline on a plane by setting
it to the first drm_colorop element of the pipeline.

#### <a id="c-drm_atomic_set_crtc_for_connector"></a>`drm_atomic_set_crtc_for_connector()`

```c
int drm_atomic_set_crtc_for_connector(struct drm_connector_state *conn_state, struct drm_crtc *crtc)
```

set CRTC for connector

**Parameters**

- `struct drm_connector_state *conn_state`: atomic state object for the connector
- `struct drm_crtc *crtc`: CRTC to use for the connector

**Description**

Changing the assigned CRTC for a connector requires us to grab the lock and
state for the new CRTC, as needed. This function takes care of all these
details besides updating the pointer in the state object itself.

**Return**

0 on success or can fail with -EDEADLK or -ENOMEM. When the error is EDEADLK
then the w/w mutex code has detected a deadlock and the entire atomic
sequence must be restarted. All other errors are fatal.


<a id="rst-crtc-abstraction"></a>

## CRTC Abstraction


A CRTC represents the overall display pipeline. It receives pixel data from
[`drm_plane`](#c-struct-drm_plane) and blends them together. The [`drm_display_mode`](#c-struct-drm_display_mode) is also attached
to the CRTC, specifying display timings. On the output side the data is fed
to one or more [`drm_encoder`](#c-struct-drm_encoder), which are then each connected to one
[`drm_connector`](#c-struct-drm_connector).

To create a CRTC, a KMS driver allocates and zeroes an instance of
[`struct drm_crtc`](#c-struct-drm_crtc) (possibly as part of a larger structure) and registers it
with a call to [`drm_crtc_init_with_planes()`](#c-drm_crtc_init_with_planes).

The CRTC is also the entry point for legacy modeset operations (see
[`drm_crtc_funcs.set_config`](#c-struct-drm_crtc_funcs)), legacy plane operations (see
[`drm_crtc_funcs.page_flip`](#c-struct-drm_crtc_funcs) and [`drm_crtc_funcs.cursor_set2`](#c-struct-drm_crtc_funcs)), and other legacy
operations like [`drm_crtc_funcs.gamma_set`](#c-struct-drm_crtc_funcs). For atomic drivers all these
features are controlled through [`drm_property`](#c-struct-drm_property) and
[`drm_mode_config_funcs.atomic_check`](#c-struct-drm_mode_config_funcs).


<a id="rst-crtc-functions-reference"></a>

### CRTC Functions Reference


#### <a id="c-struct-drm_crtc_state"></a>`struct drm_crtc_state`

mutable CRTC state

**Definition**

```c
struct drm_crtc_state {
    struct drm_crtc *crtc;
    bool enable;
    bool active;
    bool planes_changed : 1;
    bool mode_changed : 1;
    bool active_changed : 1;
    bool connectors_changed : 1;
    bool zpos_changed : 1;
    bool color_mgmt_changed : 1;
    bool no_vblank;
    u32 plane_mask;
    u32 connector_mask;
    u32 encoder_mask;
    struct drm_display_mode adjusted_mode;
    struct drm_display_mode mode;
    struct drm_property_blob *mode_blob;
    struct drm_property_blob *degamma_lut;
    struct drm_property_blob *ctm;
    struct drm_property_blob *gamma_lut;
    u32 target_vblank;
    bool async_flip;
    bool vrr_enabled;
    bool self_refresh_active;
    enum drm_scaling_filter scaling_filter;
    u8 sharpness_strength;
    struct drm_pending_vblank_event *event;
    struct drm_crtc_commit *commit;
    struct drm_atomic_state *state;
};
```

**Members**

- `crtc`: backpointer to the CRTC
- `enable`: Whether the CRTC should be enabled, gates all other state.
  This controls reservations of shared resources. Actual hardware state
  is controlled by **active**.
- `active`: Whether the CRTC is actively displaying (used for DPMS).
  Implies that **enable** is set. The driver must not release any shared
  resources if **active** is set to false but **enable** still true, because
  userspace expects that a DPMS ON always succeeds.

  Hence drivers must not consult **active** in their various
  [`drm_mode_config_funcs.atomic_check`](#c-struct-drm_mode_config_funcs) callback to reject an atomic
  commit. They can consult it to aid in the computation of derived
  hardware state, since even in the DPMS OFF state the display hardware
  should be as much powered down as when the CRTC is completely
  disabled through setting **enable** to false.
- `planes_changed`: Planes on this crtc are updated. Used by the atomic
  helpers and drivers to steer the atomic commit control flow.
- `mode_changed`:

  **mode** or **enable** has been changed. Used by the atomic
  helpers and drivers to steer the atomic commit control flow. See also
  [`drm_atomic_crtc_needs_modeset()`](#c-drm_atomic_crtc_needs_modeset).

  Drivers are supposed to set this for any CRTC state changes that
  require a full modeset. They can also reset it to false if e.g. a
  **mode** change can be done without a full modeset by only changing
  scaler settings.
- `active_changed`:

  **active** has been toggled. Used by the atomic
  helpers and drivers to steer the atomic commit control flow. See also
  [`drm_atomic_crtc_needs_modeset()`](#c-drm_atomic_crtc_needs_modeset).
- `connectors_changed`: Connectors to this crtc have been updated,
  either in their state or routing. Used by the atomic
  helpers and drivers to steer the atomic commit control flow. See also
  [`drm_atomic_crtc_needs_modeset()`](#c-drm_atomic_crtc_needs_modeset).

  Drivers are supposed to set this as-needed from their own atomic
  check code, e.g. from [`drm_encoder_helper_funcs.atomic_check`](/kernel/hardware/gpu/drm-kms-helpers.md#c-struct-drm_encoder_helper_funcs)
- `zpos_changed`: zpos values of planes on this crtc have been updated.
  Used by the atomic helpers and drivers to steer the atomic commit
  control flow.
- `color_mgmt_changed`: Color management properties have changed
  (**gamma_lut**, **degamma_lut** or **ctm**). Used by the atomic helpers and
  drivers to steer the atomic commit control flow.
- `no_vblank`: Reflects the ability of a CRTC to send VBLANK events. This state
  usually depends on the pipeline configuration. If set to true, DRM
  atomic helpers will send out a fake VBLANK event during display
  updates after all hardware changes have been committed. This is
  implemented in [`drm_atomic_helper_fake_vblank()`](/kernel/hardware/gpu/drm-kms-helpers.md#c-drm_atomic_helper_fake_vblank).

  One usage is for drivers and/or hardware without support for VBLANK
  interrupts. Such drivers typically do not initialize vblanking
  (i.e., call [`drm_vblank_init()`](#c-drm_vblank_init) with the number of CRTCs). For CRTCs
  without initialized vblanking, this field is set to true in
  [`drm_atomic_helper_check_modeset()`](/kernel/hardware/gpu/drm-kms-helpers.md#c-drm_atomic_helper_check_modeset), and a fake VBLANK event will be
  send out on each update of the display pipeline by
  [`drm_atomic_helper_fake_vblank()`](/kernel/hardware/gpu/drm-kms-helpers.md#c-drm_atomic_helper_fake_vblank).

  Another usage is CRTCs feeding a writeback connector operating in
  oneshot mode. In this case the fake VBLANK event is only generated
  when a job is queued to the writeback connector, and we want the
  core to fake VBLANK events when this part of the pipeline hasn't
  changed but others had or when the CRTC and connectors are being
  disabled.

  [`__drm_atomic_helper_crtc_duplicate_state()`](/kernel/hardware/gpu/drm-kms-helpers.md#c-__drm_atomic_helper_crtc_duplicate_state) will not reset the value
  from the current state, the CRTC driver is then responsible for
  updating this field when needed.

  Note that the combination of [`drm_crtc_state.event`](#c-struct-drm_crtc_state) == NULL and
  [`drm_crtc_state.no_blank`](#c-struct-drm_crtc_state) == true is valid and usually used when the
  writeback connector attached to the CRTC has a new job queued. In
  this case the driver will send the VBLANK event on its own when the
  writeback job is complete.
- `plane_mask`: Bitmask of drm_plane_mask(plane) of planes attached to
  this CRTC.
- `connector_mask`: Bitmask of drm_connector_mask(connector) of
  connectors attached to this CRTC.
- `encoder_mask`: Bitmask of drm_encoder_mask(encoder) of encoders
  attached to this CRTC.
- `adjusted_mode`: Internal display timings which can be used by the driver to handle
  differences between the mode requested by userspace in **mode** and what
  is actually programmed into the hardware.

  For drivers using [`drm_bridge`](/kernel/hardware/gpu/drm-kms-helpers.md#c-struct-drm_bridge), this stores hardware display timings
  used between the CRTC and the first bridge. For other drivers, the
  meaning of the adjusted_mode field is purely driver implementation
  defined information, and will usually be used to store the hardware
  display timings used between the CRTC and encoder blocks.
- `mode`: Display timings requested by userspace. The driver should try to
  match the refresh rate as close as possible (but note that it's
  undefined what exactly is close enough, e.g. some of the HDMI modes
  only differ in less than 1% of the refresh rate). The active width
  and height as observed by userspace for positioning planes must match
  exactly.

  For external connectors where the sink isn't fixed (like with a
  built-in panel), this mode here should match the physical mode on the
  wire to the last details (i.e. including sync polarities and
  everything).
- `mode_blob`: [`drm_property_blob`](#c-struct-drm_property_blob) for **mode**, for exposing the mode to
  atomic userspace.
- `degamma_lut`: Lookup table for converting framebuffer pixel data before apply the
  color conversion matrix **ctm**. See [`drm_crtc_enable_color_mgmt()`](#c-drm_crtc_enable_color_mgmt). The
  blob (if not NULL) is an array of `struct drm_color_lut`.
- `ctm`: Color transformation matrix. See [`drm_crtc_enable_color_mgmt()`](#c-drm_crtc_enable_color_mgmt). The
  blob (if not NULL) is a `struct drm_color_ctm`.
- `gamma_lut`: Lookup table for converting pixel data after the color conversion
  matrix **ctm**.  See [`drm_crtc_enable_color_mgmt()`](#c-drm_crtc_enable_color_mgmt). The blob (if not
  NULL) is an array of `struct drm_color_lut`.

  Note that for mostly historical reasons stemming from Xorg heritage,
  this is also used to store the color map (also sometimes color lut,
  CLUT or color palette) for indexed formats like DRM_FORMAT_C8.
- `target_vblank`: Target vertical blank period when a page flip
  should take effect.
- `async_flip`: This is set when DRM_MODE_PAGE_FLIP_ASYNC is set in the legacy
  PAGE_FLIP IOCTL. It's not wired up for the atomic IOCTL itself yet.
- `vrr_enabled`: Indicates if variable refresh rate should be enabled for the CRTC.
  Support for the requested vrr state will depend on driver and
  hardware capabiltiy - lacking support is not treated as failure.
- `self_refresh_active`: Used by the self refresh helpers to denote when a self refresh
  transition is occurring. This will be set on enable/disable callbacks
  when self refresh is being enabled or disabled. In some cases, it may
  not be desirable to fully shut off the crtc during self refresh.
  CRTC's can inspect this flag and determine the best course of action.
- `scaling_filter`: Scaling filter to be applied
- `sharpness_strength`: Used by the user to set the sharpness intensity.
  The value ranges from 0-255.
  Default value is 0 which disable the sharpness feature.
  Any value greater than 0 enables sharpening with the
  specified strength.
- `event`: Optional pointer to a DRM event to signal upon completion of the
  state update. The driver must send out the event when the atomic
  commit operation completes. There are two cases:

  - The event is for a CRTC which is being disabled through this
    atomic commit. In that case the event can be send out any time
    after the hardware has stopped scanning out the current
    framebuffers. It should contain the timestamp and counter for the
    last vblank before the display pipeline was shut off. The simplest
    way to achieve that is calling [`drm_crtc_send_vblank_event()`](#c-drm_crtc_send_vblank_event)
    somewhen after [`drm_crtc_vblank_off()`](#c-drm_crtc_vblank_off) has been called.

  - For a CRTC which is enabled at the end of the commit (even when it
    undergoes an full modeset) the vblank timestamp and counter must
    be for the vblank right before the first frame that scans out the
    new set of buffers. Again the event can only be sent out after the
    hardware has stopped scanning out the old buffers.

  - Events for disabled CRTCs are not allowed, and drivers can ignore
    that case.

  For very simple hardware without VBLANK interrupt, enabling
  [`struct drm_crtc_state`](#c-struct-drm_crtc_state).no_vblank makes DRM's atomic commit helpers
  send a fake VBLANK event at the end of the display update after all
  hardware changes have been applied. See
  [`drm_atomic_helper_fake_vblank()`](/kernel/hardware/gpu/drm-kms-helpers.md#c-drm_atomic_helper_fake_vblank).

  For more complex hardware this
  can be handled by the [`drm_crtc_send_vblank_event()`](#c-drm_crtc_send_vblank_event) function,
  which the driver should call on the provided event upon completion of
  the atomic commit. Note that if the driver supports vblank signalling
  and timestamping the vblank counters and timestamps must agree with
  the ones returned from page flip events. With the current vblank
  helper infrastructure this can be achieved by holding a vblank
  reference while the page flip is pending, acquired through
  [`drm_crtc_vblank_get()`](#c-drm_crtc_vblank_get) and released with [`drm_crtc_vblank_put()`](#c-drm_crtc_vblank_put).
  Drivers are free to implement their own vblank counter and timestamp
  tracking though, e.g. if they have accurate timestamp registers in
  hardware.

  For hardware which supports some means to synchronize vblank
  interrupt delivery with committing display state there's also
  [`drm_crtc_arm_vblank_event()`](#c-drm_crtc_arm_vblank_event). See the documentation of that function
  for a detailed discussion of the constraints it needs to be used
  safely.

  If the device can't notify of flip completion in a race-free way
  at all, then the event should be armed just after the page flip is
  committed. In the worst case the driver will send the event to
  userspace one frame too late. This doesn't allow for a real atomic
  update, but it should avoid tearing.
- `commit`: This tracks how the commit for this update proceeds through the
  various phases. This is never cleared, except when we destroy the
  state, so that subsequent commits can synchronize with previous ones.
- `state`: backpointer to global drm_atomic_state

**Description**

Note that the distinction between **enable** and **active** is rather subtle:
Flipping **active** while **enable** is set without changing anything else may
never return in a failure from the [`drm_mode_config_funcs.atomic_check`](#c-struct-drm_mode_config_funcs)
callback. Userspace assumes that a DPMS On will always succeed. In other
words: **enable** controls resource assignment, **active** controls the actual
hardware state.

The three booleans active_changed, connectors_changed and mode_changed are
intended to indicate whether a full modeset is needed, rather than strictly
describing what has changed in a commit. See also:
[`drm_atomic_crtc_needs_modeset()`](#c-drm_atomic_crtc_needs_modeset)

#### <a id="c-struct-drm_crtc_funcs"></a>`struct drm_crtc_funcs`

control CRTCs for a given device

**Definition**

```c
struct drm_crtc_funcs {
    void (*reset)(struct drm_crtc *crtc);
    int (*cursor_set)(struct drm_crtc *crtc, struct drm_file *file_priv, uint32_t handle, uint32_t width, uint32_t height);
    int (*cursor_set2)(struct drm_crtc *crtc, struct drm_file *file_priv, uint32_t handle, uint32_t width, uint32_t height, int32_t hot_x, int32_t hot_y);
    int (*cursor_move)(struct drm_crtc *crtc, int x, int y);
    int (*gamma_set)(struct drm_crtc *crtc, u16 *r, u16 *g, u16 *b, uint32_t size, struct drm_modeset_acquire_ctx *ctx);
    void (*destroy)(struct drm_crtc *crtc);
    int (*set_config)(struct drm_mode_set *set, struct drm_modeset_acquire_ctx *ctx);
    int (*page_flip)(struct drm_crtc *crtc, struct drm_framebuffer *fb, struct drm_pending_vblank_event *event, uint32_t flags, struct drm_modeset_acquire_ctx *ctx);
    int (*page_flip_target)(struct drm_crtc *crtc, struct drm_framebuffer *fb, struct drm_pending_vblank_event *event, uint32_t flags, uint32_t target, struct drm_modeset_acquire_ctx *ctx);
    int (*set_property)(struct drm_crtc *crtc, struct drm_property *property, uint64_t val);
    struct drm_crtc_state *(*atomic_duplicate_state)(struct drm_crtc *crtc);
    void (*atomic_destroy_state)(struct drm_crtc *crtc, struct drm_crtc_state *state);
    int (*atomic_set_property)(struct drm_crtc *crtc, struct drm_crtc_state *state, struct drm_property *property, uint64_t val);
    int (*atomic_get_property)(struct drm_crtc *crtc, const struct drm_crtc_state *state, struct drm_property *property, uint64_t *val);
    int (*late_register)(struct drm_crtc *crtc);
    void (*early_unregister)(struct drm_crtc *crtc);
    int (*set_crc_source)(struct drm_crtc *crtc, const char *source);
    int (*verify_crc_source)(struct drm_crtc *crtc, const char *source, size_t *values_cnt);
    const char *const *(*get_crc_sources)(struct drm_crtc *crtc, size_t *count);
    void (*atomic_print_state)(struct drm_printer *p, const struct drm_crtc_state *state);
    u32 (*get_vblank_counter)(struct drm_crtc *crtc);
    int (*enable_vblank)(struct drm_crtc *crtc);
    void (*disable_vblank)(struct drm_crtc *crtc);
    bool (*get_vblank_timestamp)(struct drm_crtc *crtc, int *max_error, ktime_t *vblank_time, bool in_vblank_irq);
};
```

**Members**

- `reset`: Reset CRTC hardware and software state to off. This function isn't
  called by the core directly, only through [`drm_mode_config_reset()`](#c-drm_mode_config_reset).
  It's not a helper hook only for historical reasons.

  Atomic drivers can use [`drm_atomic_helper_crtc_reset()`](/kernel/hardware/gpu/drm-kms-helpers.md#c-drm_atomic_helper_crtc_reset) to reset
  atomic state using this hook.
- `cursor_set`: Update the cursor image. The cursor position is relative to the CRTC
  and can be partially or fully outside of the visible area.

  Note that contrary to all other KMS functions the legacy cursor entry
  points don't take a framebuffer object, but instead take directly a
  raw buffer object id from the driver's buffer manager (which is
  either GEM or TTM for current drivers).

  This entry point is deprecated, drivers should instead implement
  universal plane support and register a proper cursor plane using
  [`drm_crtc_init_with_planes()`](#c-drm_crtc_init_with_planes).

  This callback is optional

  RETURNS:

  0 on success or a negative error code on failure.
- `cursor_set2`: Update the cursor image, including hotspot information. The hotspot
  must not affect the cursor position in CRTC coordinates, but is only
  meant as a hint for virtualized display hardware to coordinate the
  guests and hosts cursor position. The cursor hotspot is relative to
  the cursor image. Otherwise this works exactly like **cursor_set**.

  This entry point is deprecated, drivers should instead implement
  universal plane support and register a proper cursor plane using
  [`drm_crtc_init_with_planes()`](#c-drm_crtc_init_with_planes).

  This callback is optional.

  RETURNS:

  0 on success or a negative error code on failure.
- `cursor_move`: Update the cursor position. The cursor does not need to be visible
  when this hook is called.

  This entry point is deprecated, drivers should instead implement
  universal plane support and register a proper cursor plane using
  [`drm_crtc_init_with_planes()`](#c-drm_crtc_init_with_planes).

  This callback is optional.

  RETURNS:

  0 on success or a negative error code on failure.
- `gamma_set`: Set gamma on the CRTC.

  This callback is optional.

  Atomic drivers who want to support gamma tables should implement the
  atomic color management support, enabled by calling
  [`drm_crtc_enable_color_mgmt()`](#c-drm_crtc_enable_color_mgmt), which then supports the legacy gamma
  interface through the `drm_atomic_helper_legacy_gamma_set()`
  compatibility implementation.
- `destroy`: Clean up CRTC resources. This is only called at driver unload time
  through [`drm_mode_config_cleanup()`](#c-drm_mode_config_cleanup) since a CRTC cannot be hotplugged
  in DRM.
- `set_config`: This is the main legacy entry point to change the modeset state on a
  CRTC. All the details of the desired configuration are passed in a
  [`struct drm_mode_set`](#c-struct-drm_mode_set) - see there for details.

  Drivers implementing atomic modeset should use
  [`drm_atomic_helper_set_config()`](/kernel/hardware/gpu/drm-kms-helpers.md#c-drm_atomic_helper_set_config) to implement this hook.

  RETURNS:

  0 on success or a negative error code on failure.
- `page_flip`: Legacy entry point to schedule a flip to the given framebuffer.

  Page flipping is a synchronization mechanism that replaces the frame
  buffer being scanned out by the CRTC with a new frame buffer during
  vertical blanking, avoiding tearing (except when requested otherwise
  through the DRM_MODE_PAGE_FLIP_ASYNC flag). When an application
  requests a page flip the DRM core verifies that the new frame buffer
  is large enough to be scanned out by the CRTC in the currently
  configured mode and then calls this hook with a pointer to the new
  frame buffer.

  The driver must wait for any pending rendering to the new framebuffer
  to complete before executing the flip. It should also wait for any
  pending rendering from other drivers if the underlying buffer is a
  shared dma-buf.

  An application can request to be notified when the page flip has
  completed. The drm core will supply a [`struct drm_event`](/kernel/hardware/gpu/drm-uapi.md#c-struct-drm_event) in the event
  parameter in this case. This can be handled by the
  [`drm_crtc_send_vblank_event()`](#c-drm_crtc_send_vblank_event) function, which the driver should call on
  the provided event upon completion of the flip. Note that if
  the driver supports vblank signalling and timestamping the vblank
  counters and timestamps must agree with the ones returned from page
  flip events. With the current vblank helper infrastructure this can
  be achieved by holding a vblank reference while the page flip is
  pending, acquired through [`drm_crtc_vblank_get()`](#c-drm_crtc_vblank_get) and released with
  [`drm_crtc_vblank_put()`](#c-drm_crtc_vblank_put). Drivers are free to implement their own vblank
  counter and timestamp tracking though, e.g. if they have accurate
  timestamp registers in hardware.

  This callback is optional.

  NOTE:

  Very early versions of the KMS ABI mandated that the driver must
  block (but not reject) any rendering to the old framebuffer until the
  flip operation has completed and the old framebuffer is no longer
  visible. This requirement has been lifted, and userspace is instead
  expected to request delivery of an event and wait with recycling old
  buffers until such has been received.

  RETURNS:

  0 on success or a negative error code on failure. Note that if a
  page flip operation is already pending the callback should return
  -EBUSY. Pageflips on a disabled CRTC (either by setting a NULL mode
  or just runtime disabled through DPMS respectively the new atomic
  "ACTIVE" state) should result in an -EINVAL error code. Note that
  [`drm_atomic_helper_page_flip()`](/kernel/hardware/gpu/drm-kms-helpers.md#c-drm_atomic_helper_page_flip) checks this already for atomic drivers.
- `page_flip_target`: Same as **page_flip** but with an additional parameter specifying the
  absolute target vertical blank period (as reported by
  [`drm_crtc_vblank_count()`](#c-drm_crtc_vblank_count)) when the flip should take effect.

  Note that the core code calls drm_crtc_vblank_get before this entry
  point, and will call drm_crtc_vblank_put if this entry point returns
  any non-0 error code. It's the driver's responsibility to call
  drm_crtc_vblank_put after this entry point returns 0, typically when
  the flip completes.
- `set_property`: This is the legacy entry point to update a property attached to the
  CRTC.

  This callback is optional if the driver does not support any legacy
  driver-private properties. For atomic drivers it is not used because
  property handling is done entirely in the DRM core.

  RETURNS:

  0 on success or a negative error code on failure.
- `atomic_duplicate_state`: Duplicate the current atomic state for this CRTC and return it.
  The core and helpers guarantee that any atomic state duplicated with
  this hook and still owned by the caller (i.e. not transferred to the
  driver by calling [`drm_mode_config_funcs.atomic_commit`](#c-struct-drm_mode_config_funcs)) will be
  cleaned up by calling the **atomic_destroy_state** hook in this
  structure.

  This callback is mandatory for atomic drivers.

  Atomic drivers which don't subclass [`struct drm_crtc_state`](#c-struct-drm_crtc_state) should use
  [`drm_atomic_helper_crtc_duplicate_state()`](/kernel/hardware/gpu/drm-kms-helpers.md#c-drm_atomic_helper_crtc_duplicate_state). Drivers that subclass the
  state structure to extend it with driver-private state should use
  [`__drm_atomic_helper_crtc_duplicate_state()`](/kernel/hardware/gpu/drm-kms-helpers.md#c-__drm_atomic_helper_crtc_duplicate_state) to make sure shared state is
  duplicated in a consistent fashion across drivers.

  It is an error to call this hook before [`drm_crtc.state`](#c-struct-drm_crtc) has been
  initialized correctly.

  NOTE:

  If the duplicate state references refcounted resources this hook must
  acquire a reference for each of them. The driver must release these
  references again in **atomic_destroy_state**.

  RETURNS:

  Duplicated atomic state or NULL when the allocation failed.
- `atomic_destroy_state`: Destroy a state duplicated with **atomic_duplicate_state** and release
  or unreference all resources it references

  This callback is mandatory for atomic drivers.
- `atomic_set_property`: Decode a driver-private property value and store the decoded value
  into the passed-in state structure. Since the atomic core decodes all
  standardized properties (even for extensions beyond the core set of
  properties which might not be implemented by all drivers) this
  requires drivers to subclass the state structure.

  Such driver-private properties should really only be implemented for
  truly hardware/vendor specific state. Instead it is preferred to
  standardize atomic extension and decode the properties used to expose
  such an extension in the core.

  Do not call this function directly, use
  `drm_atomic_crtc_set_property()` instead.

  This callback is optional if the driver does not support any
  driver-private atomic properties.

  NOTE:

  This function is called in the state assembly phase of atomic
  modesets, which can be aborted for any reason (including on
  userspace's request to just check whether a configuration would be
  possible). Drivers MUST NOT touch any persistent state (hardware or
  software) or data structures except the passed in **state** parameter.

  Also since userspace controls in which order properties are set this
  function must not do any input validation (since the state update is
  incomplete and hence likely inconsistent). Instead any such input
  validation must be done in the various atomic_check callbacks.

  RETURNS:

  0 if the property has been found, -EINVAL if the property isn't
  implemented by the driver (which should never happen, the core only
  asks for properties attached to this CRTC). No other validation is
  allowed by the driver. The core already checks that the property
  value is within the range (integer, valid enum value, ...) the driver
  set when registering the property.
- `atomic_get_property`: Reads out the decoded driver-private property. This is used to
  implement the GETCRTC IOCTL.

  Do not call this function directly, use
  `drm_atomic_crtc_get_property()` instead.

  This callback is optional if the driver does not support any
  driver-private atomic properties.

  RETURNS:

  0 on success, -EINVAL if the property isn't implemented by the
  driver (which should never happen, the core only asks for
  properties attached to this CRTC).
- `late_register`: This optional hook can be used to register additional userspace
  interfaces attached to the crtc like debugfs interfaces.
  It is called late in the driver load sequence from [`drm_dev_register()`](/kernel/hardware/gpu/drm-internals.md#c-drm_dev_register).
  Everything added from this callback should be unregistered in
  the early_unregister callback.

  Returns:

  0 on success, or a negative error code on failure.
- `early_unregister`: This optional hook should be used to unregister the additional
  userspace interfaces attached to the crtc from
  **late_register**. It is called from [`drm_dev_unregister()`](/kernel/hardware/gpu/drm-internals.md#c-drm_dev_unregister),
  early in the driver unload sequence to disable userspace access
  before data structures are torndown.
- `set_crc_source`: Changes the source of CRC checksums of frames at the request of
  userspace, typically for testing purposes. The sources available are
  specific of each driver and a `NULL` value indicates that CRC
  generation is to be switched off.

  When CRC generation is enabled, the driver should call
  [`drm_crtc_add_crc_entry()`](/kernel/hardware/gpu/drm-uapi.md#c-drm_crtc_add_crc_entry) at each frame, providing any information
  that characterizes the frame contents in the crcN arguments, as
  provided from the configured source. Drivers must accept an "auto"
  source name that will select a default source for this CRTC.

  This may trigger an atomic modeset commit if necessary, to enable CRC
  generation.

  Note that "auto" can depend upon the current modeset configuration,
  e.g. it could pick an encoder or output specific CRC sampling point.

  This callback is optional if the driver does not support any CRC
  generation functionality.

  RETURNS:

  0 on success or a negative error code on failure.
- `verify_crc_source`: verifies the source of CRC checksums of frames before setting the
  source for CRC and during crc open. Source parameter can be NULL
  while disabling crc source.

  This callback is optional if the driver does not support any CRC
  generation functionality.

  RETURNS:

  0 on success or a negative error code on failure.
- `get_crc_sources`: Driver callback for getting a list of all the available sources for
  CRC generation. This callback depends upon verify_crc_source, So
  verify_crc_source callback should be implemented before implementing
  this. Driver can pass full list of available crc sources, this
  callback does the verification on each crc-source before passing it
  to userspace.

  This callback is optional if the driver does not support exporting of
  possible CRC sources list.

  RETURNS:

  a constant character pointer to the list of all the available CRC
  sources. On failure driver should return NULL. count should be
  updated with number of sources in list. if zero we don't process any
  source from the list.
- `atomic_print_state`: If driver subclasses [`struct drm_crtc_state`](#c-struct-drm_crtc_state), it should implement
  this optional hook for printing additional driver specific state.

  Do not call this directly, use `drm_atomic_crtc_print_state()`
  instead.
- `get_vblank_counter`: Driver callback for fetching a raw hardware vblank counter for the
  CRTC. It's meant to be used by new drivers as the replacement of
  [`drm_driver.get_vblank_counter`](/kernel/hardware/gpu/drm-internals.md#c-struct-drm_driver) hook.

  This callback is optional. If a device doesn't have a hardware
  counter, the driver can simply leave the hook as NULL. The DRM core
  will account for missed vblank events while interrupts where disabled
  based on system timestamps.

  Wraparound handling and loss of events due to modesetting is dealt
  with in the DRM core code, as long as drivers call
  [`drm_crtc_vblank_off()`](#c-drm_crtc_vblank_off) and [`drm_crtc_vblank_on()`](#c-drm_crtc_vblank_on) when disabling or
  enabling a CRTC.

  See also [`drm_device.vblank_disable_immediate`](/kernel/hardware/gpu/drm-internals.md#c-struct-drm_device) and
  [`drm_device.max_vblank_count`](/kernel/hardware/gpu/drm-internals.md#c-struct-drm_device).

  Returns:

  Raw vblank counter value.
- `enable_vblank`: Enable vblank interrupts for the CRTC. It's meant to be used by
  new drivers as the replacement of [`drm_driver.enable_vblank`](/kernel/hardware/gpu/drm-internals.md#c-struct-drm_driver) hook.

  Returns:

  Zero on success, appropriate errno if the vblank interrupt cannot
  be enabled.
- `disable_vblank`: Disable vblank interrupts for the CRTC. It's meant to be used by
  new drivers as the replacement of [`drm_driver.disable_vblank`](/kernel/hardware/gpu/drm-internals.md#c-struct-drm_driver) hook.
- `get_vblank_timestamp`: Called by `drm_get_last_vbltimestamp()`. Should return a precise
  timestamp when the most recent vblank interval ended or will end.

  Specifically, the timestamp in **vblank_time** should correspond as
  closely as possible to the time when the first video scanline of
  the video frame after the end of vblank will start scanning out,
  the time immediately after end of the vblank interval. If the
  **crtc** is currently inside vblank, this will be a time in the future.
  If the **crtc** is currently scanning out a frame, this will be the
  past start time of the current scanout. This is meant to adhere
  to the OpenML OML_sync_control extension specification.

  Parameters:

  - crtc:
    CRTC for which timestamp should be returned.
  - max_error:
    Maximum allowable timestamp error in nanoseconds.
    Implementation should strive to provide timestamp
    with an error of at most max_error nanoseconds.
    Returns true upper bound on error for timestamp.
  - vblank_time:
    Target location for returned vblank timestamp.
  - in_vblank_irq:
    True when called from [`drm_crtc_handle_vblank()`](#c-drm_crtc_handle_vblank).  Some drivers
    need to apply some workarounds for gpu-specific vblank irq quirks
    if flag is set.

  Returns:

  True on success, false on failure, which means the core should
  fallback to a simple timestamp taken in [`drm_crtc_handle_vblank()`](#c-drm_crtc_handle_vblank).

**Description**

The drm_crtc_funcs structure is the central CRTC management structure
in the DRM.  Each CRTC controls one or more connectors (note that the name
CRTC is simply historical, a CRTC may control LVDS, VGA, DVI, TV out, etc.
connectors, not just CRTs).

Each driver is responsible for filling out this structure at startup time,
in addition to providing other modesetting features, like i2c and DDC
bus accessors.

#### <a id="c-struct-drm_crtc"></a>`struct drm_crtc`

central CRTC control structure

**Definition**

```c
struct drm_crtc {
    struct drm_device *dev;
    struct device_node *port;
    struct list_head head;
    char *name;
    struct drm_modeset_lock mutex;
    struct drm_mode_object base;
    struct drm_plane *primary;
    struct drm_plane *cursor;
    unsigned index;
    int cursor_x;
    int cursor_y;
    bool enabled;
    struct drm_display_mode mode;
    struct drm_display_mode hwmode;
    int x;
    int y;
    const struct drm_crtc_funcs *funcs;
    uint32_t gamma_size;
    uint16_t *gamma_store;
    const struct drm_crtc_helper_funcs *helper_private;
    struct drm_object_properties properties;
    struct drm_property *scaling_filter_property;
    struct drm_property *sharpness_strength_property;
    struct drm_crtc_state *state;
    struct list_head commit_list;
    spinlock_t commit_lock;
    struct dentry *debugfs_entry;
    struct drm_crtc_crc crc;
    unsigned int fence_context;
    spinlock_t fence_lock;
    unsigned long fence_seqno;
    char timeline_name[32];
    struct drm_self_refresh_data *self_refresh_data;
};
```

**Members**

- `dev`: parent DRM device
- `port`: OF node used by [`drm_of_find_possible_crtcs()`](/kernel/hardware/gpu/drm-kms-helpers.md#c-drm_of_find_possible_crtcs).
- `head`: List of all CRTCs on **dev**, linked from [`drm_mode_config.crtc_list`](#c-struct-drm_mode_config).
  Invariant over the lifetime of **dev** and therefore does not need
  locking.
- `name`: human readable name, can be overwritten by the driver
- `mutex`: This provides a read lock for the overall CRTC state (mode, dpms
  state, ...) and a write lock for everything which can be update
  without a full modeset (fb, cursor data, CRTC properties ...). A full
  modeset also need to grab [`drm_mode_config.connection_mutex`](#c-struct-drm_mode_config).

  For atomic drivers specifically this protects **state**.
- `base`: base KMS object for ID tracking etc.
- `primary`: Primary plane for this CRTC. Note that this is only
  relevant for legacy IOCTL, it specifies the plane implicitly used by
  the SETCRTC and PAGE_FLIP IOCTLs. It does not have any significance
  beyond that.
- `cursor`: Cursor plane for this CRTC. Note that this is only relevant for
  legacy IOCTL, it specifies the plane implicitly used by the SETCURSOR
  and SETCURSOR2 IOCTLs. It does not have any significance
  beyond that.
- `index`: Position inside the mode_config.list, can be used as an array
  index. It is invariant over the lifetime of the CRTC.
- `cursor_x`: Current x position of the cursor, used for universal
  cursor planes because the SETCURSOR IOCTL only can update the
  framebuffer without supplying the coordinates. Drivers should not use
  this directly, atomic drivers should look at [`drm_plane_state.crtc_x`](#c-struct-drm_plane_state)
  of the cursor plane instead.
- `cursor_y`: Current y position of the cursor, used for universal
  cursor planes because the SETCURSOR IOCTL only can update the
  framebuffer without supplying the coordinates. Drivers should not use
  this directly, atomic drivers should look at [`drm_plane_state.crtc_y`](#c-struct-drm_plane_state)
  of the cursor plane instead.
- `enabled`: Is this CRTC enabled? Should only be used by legacy drivers, atomic
  drivers should instead consult [`drm_crtc_state.enable`](#c-struct-drm_crtc_state) and
  [`drm_crtc_state.active`](#c-struct-drm_crtc_state). Atomic drivers can update this by calling
  [`drm_atomic_helper_update_legacy_modeset_state()`](/kernel/hardware/gpu/drm-kms-helpers.md#c-drm_atomic_helper_update_legacy_modeset_state).
- `mode`: Current mode timings. Should only be used by legacy drivers, atomic
  drivers should instead consult [`drm_crtc_state.mode`](#c-struct-drm_crtc_state). Atomic drivers
  can update this by calling
  [`drm_atomic_helper_update_legacy_modeset_state()`](/kernel/hardware/gpu/drm-kms-helpers.md#c-drm_atomic_helper_update_legacy_modeset_state).
- `hwmode`: Programmed mode in hw, after adjustments for encoders, crtc, panel
  scaling etc. Should only be used by legacy drivers, for high
  precision vblank timestamps in
  [`drm_crtc_vblank_helper_get_vblank_timestamp()`](#c-drm_crtc_vblank_helper_get_vblank_timestamp).

  Note that atomic drivers should not use this, but instead use
  [`drm_crtc_state.adjusted_mode`](#c-struct-drm_crtc_state). And for high-precision timestamps
  [`drm_crtc_vblank_helper_get_vblank_timestamp()`](#c-drm_crtc_vblank_helper_get_vblank_timestamp) used
  [`drm_vblank_crtc.hwmode`](#c-struct-drm_vblank_crtc),
  which is filled out by calling [`drm_calc_timestamping_constants()`](#c-drm_calc_timestamping_constants).
- `x`: x position on screen. Should only be used by legacy drivers, atomic
  drivers should look at [`drm_plane_state.crtc_x`](#c-struct-drm_plane_state) of the primary plane
  instead. Updated by calling
  [`drm_atomic_helper_update_legacy_modeset_state()`](/kernel/hardware/gpu/drm-kms-helpers.md#c-drm_atomic_helper_update_legacy_modeset_state).
- `y`: y position on screen. Should only be used by legacy drivers, atomic
  drivers should look at [`drm_plane_state.crtc_y`](#c-struct-drm_plane_state) of the primary plane
  instead. Updated by calling
  [`drm_atomic_helper_update_legacy_modeset_state()`](/kernel/hardware/gpu/drm-kms-helpers.md#c-drm_atomic_helper_update_legacy_modeset_state).
- `funcs`: CRTC control functions
- `gamma_size`: Size of legacy gamma ramp reported to userspace. Set up
  by calling [`drm_mode_crtc_set_gamma_size()`](#c-drm_mode_crtc_set_gamma_size).

  Note that atomic drivers need to instead use
  [`drm_crtc_state.gamma_lut`](#c-struct-drm_crtc_state). See [`drm_crtc_enable_color_mgmt()`](#c-drm_crtc_enable_color_mgmt).
- `gamma_store`: Gamma ramp values used by the legacy SETGAMMA and
  GETGAMMA IOCTls. Set up by calling [`drm_mode_crtc_set_gamma_size()`](#c-drm_mode_crtc_set_gamma_size).

  Note that atomic drivers need to instead use
  [`drm_crtc_state.gamma_lut`](#c-struct-drm_crtc_state). See [`drm_crtc_enable_color_mgmt()`](#c-drm_crtc_enable_color_mgmt).
- `helper_private`: mid-layer private data
- `properties`: property tracking for this CRTC
- `scaling_filter_property`: property to apply a particular filter while
  scaling.
- `sharpness_strength_property`: property to apply
  the intensity of the sharpness requested.
- `state`: Current atomic state for this CRTC.

  This is protected by **mutex**. Note that nonblocking atomic commits
  access the current CRTC state without taking locks. Either by going
  through the [`struct drm_atomic_state`](#c-struct-drm_atomic_state) pointers, see
  [`for_each_oldnew_crtc_in_state()`](#c-for_each_oldnew_crtc_in_state), [`for_each_old_crtc_in_state()`](#c-for_each_old_crtc_in_state) and
  [`for_each_new_crtc_in_state()`](#c-for_each_new_crtc_in_state). Or through careful ordering of atomic
  commit operations as implemented in the atomic helpers, see
  [`struct drm_crtc_commit`](#c-struct-drm_crtc_commit).
- `commit_list`: List of [`drm_crtc_commit`](#c-struct-drm_crtc_commit) structures tracking pending commits.
  Protected by **commit_lock**. This list holds its own full reference,
  as does the ongoing commit.

  "Note that the commit for a state change is also tracked in
  [`drm_crtc_state.commit`](#c-struct-drm_crtc_state). For accessing the immediately preceding
  commit in an atomic update it is recommended to just use that
  pointer in the old CRTC state, since accessing that doesn't need
  any locking or list-walking. **commit_list** should only be used to
  stall for framebuffer cleanup that's signalled through
  [`drm_crtc_commit.cleanup_done`](#c-struct-drm_crtc_commit)."
- `commit_lock`: Spinlock to protect **commit_list**.
- `debugfs_entry`: Debugfs directory for this CRTC.
- `crc`: Configuration settings of CRC capture.
- `fence_context`: timeline context used for fence operations.
- `fence_lock`: spinlock to protect the fences in the fence_context.
- `fence_seqno`: Seqno variable used as monotonic counter for the fences
  created on the CRTC's timeline.
- `timeline_name`: The name of the CRTC's fence timeline.
- `self_refresh_data`: Holds the state for the self refresh helpers

  Initialized via [`drm_self_refresh_helper_init()`](/kernel/hardware/gpu/drm-kms-helpers.md#c-drm_self_refresh_helper_init).

**Description**

Each CRTC may have one or more connectors associated with it.  This structure
allows the CRTC to be controlled.

#### <a id="c-struct-drm_mode_set"></a>`struct drm_mode_set`

new values for a CRTC config change

**Definition**

```c
struct drm_mode_set {
    struct drm_framebuffer *fb;
    struct drm_crtc *crtc;
    struct drm_display_mode *mode;
    uint32_t x;
    uint32_t y;
    struct drm_connector **connectors;
    size_t num_connectors;
};
```

**Members**

- `fb`: framebuffer to use for new config
- `crtc`: CRTC whose configuration we're about to change
- `mode`: mode timings to use
- `x`: position of this CRTC relative to **fb**
- `y`: position of this CRTC relative to **fb**
- `connectors`: array of connectors to drive with this CRTC if possible
- `num_connectors`: size of **connectors** array

**Description**

This represents a modeset configuration for the legacy SETCRTC ioctl and is
also used internally. Atomic drivers instead use [`drm_atomic_state`](#c-struct-drm_atomic_state).

#### <a id="c-drmm_crtc_alloc_with_planes"></a>`drmm_crtc_alloc_with_planes()`

```c
drmm_crtc_alloc_with_planes(dev, type, member, primary, cursor, funcs, name, ...)
```

Allocate and initialize a new CRTC object with specified primary and cursor planes.

**Parameters**

- `dev`: DRM device
- `type`: the type of the struct which contains struct [`drm_crtc`](#c-struct-drm_crtc)
- `member`: the name of the [`drm_crtc`](#c-struct-drm_crtc) within **type**.
- `primary`: Primary plane for CRTC
- `cursor`: Cursor plane for CRTC
- `funcs`: callbacks for the new CRTC
- `name`: printf style format string for the CRTC name, or NULL for default name
- `...`: variable arguments

**Description**

Allocates and initializes a new crtc object. Cleanup is automatically
handled through registering `drmm_crtc_cleanup()` with [`drmm_add_action()`](/kernel/hardware/gpu/drm-internals.md#c-drmm_add_action).

The **drm_crtc_funcs.destroy** hook must be NULL.

**Return**

Pointer to new crtc, or ERR_PTR on failure.

#### <a id="c-drm_crtc_index"></a>`drm_crtc_index()`

```c
unsigned int drm_crtc_index(const struct drm_crtc *crtc)
```

find the index of a registered CRTC

**Parameters**

- `const struct drm_crtc *crtc`: CRTC to find index for

**Description**

Given a registered CRTC, return the index of that CRTC within a DRM
device's list of CRTCs.

#### <a id="c-drm_crtc_mask"></a>`drm_crtc_mask()`

```c
uint32_t drm_crtc_mask(const struct drm_crtc *crtc)
```

find the mask of a registered CRTC

**Parameters**

- `const struct drm_crtc *crtc`: CRTC to find mask for

**Description**

Given a registered CRTC, return the mask bit of that CRTC for the
[`drm_encoder.possible_crtcs`](#c-struct-drm_encoder) and [`drm_plane.possible_crtcs`](#c-struct-drm_plane) fields.

#### <a id="c-drm_crtc_find"></a>`drm_crtc_find()`

```c
struct drm_crtc * drm_crtc_find(struct drm_device *dev, struct drm_file *file_priv, uint32_t id)
```

look up a CRTC object from its ID

**Parameters**

- `struct drm_device *dev`: DRM device
- `struct drm_file *file_priv`: drm file to check for lease against.
- `uint32_t id`: [`drm_mode_object`](#c-struct-drm_mode_object) ID

**Description**

This can be used to look up a CRTC from its userspace ID. Only used by
drivers for legacy IOCTLs and interface, nowadays extensions to the KMS
userspace interface should be done using [`drm_property`](#c-struct-drm_property).

#### <a id="c-drm_for_each_crtc"></a>`drm_for_each_crtc()`

```c
drm_for_each_crtc(crtc, dev)
```

iterate over all CRTCs

**Parameters**

- `crtc`: a [`struct drm_crtc`](#c-struct-drm_crtc) as the loop cursor
- `dev`: the [`struct drm_device`](/kernel/hardware/gpu/drm-internals.md#c-struct-drm_device)

**Description**

Iterate over all CRTCs of **dev**.

#### <a id="c-drm_for_each_crtc_reverse"></a>`drm_for_each_crtc_reverse()`

```c
drm_for_each_crtc_reverse(crtc, dev)
```

iterate over all CRTCs in reverse order

**Parameters**

- `crtc`: a [`struct drm_crtc`](#c-struct-drm_crtc) as the loop cursor
- `dev`: the [`struct drm_device`](/kernel/hardware/gpu/drm-internals.md#c-struct-drm_device)

**Description**

Iterate over all CRTCs of **dev**.



#### <a id="c-drm_crtc_from_index"></a>`drm_crtc_from_index()`

```c
struct drm_crtc * drm_crtc_from_index(struct drm_device *dev, int idx)
```

find the registered CRTC at an index

**Parameters**

- `struct drm_device *dev`: DRM device
- `int idx`: index of registered CRTC to find for

**Description**

Given a CRTC index, return the registered CRTC from DRM device's
list of CRTCs with matching index. This is the inverse of [`drm_crtc_index()`](#c-drm_crtc_index).
It's useful in the vblank callbacks (like [`drm_driver.enable_vblank`](/kernel/hardware/gpu/drm-internals.md#c-struct-drm_driver) or
[`drm_driver.disable_vblank`](/kernel/hardware/gpu/drm-internals.md#c-struct-drm_driver)), since that still deals with indices instead
of pointers to [`struct drm_crtc`](#c-struct-drm_crtc)."

#### <a id="c-drm_crtc_init_with_planes"></a>`drm_crtc_init_with_planes()`

```c
int drm_crtc_init_with_planes(struct drm_device *dev, struct drm_crtc *crtc, struct drm_plane *primary, struct drm_plane *cursor, const struct drm_crtc_funcs *funcs, const char *name, ...)
```

Initialise a new CRTC object with specified primary and cursor planes.

**Parameters**

- `struct drm_device *dev`: DRM device
- `struct drm_crtc *crtc`: CRTC object to init
- `struct drm_plane *primary`: Primary plane for CRTC
- `struct drm_plane *cursor`: Cursor plane for CRTC
- `const struct drm_crtc_funcs *funcs`: callbacks for the new CRTC
- `const char *name`: printf style format string for the CRTC name, or NULL for default name
- `...`: variable arguments

**Description**

Inits a new object created as base part of a driver crtc object. Drivers
should use this function instead of [`drm_crtc_init()`](/kernel/hardware/gpu/drm-kms-helpers.md#c-drm_crtc_init), which is only provided
for backwards compatibility with drivers which do not yet support universal
planes). For really simple hardware which has only 1 plane look at
[`drm_simple_display_pipe_init()`](/kernel/hardware/gpu/drm-kms-helpers.md#c-drm_simple_display_pipe_init) instead.
The [`drm_crtc_funcs.destroy`](#c-struct-drm_crtc_funcs) hook should call [`drm_crtc_cleanup()`](#c-drm_crtc_cleanup) and [`kfree()`](/kernel/internals/core-api/mm-api.md#c-kfree)
the crtc structure. The crtc structure should not be allocated with
`devm_kzalloc()`.

The **primary** and **cursor** planes are only relevant for legacy uAPI, see
[`drm_crtc.primary`](#c-struct-drm_crtc) and [`drm_crtc.cursor`](#c-struct-drm_crtc).

**Note**

consider using [`drmm_crtc_alloc_with_planes()`](#c-drmm_crtc_alloc_with_planes) or
[`drmm_crtc_init_with_planes()`](#c-drmm_crtc_init_with_planes) instead of [`drm_crtc_init_with_planes()`](#c-drm_crtc_init_with_planes)
to let the DRM managed resource infrastructure take care of cleanup
and deallocation.

**Return**

Zero on success, error code on failure.

#### <a id="c-drmm_crtc_init_with_planes"></a>`drmm_crtc_init_with_planes()`

```c
int drmm_crtc_init_with_planes(struct drm_device *dev, struct drm_crtc *crtc, struct drm_plane *primary, struct drm_plane *cursor, const struct drm_crtc_funcs *funcs, const char *name, ...)
```

Initialise a new CRTC object with specified primary and cursor planes.

**Parameters**

- `struct drm_device *dev`: DRM device
- `struct drm_crtc *crtc`: CRTC object to init
- `struct drm_plane *primary`: Primary plane for CRTC
- `struct drm_plane *cursor`: Cursor plane for CRTC
- `const struct drm_crtc_funcs *funcs`: callbacks for the new CRTC
- `const char *name`: printf style format string for the CRTC name, or NULL for default name
- `...`: variable arguments

**Description**

Inits a new object created as base part of a driver crtc object. Drivers
should use this function instead of [`drm_crtc_init()`](/kernel/hardware/gpu/drm-kms-helpers.md#c-drm_crtc_init), which is only provided
for backwards compatibility with drivers which do not yet support universal
planes). For really simple hardware which has only 1 plane look at
[`drm_simple_display_pipe_init()`](/kernel/hardware/gpu/drm-kms-helpers.md#c-drm_simple_display_pipe_init) instead.

Cleanup is automatically handled through registering
`drmm_crtc_cleanup()` with [`drmm_add_action()`](/kernel/hardware/gpu/drm-internals.md#c-drmm_add_action). The crtc structure should
be allocated with [`drmm_kzalloc()`](/kernel/hardware/gpu/drm-internals.md#c-drmm_kzalloc).

The **drm_crtc_funcs.destroy** hook must be NULL.

The **primary** and **cursor** planes are only relevant for legacy uAPI, see
[`drm_crtc.primary`](#c-struct-drm_crtc) and [`drm_crtc.cursor`](#c-struct-drm_crtc).

**Return**

Zero on success, error code on failure.

#### <a id="c-drm_crtc_cleanup"></a>`drm_crtc_cleanup()`

```c
void drm_crtc_cleanup(struct drm_crtc *crtc)
```

Clean up the core crtc usage

**Parameters**

- `struct drm_crtc *crtc`: CRTC to cleanup

**Description**

This function cleans up **crtc** and removes it from the DRM mode setting
core. Note that the function does *not* free the crtc structure itself,
this is the responsibility of the caller.

#### <a id="c-drm_mode_set_config_internal"></a>`drm_mode_set_config_internal()`

```c
int drm_mode_set_config_internal(struct drm_mode_set *set)
```

helper to call [`drm_mode_config_funcs.set_config`](#c-struct-drm_mode_config_funcs)

**Parameters**

- `struct drm_mode_set *set`: modeset config to set

**Description**

This is a little helper to wrap internal calls to the
[`drm_mode_config_funcs.set_config`](#c-struct-drm_mode_config_funcs) driver interface. The only thing it adds is
correct refcounting dance.

This should only be used by non-atomic legacy drivers.

**Return**

Zero on success, negative errno on failure.

#### <a id="c-drm_crtc_check_viewport"></a>`drm_crtc_check_viewport()`

```c
int drm_crtc_check_viewport(const struct drm_crtc *crtc, int x, int y, const struct drm_display_mode *mode, const struct drm_framebuffer *fb)
```

Checks that a framebuffer is big enough for the CRTC viewport

**Parameters**

- `const struct drm_crtc *crtc`: CRTC that framebuffer will be displayed on
- `int x`: x panning
- `int y`: y panning
- `const struct drm_display_mode *mode`: mode that framebuffer will be displayed under
- `const struct drm_framebuffer *fb`: framebuffer to check size of

#### <a id="c-drm_crtc_create_scaling_filter_property"></a>`drm_crtc_create_scaling_filter_property()`

```c
int drm_crtc_create_scaling_filter_property(struct drm_crtc *crtc, unsigned int supported_filters)
```

create a new scaling filter property

**Parameters**

- `struct drm_crtc *crtc`: drm CRTC
- `unsigned int supported_filters`: bitmask of supported scaling filters, must include
  BIT(DRM_SCALING_FILTER_DEFAULT).

**Description**

This function lets driver to enable the scaling filter property on a given
CRTC.

**Return**

Zero for success or -errno

#### <a id="c-drm_crtc_in_clone_mode"></a>`drm_crtc_in_clone_mode()`

```c
bool drm_crtc_in_clone_mode(struct drm_crtc_state *crtc_state)
```

check if the given CRTC state is in clone mode

**Parameters**

- `struct drm_crtc_state *crtc_state`: CRTC state to check

**Description**

This function determines if the given CRTC state is being cloned by multiple
encoders.

**Return**

True if the CRTC state is in clone mode. False otherwise


<a id="rst-color-management-functions-reference"></a>

### Color Management Functions Reference


#### <a id="c-drm_color_ctm_s31_32_to_qm_n"></a>`drm_color_ctm_s31_32_to_qm_n()`

```c
u64 drm_color_ctm_s31_32_to_qm_n(u64 user_input, u32 m, u32 n)
```

**Parameters**

- `u64 user_input`: input value
- `u32 m`: number of integer bits, only support m \<= 32, include the sign-bit
- `u32 n`: number of fractional bits, only support n \<= 32

**Description**

Convert and clamp S31.32 sign-magnitude to Qm.n (signed 2's complement).
The sign-bit BIT(m+n-1) and above are 0 for positive value and 1 for negative
the range of value is \[-2^(m-1), 2^(m-1) - 2^-n\]

For example
A Q3.12 format number:
- required bit: 3 + 12 = 15bits
- range: \[-2^2, 2^2 - 2^−15\]

**NOTE**

- the m can be zero if all bit_precision are used to present fractional

  bits like Q0.32

#### <a id="c-drm_crtc_enable_color_mgmt"></a>`drm_crtc_enable_color_mgmt()`

```c
void drm_crtc_enable_color_mgmt(struct drm_crtc *crtc, uint degamma_lut_size, bool has_ctm, uint gamma_lut_size)
```

enable color management properties

**Parameters**

- `struct drm_crtc *crtc`: DRM CRTC
- `uint degamma_lut_size`: the size of the degamma lut (before CSC)
- `bool has_ctm`: whether to attach ctm_property for CSC matrix
- `uint gamma_lut_size`: the size of the gamma lut (after CSC)

**Description**

This function lets the driver enable the color correction
properties on a CRTC. This includes 3 degamma, csc and gamma
properties that userspace can set and 2 size properties to inform
the userspace of the lut sizes. Each of the properties are
optional. The gamma and degamma properties are only attached if
their size is not 0 and ctm_property is only attached if has_ctm is
true.

#### <a id="c-drm_mode_crtc_set_gamma_size"></a>`drm_mode_crtc_set_gamma_size()`

```c
int drm_mode_crtc_set_gamma_size(struct drm_crtc *crtc, int gamma_size)
```

set the gamma table size

**Parameters**

- `struct drm_crtc *crtc`: CRTC to set the gamma table size for
- `int gamma_size`: size of the gamma table

**Description**

Drivers which support gamma tables should set this to the supported gamma
table size when initializing the CRTC. Currently the drm core only supports a
fixed gamma table size.

**Return**

Zero on success, negative errno on failure.

#### <a id="c-drm_plane_create_color_properties"></a>`drm_plane_create_color_properties()`

```c
int drm_plane_create_color_properties(struct drm_plane *plane, u32 supported_encodings, u32 supported_ranges, enum drm_color_encoding default_encoding, enum drm_color_range default_range)
```

color encoding related plane properties

**Parameters**

- `struct drm_plane *plane`: plane object
- `u32 supported_encodings`: bitfield indicating supported color encodings
- `u32 supported_ranges`: bitfileld indicating supported color ranges
- `enum drm_color_encoding default_encoding`: default color encoding
- `enum drm_color_range default_range`: default color range

**Description**

Create and attach plane specific COLOR_ENCODING and COLOR_RANGE
properties to **plane**. The supported encodings and ranges should
be provided in supported_encodings and supported_ranges bitmasks.
Each bit set in the bitmask indicates that its number as enum
value is supported.

#### <a id="c-drm_color_lut_check"></a>`drm_color_lut_check()`

```c
int drm_color_lut_check(const struct drm_property_blob *lut, u32 tests)
```

check validity of lookup table

**Parameters**

- `const struct drm_property_blob *lut`: property blob containing LUT to check
- `u32 tests`: bitmask of tests to run

**Description**

Helper to check whether a userspace-provided lookup table is valid and
satisfies hardware requirements.  Drivers pass a bitmask indicating which of
the tests in [`drm_color_lut_tests`](#c-enum-drm_color_lut_tests) should be performed.

Returns 0 on success, -EINVAL on failure.

#### <a id="c-drm_crtc_load_gamma_888"></a>`drm_crtc_load_gamma_888()`

```c
void drm_crtc_load_gamma_888(struct drm_crtc *crtc, const struct drm_color_lut *lut, drm_crtc_set_lut_func set_gamma)
```

Programs gamma ramp for RGB888-like formats

**Parameters**

- `struct drm_crtc *crtc`: The displaying CRTC
- `const struct drm_color_lut *lut`: The gamma ramp to program
- `drm_crtc_set_lut_func set_gamma`: Callback for programming the hardware gamma LUT

**Description**

Programs the gamma ramp specified in **lut** to hardware. The input gamma
ramp must have 256 entries per color component.

#### <a id="c-drm_crtc_load_gamma_565_from_888"></a>`drm_crtc_load_gamma_565_from_888()`

```c
void drm_crtc_load_gamma_565_from_888(struct drm_crtc *crtc, const struct drm_color_lut *lut, drm_crtc_set_lut_func set_gamma)
```

Programs gamma ramp for RGB565-like formats

**Parameters**

- `struct drm_crtc *crtc`: The displaying CRTC
- `const struct drm_color_lut *lut`: The gamma ramp to program
- `drm_crtc_set_lut_func set_gamma`: Callback for programming the hardware gamma LUT

**Description**

Programs the gamma ramp specified in **lut** to hardware. The input gamma
ramp must have 256 entries per color component. The helper interpolates
the individual color components to reduce the number of entries to 5/6/5.

#### <a id="c-drm_crtc_load_gamma_555_from_888"></a>`drm_crtc_load_gamma_555_from_888()`

```c
void drm_crtc_load_gamma_555_from_888(struct drm_crtc *crtc, const struct drm_color_lut *lut, drm_crtc_set_lut_func set_gamma)
```

Programs gamma ramp for RGB555-like formats

**Parameters**

- `struct drm_crtc *crtc`: The displaying CRTC
- `const struct drm_color_lut *lut`: The gamma ramp to program
- `drm_crtc_set_lut_func set_gamma`: Callback for programming the hardware gamma LUT

**Description**

Programs the gamma ramp specified in **lut** to hardware. The input gamma
ramp must have 256 entries per color component. The helper interpolates
the individual color components to reduce the number of entries to 5/5/5.

#### <a id="c-drm_crtc_fill_gamma_888"></a>`drm_crtc_fill_gamma_888()`

```c
void drm_crtc_fill_gamma_888(struct drm_crtc *crtc, drm_crtc_set_lut_func set_gamma)
```

Programs a default gamma ramp for RGB888-like formats

**Parameters**

- `struct drm_crtc *crtc`: The displaying CRTC
- `drm_crtc_set_lut_func set_gamma`: Callback for programming the hardware gamma LUT

**Description**

Programs a default gamma ramp to hardware.

#### <a id="c-drm_crtc_fill_gamma_565"></a>`drm_crtc_fill_gamma_565()`

```c
void drm_crtc_fill_gamma_565(struct drm_crtc *crtc, drm_crtc_set_lut_func set_gamma)
```

Programs a default gamma ramp for RGB565-like formats

**Parameters**

- `struct drm_crtc *crtc`: The displaying CRTC
- `drm_crtc_set_lut_func set_gamma`: Callback for programming the hardware gamma LUT

**Description**

Programs a default gamma ramp to hardware.

#### <a id="c-drm_crtc_fill_gamma_555"></a>`drm_crtc_fill_gamma_555()`

```c
void drm_crtc_fill_gamma_555(struct drm_crtc *crtc, drm_crtc_set_lut_func set_gamma)
```

Programs a default gamma ramp for RGB555-like formats

**Parameters**

- `struct drm_crtc *crtc`: The displaying CRTC
- `drm_crtc_set_lut_func set_gamma`: Callback for programming the hardware gamma LUT

**Description**

Programs a default gamma ramp to hardware.

#### <a id="c-drm_crtc_load_palette_8"></a>`drm_crtc_load_palette_8()`

```c
void drm_crtc_load_palette_8(struct drm_crtc *crtc, const struct drm_color_lut *lut, drm_crtc_set_lut_func set_palette)
```

Programs palette for C8-like formats

**Parameters**

- `struct drm_crtc *crtc`: The displaying CRTC
- `const struct drm_color_lut *lut`: The palette to program
- `drm_crtc_set_lut_func set_palette`: Callback for programming the hardware palette

**Description**

Programs the palette specified in **lut** to hardware. The input palette
must have 256 entries per color component.

#### <a id="c-drm_crtc_fill_palette_332"></a>`drm_crtc_fill_palette_332()`

```c
void drm_crtc_fill_palette_332(struct drm_crtc *crtc, drm_crtc_set_lut_func set_palette)
```

Programs a default palette for R332-like formats

**Parameters**

- `struct drm_crtc *crtc`: The displaying CRTC
- `drm_crtc_set_lut_func set_palette`: Callback for programming the hardware gamma LUT

**Description**

Programs an RGB332 palette to hardware.

#### <a id="c-drm_crtc_fill_palette_8"></a>`drm_crtc_fill_palette_8()`

```c
void drm_crtc_fill_palette_8(struct drm_crtc *crtc, drm_crtc_set_lut_func set_palette)
```

Programs a default palette for C8-like formats

**Parameters**

- `struct drm_crtc *crtc`: The displaying CRTC
- `drm_crtc_set_lut_func set_palette`: Callback for programming the hardware gamma LUT

**Description**

Programs a default palette to hardware.

#### <a id="c-drm_color_lut32_check"></a>`drm_color_lut32_check()`

```c
int drm_color_lut32_check(const struct drm_property_blob *lut, u32 tests)
```

check validity of extended lookup table

**Parameters**

- `const struct drm_property_blob *lut`: property blob containing extended LUT to check
- `u32 tests`: bitmask of tests to run

**Description**

Helper to check whether a userspace-provided extended lookup table is valid and
satisfies hardware requirements.  Drivers pass a bitmask indicating which of
the tests in [`drm_color_lut_tests`](#c-enum-drm_color_lut_tests) should be performed.

Returns 0 on success, -EINVAL on failure.



#### <a id="c-drm_color_lut_extract"></a>`drm_color_lut_extract()`

```c
u32 drm_color_lut_extract(u32 user_input, int bit_precision)
```

clamp and round LUT entries

**Parameters**

- `u32 user_input`: input value
- `int bit_precision`: number of bits the hw LUT supports

**Description**

Extract a degamma/gamma LUT value provided by user (in the form of
`drm_color_lut` entries) and round it to the precision supported by the
hardware, following OpenGL int\<->float conversion rules
(see eg. OpenGL 4.6 specification - 2.3.5 Fixed-Point Data Conversions).

#### <a id="c-drm_color_lut32_extract"></a>`drm_color_lut32_extract()`

```c
u32 drm_color_lut32_extract(u32 user_input, int bit_precision)
```

clamp and round LUT entries

**Parameters**

- `u32 user_input`: input value
- `int bit_precision`: number of bits the hw LUT supports

**Description**

Extract U0.bit_precision from a U0.32 LUT value.

#### <a id="c-drm_color_lut_size"></a>`drm_color_lut_size()`

```c
int drm_color_lut_size(const struct drm_property_blob *blob)
```

calculate the number of entries in the LUT

**Parameters**

- `const struct drm_property_blob *blob`: blob containing the LUT

**Return**

The number of entries in the color LUT stored in **blob**.

#### <a id="c-drm_color_lut32_size"></a>`drm_color_lut32_size()`

```c
int drm_color_lut32_size(const struct drm_property_blob *blob)
```

calculate the number of entries in the extended LUT

**Parameters**

- `const struct drm_property_blob *blob`: blob containing the LUT

**Return**

The number of entries in the color LUT stored in **blob**.

#### <a id="c-enum-drm_color_lut_tests"></a>`enum drm_color_lut_tests`

hw-specific LUT tests to perform

**Constants**

- `DRM_COLOR_LUT_EQUAL_CHANNELS`: Checks whether the entries of a LUT all have equal values for the
  red, green, and blue channels.  Intended for hardware that only
  accepts a single value per LUT entry and assumes that value applies
  to all three color components.
- `DRM_COLOR_LUT_NON_DECREASING`: Checks whether the entries of a LUT are always flat or increasing
  (never decreasing).

**Description**

The [`drm_color_lut_check()`](#c-drm_color_lut_check) function takes a bitmask of the values here to
determine which tests to apply to a userspace-provided LUT.


<a id="rst-frame-buffer-abstraction"></a>

## Frame Buffer Abstraction


Frame buffers are abstract memory objects that provide a source of pixels to
scanout to a CRTC. Applications explicitly request the creation of frame
buffers through the DRM_IOCTL_MODE_ADDFB(2) ioctls and receive an opaque
handle that can be passed to the KMS CRTC control, plane configuration and
page flip functions.

Frame buffers rely on the underlying memory manager for allocating backing
storage. When creating a frame buffer applications pass a memory handle
(or a list of memory handles for multi-planar formats) through the
[`struct drm_mode_fb_cmd2`](/kernel/hardware/gpu/drm-uapi.md#c-struct-drm_mode_fb_cmd2) argument. For drivers using GEM as their userspace
buffer management interface this would be a GEM handle.  Drivers are however
free to use their own backing storage object handles, e.g. vmwgfx directly
exposes special TTM handles to userspace and so expects TTM handles in the
create ioctl and not GEM handles.

Framebuffers are tracked with [`struct drm_framebuffer`](#c-struct-drm_framebuffer). They are published
using [`drm_framebuffer_init()`](#c-drm_framebuffer_init) - after calling that function userspace can use
and access the framebuffer object. The helper function
[`drm_helper_mode_fill_fb_struct()`](/kernel/hardware/gpu/drm-kms-helpers.md#c-drm_helper_mode_fill_fb_struct) can be used to pre-fill the required
metadata fields.

The lifetime of a drm framebuffer is controlled with a reference count,
drivers can grab additional references with [`drm_framebuffer_get()`](#c-drm_framebuffer_get) and drop
them again with [`drm_framebuffer_put()`](#c-drm_framebuffer_put). For driver-private framebuffers for
which the last reference is never dropped (e.g. for the fbdev framebuffer
when the struct [`struct drm_framebuffer`](#c-struct-drm_framebuffer) is embedded into the fbdev helper
struct) drivers can manually clean up a framebuffer at module unload time
with [`drm_framebuffer_unregister_private()`](#c-drm_framebuffer_unregister_private). But doing this is not
recommended, and it's better to have a normal free-standing [`struct drm_framebuffer`](#c-struct-drm_framebuffer).


<a id="rst-frame-buffer-functions-reference"></a>

### Frame Buffer Functions Reference


#### <a id="c-struct-drm_framebuffer_funcs"></a>`struct drm_framebuffer_funcs`

framebuffer hooks

**Definition**

```c
struct drm_framebuffer_funcs {
    void (*destroy)(struct drm_framebuffer *framebuffer);
    int (*create_handle)(struct drm_framebuffer *fb, struct drm_file *file_priv, unsigned int *handle);
    int (*dirty)(struct drm_framebuffer *framebuffer, struct drm_file *file_priv, unsigned flags, unsigned color, struct drm_clip_rect *clips, unsigned num_clips);
};
```

**Members**

- `destroy`: Clean up framebuffer resources, specifically also unreference the
  backing storage. The core guarantees to call this function for every
  framebuffer successfully created by calling
  [`drm_mode_config_funcs.fb_create`](#c-struct-drm_mode_config_funcs). Drivers must also call
  [`drm_framebuffer_cleanup()`](#c-drm_framebuffer_cleanup) to release DRM core resources for this
  framebuffer.
- `create_handle`: Create a buffer handle in the driver-specific buffer manager (either
  GEM or TTM) valid for the passed-in [`struct drm_file`](/kernel/hardware/gpu/drm-internals.md#c-struct-drm_file). This is used by
  the core to implement the GETFB IOCTL, which returns (for
  sufficiently priviledged user) also a native buffer handle. This can
  be used for seamless transitions between modesetting clients by
  copying the current screen contents to a private buffer and blending
  between that and the new contents.

  GEM based drivers should call [`drm_gem_handle_create()`](/kernel/hardware/gpu/drm-mm.md#c-drm_gem_handle_create) to create the
  handle.

  RETURNS:

  0 on success or a negative error code on failure.
- `dirty`: Optional callback for the dirty fb IOCTL.

  Userspace can notify the driver via this callback that an area of the
  framebuffer has changed and should be flushed to the display
  hardware. This can also be used internally, e.g. by the fbdev
  emulation, though that's not the case currently.

  See documentation in drm_mode.h for the struct drm_mode_fb_dirty_cmd
  for more information as all the semantics and arguments have a one to
  one mapping on this function.

  Atomic drivers should use [`drm_atomic_helper_dirtyfb()`](#c-drm_atomic_helper_dirtyfb) to implement
  this hook.

  RETURNS:

  0 on success or a negative error code on failure.

#### <a id="c-struct-drm_framebuffer"></a>`struct drm_framebuffer`

frame buffer object

**Definition**

```c
struct drm_framebuffer {
    struct drm_device *dev;
    struct list_head head;
    struct drm_mode_object base;
    char comm[TASK_COMM_LEN];
    const struct drm_format_info *format;
    const struct drm_framebuffer_funcs *funcs;
    unsigned int pitches[DRM_FORMAT_MAX_PLANES];
    unsigned int offsets[DRM_FORMAT_MAX_PLANES];
    uint64_t modifier;
    unsigned int width;
    unsigned int height;
    int flags;
    unsigned int internal_flags;
    struct list_head filp_head;
    struct drm_gem_object *obj[DRM_FORMAT_MAX_PLANES];
};
```

**Members**

- `dev`: DRM device this framebuffer belongs to
- `head`: Place on the [`drm_mode_config.fb_list`](#c-struct-drm_mode_config), access protected by
  [`drm_mode_config.fb_lock`](#c-struct-drm_mode_config).
- `base`: base modeset object structure, contains the reference count.
- `comm`: Name of the process allocating the fb, used for fb dumping.
- `format`: framebuffer format information
- `funcs`: framebuffer vfunc table
- `pitches`: Line stride per buffer. For userspace created object this
  is copied from drm_mode_fb_cmd2.
- `offsets`: Offset from buffer start to the actual pixel data in bytes,
  per buffer. For userspace created object this is copied from
  drm_mode_fb_cmd2.

  Note that this is a linear offset and does not take into account
  tiling or buffer layout per **modifier**. It is meant to be used when
  the actual pixel data for this framebuffer plane starts at an offset,
  e.g. when multiple planes are allocated within the same backing
  storage buffer object. For tiled layouts this generally means its
  **offsets** must at least be tile-size aligned, but hardware often has
  stricter requirements.

  This should not be used to specifiy x/y pixel offsets into the buffer
  data (even for linear buffers). Specifying an x/y pixel offset is
  instead done through the source rectangle in [`struct drm_plane_state`](#c-struct-drm_plane_state).
- `modifier`: Data layout modifier. This is used to describe
  tiling, or also special layouts (like compression) of auxiliary
  buffers. For userspace created object this is copied from
  drm_mode_fb_cmd2.
- `width`: Logical width of the visible area of the framebuffer, in
  pixels.
- `height`: Logical height of the visible area of the framebuffer, in
  pixels.
- `flags`: Framebuffer flags like DRM_MODE_FB_INTERLACED or
  DRM_MODE_FB_MODIFIERS.
- `internal_flags`: Framebuffer flags like DRM_FRAMEBUFFER_HAS_HANDLE_REF.
- `filp_head`: Placed on [`drm_file.fbs`](/kernel/hardware/gpu/drm-internals.md#c-struct-drm_file), protected by [`drm_file.fbs_lock`](/kernel/hardware/gpu/drm-internals.md#c-struct-drm_file).
- `obj`: GEM objects backing the framebuffer, one per plane (optional).

  This is used by the GEM framebuffer helpers, see e.g.
  [`drm_gem_fb_create()`](/kernel/hardware/gpu/drm-kms-helpers.md#c-drm_gem_fb_create).

**Description**

Note that the fb is refcounted for the benefit of driver internals,
for example some hw, disabling a CRTC/plane is asynchronous, and
scanout does not actually complete until the next vblank.  So some
cleanup (like releasing the reference(s) on the backing GEM bo(s))
should be deferred.  In cases like this, the driver would like to
hold a ref to the fb even though it has already been removed from
userspace perspective. See [`drm_framebuffer_get()`](#c-drm_framebuffer_get) and
[`drm_framebuffer_put()`](#c-drm_framebuffer_put).

The refcount is stored inside the mode object **base**.

#### <a id="c-drm_framebuffer_get"></a>`drm_framebuffer_get()`

```c
void drm_framebuffer_get(struct drm_framebuffer *fb)
```

acquire a framebuffer reference

**Parameters**

- `struct drm_framebuffer *fb`: DRM framebuffer

**Description**

This function increments the framebuffer's reference count.

#### <a id="c-drm_framebuffer_put"></a>`drm_framebuffer_put()`

```c
void drm_framebuffer_put(struct drm_framebuffer *fb)
```

release a framebuffer reference

**Parameters**

- `struct drm_framebuffer *fb`: DRM framebuffer

**Description**

This function decrements the framebuffer's reference count and frees the
framebuffer if the reference count drops to zero.

#### <a id="c-drm_framebuffer_read_refcount"></a>`drm_framebuffer_read_refcount()`

```c
uint32_t drm_framebuffer_read_refcount(const struct drm_framebuffer *fb)
```

read the framebuffer reference count.

**Parameters**

- `const struct drm_framebuffer *fb`: framebuffer

**Description**

This functions returns the framebuffer's reference count.

#### <a id="c-drm_framebuffer_assign"></a>`drm_framebuffer_assign()`

```c
void drm_framebuffer_assign(struct drm_framebuffer **p, struct drm_framebuffer *fb)
```

store a reference to the fb

**Parameters**

- `struct drm_framebuffer **p`: location to store framebuffer
- `struct drm_framebuffer *fb`: new framebuffer (maybe NULL)

**Description**

This functions sets the location to store a reference to the framebuffer,
unreferencing the framebuffer that was previously stored in that location.

#### <a id="c-struct-drm_afbc_framebuffer"></a>`struct drm_afbc_framebuffer`

a special afbc frame buffer object

**Definition**

```c
struct drm_afbc_framebuffer {
    struct drm_framebuffer base;
    u32 block_width;
    u32 block_height;
    u32 aligned_width;
    u32 aligned_height;
    u32 offset;
    u32 afbc_size;
};
```

**Members**

- `base`: base framebuffer structure.
- `block_width`: width of a single afbc block
- `block_height`: height of a single afbc block
- `aligned_width`: aligned frame buffer width
- `aligned_height`: aligned frame buffer height
- `offset`: offset of the first afbc header
- `afbc_size`: minimum size of afbc buffer

**Description**

A derived class of struct drm_framebuffer, dedicated for afbc use cases.



#### <a id="c-drm_framebuffer_init"></a>`drm_framebuffer_init()`

```c
int drm_framebuffer_init(struct drm_device *dev, struct drm_framebuffer *fb, const struct drm_framebuffer_funcs *funcs)
```

initialize a framebuffer

**Parameters**

- `struct drm_device *dev`: DRM device
- `struct drm_framebuffer *fb`: framebuffer to be initialized
- `const struct drm_framebuffer_funcs *funcs`: ... with these functions

**Description**

Allocates an ID for the framebuffer's parent mode object, sets its mode
functions & device file and adds it to the master fd list.

IMPORTANT:
This functions publishes the fb and makes it available for concurrent access
by other users. Which means by this point the fb _must_ be fully set up -
since all the fb attributes are invariant over its lifetime, no further
locking but only correct reference counting is required.

**Return**

Zero on success, error code on failure.

#### <a id="c-drm_framebuffer_lookup"></a>`drm_framebuffer_lookup()`

```c
struct drm_framebuffer * drm_framebuffer_lookup(struct drm_device *dev, struct drm_file *file_priv, uint32_t id)
```

look up a drm framebuffer and grab a reference

**Parameters**

- `struct drm_device *dev`: drm device
- `struct drm_file *file_priv`: drm file to check for lease against.
- `uint32_t id`: id of the fb object

**Description**

If successful, this grabs an additional reference to the framebuffer -
callers need to make sure to eventually unreference the returned framebuffer
again, using [`drm_framebuffer_put()`](#c-drm_framebuffer_put).

#### <a id="c-drm_framebuffer_unregister_private"></a>`drm_framebuffer_unregister_private()`

```c
void drm_framebuffer_unregister_private(struct drm_framebuffer *fb)
```

unregister a private fb from the lookup idr

**Parameters**

- `struct drm_framebuffer *fb`: fb to unregister

**Description**

Drivers need to call this when cleaning up driver-private framebuffers, e.g.
those used for fbdev. Note that the caller must hold a reference of its own,
i.e. the object may not be destroyed through this call (since it'll lead to a
locking inversion).

**NOTE**

This function is deprecated. For driver-private framebuffers it is not
recommended to embed a framebuffer struct info fbdev struct, instead, a
framebuffer pointer is preferred and [`drm_framebuffer_put()`](#c-drm_framebuffer_put) should be called
when the framebuffer is to be cleaned up.

#### <a id="c-drm_framebuffer_cleanup"></a>`drm_framebuffer_cleanup()`

```c
void drm_framebuffer_cleanup(struct drm_framebuffer *fb)
```

remove a framebuffer object

**Parameters**

- `struct drm_framebuffer *fb`: framebuffer to remove

**Description**

Cleanup framebuffer. This function is intended to be used from the drivers
[`drm_framebuffer_funcs.destroy`](#c-struct-drm_framebuffer_funcs) callback. It can also be used to clean up
driver private framebuffers embedded into a larger structure.

Note that this function does not remove the fb from active usage - if it is
still used anywhere, hilarity can ensue since userspace could call getfb on
the id and get back -EINVAL. Obviously no concern at driver unload time.

Also, the framebuffer will not be removed from the lookup idr - for
user-created framebuffers this will happen in the rmfb ioctl. For
driver-private objects (e.g. for fbdev) drivers need to explicitly call
drm_framebuffer_unregister_private.

#### <a id="c-drm_framebuffer_remove"></a>`drm_framebuffer_remove()`

```c
void drm_framebuffer_remove(struct drm_framebuffer *fb)
```

remove and unreference a framebuffer object

**Parameters**

- `struct drm_framebuffer *fb`: framebuffer to remove

**Description**

Scans all the CRTCs and planes in **dev**'s mode_config.  If they're
using **fb**, removes it, setting it to NULL. Then drops the reference to the
passed-in framebuffer. Might take the modeset locks.

Note that this function optimizes the cleanup away if the caller holds the
last reference to the framebuffer. It is also guaranteed to not take the
modeset locks in this case.


<a id="rst-drm-format-handling"></a>

## DRM Format Handling


In the DRM subsystem, framebuffer pixel formats are described using the
fourcc codes defined in `include/uapi/drm/drm_fourcc.h`. In addition to the
fourcc code, a Format Modifier may optionally be provided, in order to
further describe the buffer's format - for example tiling or compression.

**Format Modifiers**

Format modifiers are used in conjunction with a fourcc code, forming a
unique fourcc:modifier pair. This format:modifier pair must fully define the
format and data layout of the buffer, and should be the only way to describe
that particular buffer.

Having multiple fourcc:modifier pairs which describe the same layout should
be avoided, as such aliases run the risk of different drivers exposing
different names for the same data format, forcing userspace to understand
that they are aliases.

Format modifiers may change any property of the buffer, including the number
of planes and/or the required allocation size. Format modifiers are
vendor-namespaced, and as such the relationship between a fourcc code and a
modifier is specific to the modifier being used. For example, some modifiers
may preserve meaning - such as number of planes - from the fourcc code,
whereas others may not.

Modifiers must uniquely encode buffer layout. In other words, a buffer must
match only a single modifier. A modifier must not be a subset of layouts of
another modifier. For instance, it's incorrect to encode pitch alignment in
a modifier: a buffer may match a 64-pixel aligned modifier and a 32-pixel
aligned modifier. That said, modifiers can have implicit minimal
requirements.

For modifiers where the combination of fourcc code and modifier can alias,
a canonical pair needs to be defined and used by all drivers. Preferred
combinations are also encouraged where all combinations might lead to
confusion and unnecessarily reduced interoperability. An example for the
latter is AFBC, where the ABGR layouts are preferred over ARGB layouts.

There are two kinds of modifier users:

- Kernel and user-space drivers: for drivers it's important that modifiers
  don't alias, otherwise two drivers might support the same format but use
  different aliases, preventing them from sharing buffers in an efficient
  format.
- Higher-level programs interfacing with KMS/GBM/EGL/Vulkan/etc: these users
  see modifiers as opaque tokens they can check for equality and intersect.
  These users mustn't need to know to reason about the modifier value
  (i.e. they are not expected to extract information out of the modifier).

Vendors should document their modifier usage in as much detail as
possible, to ensure maximum compatibility across devices, drivers and
applications.

The authoritative list of format modifier codes is found in
`include/uapi/drm/drm_fourcc.h`

**Open Source User Waiver**

Because this is the authoritative source for pixel formats and modifiers
referenced by GL, Vulkan extensions and other standards and hence used both
by open source and closed source driver stacks, the usual requirement for an
upstream in-kernel or open source userspace user does not apply.

To ensure, as much as feasible, compatibility across stacks and avoid
confusion with incompatible enumerations stakeholders for all relevant driver
stacks should approve additions.


<a id="rst-format-functions-reference"></a>

### Format Functions Reference


#### <a id="c-DRM_FORMAT_MAX_PLANES"></a>`DRM_FORMAT_MAX_PLANES`

```c
DRM_FORMAT_MAX_PLANES
```

maximum number of planes a DRM format can have

#### <a id="c-struct-drm_format_info"></a>`struct drm_format_info`

information about a DRM format

**Definition**

```c
struct drm_format_info {
    u32 format;
    u8 depth;
    u8 num_planes;
    union {
        u8 cpp[DRM_FORMAT_MAX_PLANES];
        u8 char_per_block[DRM_FORMAT_MAX_PLANES];
    };
    u8 block_w[DRM_FORMAT_MAX_PLANES];
    u8 block_h[DRM_FORMAT_MAX_PLANES];
    u8 hsub;
    u8 vsub;
    bool has_alpha;
    bool is_yuv;
    bool is_color_indexed;
};
```

**Members**

- `format`: 4CC format identifier (DRM_FORMAT_*)
- `depth`: Color depth (number of bits per pixel excluding padding bits),
  valid for a subset of RGB formats only. This is a legacy field, do
  not use in new code and set to 0 for new formats.
- `num_planes`: Number of color planes (1 to 3)
- `{unnamed_union}`: anonymous
- `cpp`: Number of bytes per pixel (per plane), this is aliased with
  **char_per_block**. It is deprecated in favour of using the
  triplet **char_per_block**, **block_w**, **block_h** for better
  describing the pixel format.
- `char_per_block`: Number of bytes per block (per plane), where blocks are
  defined as a rectangle of pixels which are stored next to
  each other in a byte aligned memory region. Together with
  **block_w** and **block_h** this is used to properly describe tiles
  in tiled formats or to describe groups of pixels in packed
  formats for which the memory needed for a single pixel is not
  byte aligned.

  **cpp** has been kept for historical reasons because there are
  a lot of places in drivers where it's used. In drm core for
  generic code paths the preferred way is to use
  **char_per_block**, [`drm_format_info_block_width()`](#c-drm_format_info_block_width) and
  [`drm_format_info_block_height()`](#c-drm_format_info_block_height) which allows handling both
  block and non-block formats in the same way.

  For formats that are intended to be used only with non-linear
  modifiers both **cpp** and **char_per_block** must be 0 in the
  generic format table. Drivers could supply accurate
  information from their drm_mode_config.get_format_info hook
  if they want the core to be validating the pitch.
- `block_w`: Block width in pixels, this is intended to be accessed through
  [`drm_format_info_block_width()`](#c-drm_format_info_block_width)
- `block_h`: Block height in pixels, this is intended to be accessed through
  [`drm_format_info_block_height()`](#c-drm_format_info_block_height)
- `hsub`: Horizontal chroma subsampling factor
- `vsub`: Vertical chroma subsampling factor
- `has_alpha`: Does the format embeds an alpha component?
- `is_yuv`: Is it a YUV format?
- `is_color_indexed`: Is it a color-indexed format?

#### <a id="c-drm_format_info_is_yuv_packed"></a>`drm_format_info_is_yuv_packed()`

```c
bool drm_format_info_is_yuv_packed(const struct drm_format_info *info)
```

check that the format info matches a YUV format with data laid in a single plane

**Parameters**

- `const struct drm_format_info *info`: format info

**Return**

A boolean indicating whether the format info matches a packed YUV format.

#### <a id="c-drm_format_info_is_yuv_semiplanar"></a>`drm_format_info_is_yuv_semiplanar()`

```c
bool drm_format_info_is_yuv_semiplanar(const struct drm_format_info *info)
```

check that the format info matches a YUV format with data laid in two planes (luminance and chrominance)

**Parameters**

- `const struct drm_format_info *info`: format info

**Return**

A boolean indicating whether the format info matches a semiplanar YUV format.

#### <a id="c-drm_format_info_is_yuv_planar"></a>`drm_format_info_is_yuv_planar()`

```c
bool drm_format_info_is_yuv_planar(const struct drm_format_info *info)
```

check that the format info matches a YUV format with data laid in three planes (one for each YUV component)

**Parameters**

- `const struct drm_format_info *info`: format info

**Return**

A boolean indicating whether the format info matches a planar YUV format.

#### <a id="c-drm_format_info_is_yuv_sampling_410"></a>`drm_format_info_is_yuv_sampling_410()`

```c
bool drm_format_info_is_yuv_sampling_410(const struct drm_format_info *info)
```

check that the format info matches a YUV format with 4:1:0 sub-sampling

**Parameters**

- `const struct drm_format_info *info`: format info

**Return**

A boolean indicating whether the format info matches a YUV format with 4:1:0
sub-sampling.

#### <a id="c-drm_format_info_is_yuv_sampling_411"></a>`drm_format_info_is_yuv_sampling_411()`

```c
bool drm_format_info_is_yuv_sampling_411(const struct drm_format_info *info)
```

check that the format info matches a YUV format with 4:1:1 sub-sampling

**Parameters**

- `const struct drm_format_info *info`: format info

**Return**

A boolean indicating whether the format info matches a YUV format with 4:1:1
sub-sampling.

#### <a id="c-drm_format_info_is_yuv_sampling_420"></a>`drm_format_info_is_yuv_sampling_420()`

```c
bool drm_format_info_is_yuv_sampling_420(const struct drm_format_info *info)
```

check that the format info matches a YUV format with 4:2:0 sub-sampling

**Parameters**

- `const struct drm_format_info *info`: format info

**Return**

A boolean indicating whether the format info matches a YUV format with 4:2:0
sub-sampling.

#### <a id="c-drm_format_info_is_yuv_sampling_422"></a>`drm_format_info_is_yuv_sampling_422()`

```c
bool drm_format_info_is_yuv_sampling_422(const struct drm_format_info *info)
```

check that the format info matches a YUV format with 4:2:2 sub-sampling

**Parameters**

- `const struct drm_format_info *info`: format info

**Return**

A boolean indicating whether the format info matches a YUV format with 4:2:2
sub-sampling.

#### <a id="c-drm_format_info_is_yuv_sampling_444"></a>`drm_format_info_is_yuv_sampling_444()`

```c
bool drm_format_info_is_yuv_sampling_444(const struct drm_format_info *info)
```

check that the format info matches a YUV format with 4:4:4 sub-sampling

**Parameters**

- `const struct drm_format_info *info`: format info

**Return**

A boolean indicating whether the format info matches a YUV format with 4:4:4
sub-sampling.

#### <a id="c-drm_format_info_plane_width"></a>`drm_format_info_plane_width()`

```c
int drm_format_info_plane_width(const struct drm_format_info *info, int width, int plane)
```

width of the plane given the first plane

**Parameters**

- `const struct drm_format_info *info`: pixel format info
- `int width`: width of the first plane
- `int plane`: plane index

**Return**

The width of **plane**, given that the width of the first plane is **width**.

#### <a id="c-drm_format_info_plane_height"></a>`drm_format_info_plane_height()`

```c
int drm_format_info_plane_height(const struct drm_format_info *info, int height, int plane)
```

height of the plane given the first plane

**Parameters**

- `const struct drm_format_info *info`: pixel format info
- `int height`: height of the first plane
- `int plane`: plane index

**Return**

The height of **plane**, given that the height of the first plane is **height**.



#### <a id="c-drm_mode_legacy_fb_format"></a>`drm_mode_legacy_fb_format()`

```c
uint32_t drm_mode_legacy_fb_format(uint32_t bpp, uint32_t depth)
```

compute drm fourcc code from legacy description

**Parameters**

- `uint32_t bpp`: bits per pixels
- `uint32_t depth`: bit depth per pixel

**Description**

Computes a drm fourcc pixel format code for the given **bpp**/**depth** values.

#### <a id="c-drm_driver_legacy_fb_format"></a>`drm_driver_legacy_fb_format()`

```c
uint32_t drm_driver_legacy_fb_format(struct drm_device *dev, uint32_t bpp, uint32_t depth)
```

compute drm fourcc code from legacy description

**Parameters**

- `struct drm_device *dev`: DRM device
- `uint32_t bpp`: bits per pixels
- `uint32_t depth`: bit depth per pixel

**Description**

Computes a drm fourcc pixel format code for the given **bpp**/**depth** values.
Unlike [`drm_mode_legacy_fb_format()`](#c-drm_mode_legacy_fb_format) this looks at the drivers mode_config,
and depending on the [`drm_mode_config.quirk_addfb_prefer_host_byte_order`](#c-struct-drm_mode_config) flag
it returns little endian byte order or host byte order framebuffer formats.

#### <a id="c-drm_driver_color_mode_format"></a>`drm_driver_color_mode_format()`

```c
uint32_t drm_driver_color_mode_format(struct drm_device *dev, unsigned int color_mode)
```

Compute DRM 4CC code from color mode

**Parameters**

- `struct drm_device *dev`: DRM device
- `unsigned int color_mode`: command-line color mode

**Description**

Computes a DRM 4CC pixel format code for the given color mode using
`drm_driver_color_mode()`. The color mode is in the format used and the
kernel command line. It specifies the number of bits per pixel
and color depth in a single value.

Useful in fbdev emulation code, since that deals in those values. The
helper does not consider YUV or other complicated formats. This means
only legacy formats are supported (fmt->depth is a legacy field), but
the framebuffer emulation can only deal with such formats, specifically
RGB/BGA formats.

#### <a id="c-drm_format_info"></a>`drm_format_info()`

```c
const struct drm_format_info * drm_format_info(u32 format)
```

query information for a given format

**Parameters**

- `u32 format`: pixel format (DRM_FORMAT_*)

**Description**

The caller should only pass a supported pixel format to this function.
Unsupported pixel formats will generate a warning in the kernel log.

**Return**

The instance of struct drm_format_info that describes the pixel format, or
NULL if the format is unsupported.

#### <a id="c-drm_get_format_info"></a>`drm_get_format_info()`

```c
const struct drm_format_info * drm_get_format_info(struct drm_device *dev, u32 pixel_format, u64 modifier)
```

query information for a given framebuffer configuration

**Parameters**

- `struct drm_device *dev`: DRM device
- `u32 pixel_format`: pixel format (DRM_FORMAT_*)
- `u64 modifier`: modifier

**Return**

The instance of struct drm_format_info that describes the pixel format, or
NULL if the format is unsupported.

#### <a id="c-drm_format_info_block_width"></a>`drm_format_info_block_width()`

```c
unsigned int drm_format_info_block_width(const struct drm_format_info *info, int plane)
```

width in pixels of block.

**Parameters**

- `const struct drm_format_info *info`: pixel format info
- `int plane`: plane index

**Return**

The width in pixels of a block, depending on the plane index.

#### <a id="c-drm_format_info_block_height"></a>`drm_format_info_block_height()`

```c
unsigned int drm_format_info_block_height(const struct drm_format_info *info, int plane)
```

height in pixels of a block

**Parameters**

- `const struct drm_format_info *info`: pixel format info
- `int plane`: plane index

**Return**

The height in pixels of a block, depending on the plane index.

#### <a id="c-drm_format_info_bpp"></a>`drm_format_info_bpp()`

```c
unsigned int drm_format_info_bpp(const struct drm_format_info *info, int plane)
```

number of bits per pixel

**Parameters**

- `const struct drm_format_info *info`: pixel format info
- `int plane`: plane index

**Return**

The actual number of bits per pixel, depending on the plane index.

#### <a id="c-drm_format_info_min_pitch"></a>`drm_format_info_min_pitch()`

```c
uint64_t drm_format_info_min_pitch(const struct drm_format_info *info, int plane, unsigned int buffer_width)
```

computes the minimum required pitch in bytes

**Parameters**

- `const struct drm_format_info *info`: pixel format info
- `int plane`: plane index
- `unsigned int buffer_width`: buffer width in pixels

**Return**

The minimum required pitch in bytes for a buffer by taking into consideration
the pixel format information and the buffer width.


<a id="rst-dumb-buffer-objects"></a>
<a id="rst-kms-dumb-buffer-objects"></a>

## Dumb Buffer Objects


The KMS API doesn't standardize backing storage object creation and leaves it
to driver-specific ioctls. Furthermore actually creating a buffer object even
for GEM-based drivers is done through a driver-specific ioctl - GEM only has
a common userspace interface for sharing and destroying objects. While not an
issue for full-fledged graphics stacks that include device-specific userspace
components (in libdrm for instance), this limit makes DRM-based early boot
graphics unnecessarily complex.

Dumb objects partly alleviate the problem by providing a standard API to
create dumb buffers suitable for scanout, which can then be used to create
KMS frame buffers.

To support dumb objects drivers must implement the [`drm_driver.dumb_create`](/kernel/hardware/gpu/drm-internals.md#c-struct-drm_driver)
and [`drm_driver.dumb_map_offset`](/kernel/hardware/gpu/drm-internals.md#c-struct-drm_driver) operations (the latter defaults to
[`drm_gem_dumb_map_offset()`](/kernel/hardware/gpu/drm-mm.md#c-drm_gem_dumb_map_offset) if not set). Drivers that don't use GEM handles
additionally need to implement the [`drm_driver.dumb_destroy`](/kernel/hardware/gpu/drm-internals.md#c-struct-drm_driver) operation. See
the callbacks for further details.

Note that dumb objects may not be used for gpu acceleration, as has been
attempted on some ARM embedded platforms. Such drivers really must have
a hardware-specific ioctl to allocate suitable buffer objects.


<a id="rst-plane-abstraction"></a>

## Plane Abstraction


A plane represents an image source that can be blended with or overlaid on
top of a CRTC during the scanout process. Planes take their input data from a
[`drm_framebuffer`](#c-struct-drm_framebuffer) object. The plane itself specifies the cropping and scaling
of that image, and where it is placed on the visible area of a display
pipeline, represented by [`drm_crtc`](#c-struct-drm_crtc). A plane can also have additional
properties that specify how the pixels are positioned and blended, like
rotation or Z-position. All these properties are stored in [`drm_plane_state`](#c-struct-drm_plane_state).

Unless explicitly specified (via CRTC property or otherwise), the active area
of a CRTC will be black by default. This means portions of the active area
which are not covered by a plane will be black, and alpha blending of any
planes with the CRTC background will blend with black at the lowest zpos.

To create a plane, a KMS drivers allocates and zeroes an instances of
[`struct drm_plane`](#c-struct-drm_plane) (possibly as part of a larger structure) and registers it
with a call to [`drm_universal_plane_init()`](#c-drm_universal_plane_init).

Each plane has a type, see enum drm_plane_type. A plane can be compatible
with multiple CRTCs, see [`drm_plane.possible_crtcs`](#c-struct-drm_plane).

Each CRTC must have a unique primary plane userspace can attach to enable
the CRTC. In other words, userspace must be able to attach a different
primary plane to each CRTC at the same time. Primary planes can still be
compatible with multiple CRTCs. There must be exactly as many primary planes
as there are CRTCs.

Legacy uAPI doesn't expose the primary and cursor planes directly. DRM core
relies on the driver to set the primary and optionally the cursor plane used
for legacy IOCTLs. This is done by calling [`drm_crtc_init_with_planes()`](#c-drm_crtc_init_with_planes). All
drivers must provide one primary plane per CRTC to avoid surprising legacy
userspace too much.


<a id="rst-plane-functions-reference"></a>

### Plane Functions Reference


#### <a id="c-struct-drm_plane_state"></a>`struct drm_plane_state`

mutable plane state

**Definition**

```c
struct drm_plane_state {
    struct drm_plane *plane;
    struct drm_crtc *crtc;
    struct drm_framebuffer *fb;
    struct dma_fence *fence;
    int32_t crtc_x;
    int32_t crtc_y;
    uint32_t crtc_w, crtc_h;
    uint32_t src_x;
    uint32_t src_y;
    uint32_t src_h, src_w;
    int32_t hotspot_x, hotspot_y;
    u16 alpha;
    uint16_t pixel_blend_mode;
    unsigned int rotation;
    unsigned int zpos;
    unsigned int normalized_zpos;
    enum drm_color_encoding color_encoding;
    enum drm_color_range color_range;
    struct drm_property_blob *fb_damage_clips;
    bool ignore_damage_clips;
    struct drm_rect src, dst;
    bool visible;
    enum drm_scaling_filter scaling_filter;
    struct drm_colorop *color_pipeline;
    struct drm_crtc_commit *commit;
    struct drm_atomic_state *state;
    bool color_mgmt_changed : 1;
};
```

**Members**

- `plane`: backpointer to the plane
- `crtc`: Currently bound CRTC, NULL if disabled. Do not write this directly,
  use [`drm_atomic_set_crtc_for_plane()`](#c-drm_atomic_set_crtc_for_plane)
- `fb`: Currently bound framebuffer. Do not write this directly, use
  [`drm_atomic_set_fb_for_plane()`](#c-drm_atomic_set_fb_for_plane)
- `fence`: Optional fence to wait for before scanning out **fb**. The core atomic
  code will set this when userspace is using explicit fencing. Do not
  write this field directly for a driver's implicit fence.

  Drivers should store any implicit fence in this from their
  [`drm_plane_helper_funcs.prepare_fb`](/kernel/hardware/gpu/drm-kms-helpers.md#c-struct-drm_plane_helper_funcs) callback. See
  [`drm_gem_plane_helper_prepare_fb()`](/kernel/hardware/gpu/drm-kms-helpers.md#c-drm_gem_plane_helper_prepare_fb) for a suitable helper.
- `crtc_x`: Left position of visible portion of plane on crtc, signed dest
  location allows it to be partially off screen.
- `crtc_y`: Upper position of visible portion of plane on crtc, signed dest
  location allows it to be partially off screen.
- `crtc_w`: width of visible portion of plane on crtc
- `crtc_h`: height of visible portion of plane on crtc
- `src_x`: left position of visible portion of plane within plane (in
  16.16 fixed point).
- `src_y`: upper position of visible portion of plane within plane (in
  16.16 fixed point).
- `src_h`: height of visible portion of plane (in 16.16)
- `src_w`: width of visible portion of plane (in 16.16)
- `hotspot_x`: x offset to mouse cursor hotspot
- `hotspot_y`: y offset to mouse cursor hotspot
- `alpha`: Opacity of the plane with 0 as completely transparent and 0xffff as
  completely opaque. See [`drm_plane_create_alpha_property()`](#c-drm_plane_create_alpha_property) for more
  details.
- `pixel_blend_mode`: The alpha blending equation selection, describing how the pixels from
  the current plane are composited with the background. Value can be
  one of DRM_MODE_BLEND_*
- `rotation`: Rotation of the plane. See [`drm_plane_create_rotation_property()`](#c-drm_plane_create_rotation_property) for
  more details.
- `zpos`: Priority of the given plane on crtc (optional).

  User-space may set mutable zpos properties so that multiple active
  planes on the same CRTC have identical zpos values. This is a
  user-space bug, but drivers can solve the conflict by comparing the
  plane object IDs; the plane with a higher ID is stacked on top of a
  plane with a lower ID.

  See [`drm_plane_create_zpos_property()`](#c-drm_plane_create_zpos_property) and
  [`drm_plane_create_zpos_immutable_property()`](#c-drm_plane_create_zpos_immutable_property) for more details.
- `normalized_zpos`: Normalized value of zpos: unique, range from 0 to N-1 where N is the
  number of active planes for given crtc. Note that the driver must set
  [`drm_mode_config.normalize_zpos`](#c-struct-drm_mode_config) or call [`drm_atomic_normalize_zpos()`](#c-drm_atomic_normalize_zpos) to
  update this before it can be trusted.
- `color_encoding`: Color encoding for non RGB formats
- `color_range`: Color range for non RGB formats
- `fb_damage_clips`: Blob representing damage (area in plane framebuffer that changed
  since last plane update) as an array of [`drm_mode_rect`](/kernel/hardware/gpu/drm-uapi.md#c-struct-drm_mode_rect) in framebuffer
  coodinates of the attached framebuffer. Note that unlike plane src,
  damage clips are not in 16.16 fixed point.

  See [`drm_plane_get_damage_clips()`](#c-drm_plane_get_damage_clips) and
  [`drm_plane_get_damage_clips_count()`](#c-drm_plane_get_damage_clips_count) for accessing these.
- `ignore_damage_clips`: Set by drivers to indicate the [`drm_atomic_helper_damage_iter_init()`](#c-drm_atomic_helper_damage_iter_init)
  helper that the **fb_damage_clips** blob property should be ignored.

  See damage_tracking_properties for more information.
- `src`: source coordinates of the plane (in 16.16).

  When using [`drm_atomic_helper_check_plane_state()`](/kernel/hardware/gpu/drm-kms-helpers.md#c-drm_atomic_helper_check_plane_state),
  the coordinates are clipped, but the driver may choose
  to use unclipped coordinates instead when the hardware
  performs the clipping automatically.
- `dst`: clipped destination coordinates of the plane.

  When using [`drm_atomic_helper_check_plane_state()`](/kernel/hardware/gpu/drm-kms-helpers.md#c-drm_atomic_helper_check_plane_state),
  the coordinates are clipped, but the driver may choose
  to use unclipped coordinates instead when the hardware
  performs the clipping automatically.
- `visible`: Visibility of the plane. This can be false even if fb!=NULL and
  crtc!=NULL, due to clipping.
- `scaling_filter`: Scaling filter to be applied
- `color_pipeline`: The first colorop of the active color pipeline, or NULL, if no
  color pipeline is active.
- `commit`: Tracks the pending commit to prevent use-after-free conditions,
  and for async plane updates.

  May be NULL.
- `state`: backpointer to global drm_atomic_state
- `color_mgmt_changed`: Color management properties have changed. Used
  by the atomic helpers and drivers to steer the atomic commit control
  flow.

**Description**

Please note that the destination coordinates **crtc_x**, **crtc_y**, **crtc_h** and
**crtc_w** and the source coordinates **src_x**, **src_y**, **src_h** and **src_w** are the
raw coordinates provided by userspace. Drivers should use
[`drm_atomic_helper_check_plane_state()`](/kernel/hardware/gpu/drm-kms-helpers.md#c-drm_atomic_helper_check_plane_state) and only use the derived rectangles in
**src** and **dst** to program the hardware.

#### <a id="c-struct-drm_plane_funcs"></a>`struct drm_plane_funcs`

driver plane control functions

**Definition**

```c
struct drm_plane_funcs {
    int (*update_plane)(struct drm_plane *plane, struct drm_crtc *crtc, struct drm_framebuffer *fb, int crtc_x, int crtc_y, unsigned int crtc_w, unsigned int crtc_h, uint32_t src_x, uint32_t src_y, uint32_t src_w, uint32_t src_h, struct drm_modeset_acquire_ctx *ctx);
    int (*disable_plane)(struct drm_plane *plane, struct drm_modeset_acquire_ctx *ctx);
    void (*destroy)(struct drm_plane *plane);
    void (*reset)(struct drm_plane *plane);
    int (*set_property)(struct drm_plane *plane, struct drm_property *property, uint64_t val);
    struct drm_plane_state *(*atomic_duplicate_state)(struct drm_plane *plane);
    void (*atomic_destroy_state)(struct drm_plane *plane, struct drm_plane_state *state);
    int (*atomic_set_property)(struct drm_plane *plane, struct drm_plane_state *state, struct drm_property *property, uint64_t val);
    int (*atomic_get_property)(struct drm_plane *plane, const struct drm_plane_state *state, struct drm_property *property, uint64_t *val);
    int (*late_register)(struct drm_plane *plane);
    void (*early_unregister)(struct drm_plane *plane);
    void (*atomic_print_state)(struct drm_printer *p, const struct drm_plane_state *state);
    bool (*format_mod_supported)(struct drm_plane *plane, uint32_t format, uint64_t modifier);
    bool (*format_mod_supported_async)(struct drm_plane *plane, u32 format, u64 modifier);
};
```

**Members**

- `update_plane`: This is the legacy entry point to enable and configure the plane for
  the given CRTC and framebuffer. It is never called to disable the
  plane, i.e. the passed-in crtc and fb paramters are never NULL.

  The source rectangle in frame buffer memory coordinates is given by
  the src_x, src_y, src_w and src_h parameters (as 16.16 fixed point
  values). Devices that don't support subpixel plane coordinates can
  ignore the fractional part.

  The destination rectangle in CRTC coordinates is given by the
  crtc_x, crtc_y, crtc_w and crtc_h parameters (as integer values).
  Devices scale the source rectangle to the destination rectangle. If
  scaling is not supported, and the source rectangle size doesn't match
  the destination rectangle size, the driver must return a
  -\<errorname>EINVAL\</errorname> error.

  Drivers implementing atomic modeset should use
  [`drm_atomic_helper_update_plane()`](/kernel/hardware/gpu/drm-kms-helpers.md#c-drm_atomic_helper_update_plane) to implement this hook.

  RETURNS:

  0 on success or a negative error code on failure.
- `disable_plane`: This is the legacy entry point to disable the plane. The DRM core
  calls this method in response to a DRM_IOCTL_MODE_SETPLANE IOCTL call
  with the frame buffer ID set to 0.  Disabled planes must not be
  processed by the CRTC.

  Drivers implementing atomic modeset should use
  [`drm_atomic_helper_disable_plane()`](/kernel/hardware/gpu/drm-kms-helpers.md#c-drm_atomic_helper_disable_plane) to implement this hook.

  RETURNS:

  0 on success or a negative error code on failure.
- `destroy`: Clean up plane resources. This is only called at driver unload time
  through [`drm_mode_config_cleanup()`](#c-drm_mode_config_cleanup) since a plane cannot be hotplugged
  in DRM.
- `reset`: Reset plane hardware and software state to off. This function isn't
  called by the core directly, only through [`drm_mode_config_reset()`](#c-drm_mode_config_reset).
  It's not a helper hook only for historical reasons.

  Atomic drivers can use [`drm_atomic_helper_plane_reset()`](/kernel/hardware/gpu/drm-kms-helpers.md#c-drm_atomic_helper_plane_reset) to reset
  atomic state using this hook.
- `set_property`: This is the legacy entry point to update a property attached to the
  plane.

  This callback is optional if the driver does not support any legacy
  driver-private properties. For atomic drivers it is not used because
  property handling is done entirely in the DRM core.

  RETURNS:

  0 on success or a negative error code on failure.
- `atomic_duplicate_state`: Duplicate the current atomic state for this plane and return it.
  The core and helpers guarantee that any atomic state duplicated with
  this hook and still owned by the caller (i.e. not transferred to the
  driver by calling [`drm_mode_config_funcs.atomic_commit`](#c-struct-drm_mode_config_funcs)) will be
  cleaned up by calling the **atomic_destroy_state** hook in this
  structure.

  This callback is mandatory for atomic drivers.

  Atomic drivers which don't subclass [`struct drm_plane_state`](#c-struct-drm_plane_state) should use
  [`drm_atomic_helper_plane_duplicate_state()`](/kernel/hardware/gpu/drm-kms-helpers.md#c-drm_atomic_helper_plane_duplicate_state). Drivers that subclass the
  state structure to extend it with driver-private state should use
  [`__drm_atomic_helper_plane_duplicate_state()`](/kernel/hardware/gpu/drm-kms-helpers.md#c-__drm_atomic_helper_plane_duplicate_state) to make sure shared state is
  duplicated in a consistent fashion across drivers.

  It is an error to call this hook before [`drm_plane.state`](#c-struct-drm_plane) has been
  initialized correctly.

  NOTE:

  If the duplicate state references refcounted resources this hook must
  acquire a reference for each of them. The driver must release these
  references again in **atomic_destroy_state**.

  RETURNS:

  Duplicated atomic state or NULL when the allocation failed.
- `atomic_destroy_state`: Destroy a state duplicated with **atomic_duplicate_state** and release
  or unreference all resources it references

  This callback is mandatory for atomic drivers.
- `atomic_set_property`: Decode a driver-private property value and store the decoded value
  into the passed-in state structure. Since the atomic core decodes all
  standardized properties (even for extensions beyond the core set of
  properties which might not be implemented by all drivers) this
  requires drivers to subclass the state structure.

  Such driver-private properties should really only be implemented for
  truly hardware/vendor specific state. Instead it is preferred to
  standardize atomic extension and decode the properties used to expose
  such an extension in the core.

  Do not call this function directly, use
  `drm_atomic_plane_set_property()` instead.

  This callback is optional if the driver does not support any
  driver-private atomic properties.

  NOTE:

  This function is called in the state assembly phase of atomic
  modesets, which can be aborted for any reason (including on
  userspace's request to just check whether a configuration would be
  possible). Drivers MUST NOT touch any persistent state (hardware or
  software) or data structures except the passed in **state** parameter.

  Also since userspace controls in which order properties are set this
  function must not do any input validation (since the state update is
  incomplete and hence likely inconsistent). Instead any such input
  validation must be done in the various atomic_check callbacks.

  RETURNS:

  0 if the property has been found, -EINVAL if the property isn't
  implemented by the driver (which shouldn't ever happen, the core only
  asks for properties attached to this plane). No other validation is
  allowed by the driver. The core already checks that the property
  value is within the range (integer, valid enum value, ...) the driver
  set when registering the property.
- `atomic_get_property`: Reads out the decoded driver-private property. This is used to
  implement the GETPLANE IOCTL.

  Do not call this function directly, use
  `drm_atomic_plane_get_property()` instead.

  This callback is optional if the driver does not support any
  driver-private atomic properties.

  RETURNS:

  0 on success, -EINVAL if the property isn't implemented by the
  driver (which should never happen, the core only asks for
  properties attached to this plane).
- `late_register`: This optional hook can be used to register additional userspace
  interfaces attached to the plane like debugfs interfaces.
  It is called late in the driver load sequence from [`drm_dev_register()`](/kernel/hardware/gpu/drm-internals.md#c-drm_dev_register).
  Everything added from this callback should be unregistered in
  the early_unregister callback.

  Returns:

  0 on success, or a negative error code on failure.
- `early_unregister`: This optional hook should be used to unregister the additional
  userspace interfaces attached to the plane from
  **late_register**. It is called from [`drm_dev_unregister()`](/kernel/hardware/gpu/drm-internals.md#c-drm_dev_unregister),
  early in the driver unload sequence to disable userspace access
  before data structures are torndown.
- `atomic_print_state`: If driver subclasses [`struct drm_plane_state`](#c-struct-drm_plane_state), it should implement
  this optional hook for printing additional driver specific state.

  Do not call this directly, use `drm_atomic_plane_print_state()`
  instead.
- `format_mod_supported`: This optional hook is used for the DRM to determine if the given
  format/modifier combination is valid for the plane. This allows the
  DRM to generate the correct format bitmask (which formats apply to
  which modifier), and to validate modifiers at atomic_check time.

  If not present, then any modifier in the plane's modifier
  list is allowed with any of the plane's formats.

  Returns:

  True if the given modifier is valid for that format on the plane.
  False otherwise.
- `format_mod_supported_async`: This optional hook is used for the DRM to determine if for
  asynchronous flip the given format/modifier combination is valid for
  the plane. This allows the DRM to generate the correct format
  bitmask (which formats apply to which modifier), and to validate
  modifiers at atomic_check time.

  Returns:

  True if the given modifier is valid for that format on the plane.
  False otherwise.

#### <a id="c-enum-drm_plane_type"></a>`enum drm_plane_type`

uapi plane type enumeration

**Constants**

- `DRM_PLANE_TYPE_OVERLAY`: Overlay planes represent all non-primary, non-cursor planes. Some
  drivers refer to these types of planes as "sprites" internally.
- `DRM_PLANE_TYPE_PRIMARY`: A primary plane attached to a CRTC is the most likely to be able to
  light up the CRTC when no scaling/cropping is used and the plane
  covers the whole CRTC.
- `DRM_PLANE_TYPE_CURSOR`: A cursor plane attached to a CRTC is more likely to be able to be
  enabled when no scaling/cropping is used and the framebuffer has the
  size indicated by [`drm_mode_config.cursor_width`](#c-struct-drm_mode_config) and
  [`drm_mode_config.cursor_height`](#c-struct-drm_mode_config). Additionally, if the driver doesn't
  support modifiers, the framebuffer should have a linear layout.

**Description**

For historical reasons not all planes are made the same. This enumeration is
used to tell the different types of planes apart to implement the different
uapi semantics for them. For userspace which is universal plane aware and
which is using that atomic IOCTL there's no difference between these planes
(beyong what the driver and hardware can support of course).

For compatibility with legacy userspace, only overlay planes are made
available to userspace by default. Userspace clients may set the
[`DRM_CLIENT_CAP_UNIVERSAL_PLANES`](/kernel/hardware/gpu/drm-uapi.md#c-DRM_CLIENT_CAP_UNIVERSAL_PLANES) client capability bit to indicate that they
wish to receive a universal plane list containing all plane types. See also
[`drm_for_each_legacy_plane()`](#c-drm_for_each_legacy_plane).

In addition to setting each plane's type, drivers need to setup the
[`drm_crtc.primary`](#c-struct-drm_crtc) and optionally [`drm_crtc.cursor`](#c-struct-drm_crtc) pointers for legacy
IOCTLs. See [`drm_crtc_init_with_planes()`](#c-drm_crtc_init_with_planes).

WARNING: The values of this enum is UABI since they're exposed in the "type"
property.

#### <a id="c-struct-drm_plane"></a>`struct drm_plane`

central DRM plane control structure

**Definition**

```c
struct drm_plane {
    struct drm_device *dev;
    struct list_head head;
    char *name;
    struct drm_modeset_lock mutex;
    struct drm_mode_object base;
    uint32_t possible_crtcs;
    uint32_t *format_types;
    unsigned int format_count;
    bool format_default;
    uint64_t *modifiers;
    unsigned int modifier_count;
    struct drm_crtc *crtc;
    struct drm_framebuffer *fb;
    struct drm_framebuffer *old_fb;
    const struct drm_plane_funcs *funcs;
    struct drm_object_properties properties;
    enum drm_plane_type type;
    unsigned index;
    const struct drm_plane_helper_funcs *helper_private;
    struct drm_plane_state *state;
    struct drm_property *alpha_property;
    struct drm_property *zpos_property;
    struct drm_property *rotation_property;
    struct drm_property *blend_mode_property;
    struct drm_property *color_encoding_property;
    struct drm_property *color_range_property;
    struct drm_property *color_pipeline_property;
    struct drm_property *scaling_filter_property;
    struct drm_property *hotspot_x_property;
    struct drm_property *hotspot_y_property;
    struct kmsg_dumper kmsg_panic;
};
```

**Members**

- `dev`: DRM device this plane belongs to
- `head`: List of all planes on **dev**, linked from [`drm_mode_config.plane_list`](#c-struct-drm_mode_config).
  Invariant over the lifetime of **dev** and therefore does not need
  locking.
- `name`: human readable name, can be overwritten by the driver
- `mutex`: Protects modeset plane state, together with the [`drm_crtc.mutex`](#c-struct-drm_crtc) of
  CRTC this plane is linked to (when active, getting activated or
  getting disabled).

  For atomic drivers specifically this protects **state**.
- `base`: base mode object
- `possible_crtcs`: pipes this plane can be bound to constructed from
  [`drm_crtc_mask()`](#c-drm_crtc_mask)
- `format_types`: array of formats supported by this plane
- `format_count`: Size of the array pointed at by **format_types**.
- `format_default`: driver hasn't supplied supported formats for the
  plane. Used by the non-atomic driver compatibility wrapper only.
- `modifiers`: array of modifiers supported by this plane
- `modifier_count`: Size of the array pointed at by **modifier_count**.
- `crtc`: Currently bound CRTC, only meaningful for non-atomic drivers. For
  atomic drivers this is forced to be NULL, atomic drivers should
  instead check [`drm_plane_state.crtc`](#c-struct-drm_plane_state).
- `fb`: Currently bound framebuffer, only meaningful for non-atomic drivers.
  For atomic drivers this is forced to be NULL, atomic drivers should
  instead check [`drm_plane_state.fb`](#c-struct-drm_plane_state).
- `old_fb`: Temporary tracking of the old fb while a modeset is ongoing. Only
  used by non-atomic drivers, forced to be NULL for atomic drivers.
- `funcs`: plane control functions
- `properties`: property tracking for this plane
- `type`: Type of plane, see [`enum drm_plane_type`](#c-enum-drm_plane_type) for details.
- `index`: Position inside the mode_config.list, can be used as an array
  index. It is invariant over the lifetime of the plane.
- `helper_private`: mid-layer private data
- `state`: Current atomic state for this plane.

  This is protected by **mutex**. Note that nonblocking atomic commits
  access the current plane state without taking locks. Either by going
  through the [`struct drm_atomic_state`](#c-struct-drm_atomic_state) pointers, see
  [`for_each_oldnew_plane_in_state()`](#c-for_each_oldnew_plane_in_state), [`for_each_old_plane_in_state()`](#c-for_each_old_plane_in_state) and
  [`for_each_new_plane_in_state()`](#c-for_each_new_plane_in_state). Or through careful ordering of atomic
  commit operations as implemented in the atomic helpers, see
  [`struct drm_crtc_commit`](#c-struct-drm_crtc_commit).
- `alpha_property`: Optional alpha property for this plane. See
  [`drm_plane_create_alpha_property()`](#c-drm_plane_create_alpha_property).
- `zpos_property`: Optional zpos property for this plane. See
  [`drm_plane_create_zpos_property()`](#c-drm_plane_create_zpos_property).
- `rotation_property`: Optional rotation property for this plane. See
  [`drm_plane_create_rotation_property()`](#c-drm_plane_create_rotation_property).
- `blend_mode_property`: Optional "pixel blend mode" enum property for this plane.
  Blend mode property represents the alpha blending equation selection,
  describing how the pixels from the current plane are composited with
  the background.
- `color_encoding_property`: Optional "COLOR_ENCODING" enum property for specifying
  color encoding for non RGB formats.
  See [`drm_plane_create_color_properties()`](#c-drm_plane_create_color_properties).
- `color_range_property`: Optional "COLOR_RANGE" enum property for specifying
  color range for non RGB formats.
  See [`drm_plane_create_color_properties()`](#c-drm_plane_create_color_properties).
- `color_pipeline_property`: Optional "COLOR_PIPELINE" enum property for specifying
  a color pipeline to use on the plane.
- `scaling_filter_property`: property to apply a particular filter while
  scaling.
- `hotspot_x_property`: property to set mouse hotspot x offset.
- `hotspot_y_property`: property to set mouse hotspot y offset.
- `kmsg_panic`: Used to register a panic notifier for this plane

**Description**

Planes represent the scanout hardware of a display block. They receive their
input data from a [`drm_framebuffer`](#c-struct-drm_framebuffer) and feed it to a [`drm_crtc`](#c-struct-drm_crtc). Planes control
the color conversion, see `Plane Composition Properties` for more details,
and are also involved in the color conversion of input pixels, see `Color Management Properties` for details on that.

#### <a id="c-drmm_universal_plane_alloc"></a>`drmm_universal_plane_alloc()`

```c
drmm_universal_plane_alloc(dev, type, member, possible_crtcs, funcs, formats, format_count, format_modifiers, plane_type, name, ...)
```

Allocate and initialize an universal plane object

**Parameters**

- `dev`: DRM device
- `type`: the type of the struct which contains struct [`drm_plane`](#c-struct-drm_plane)
- `member`: the name of the [`drm_plane`](#c-struct-drm_plane) within **type**
- `possible_crtcs`: bitmask of possible CRTCs
- `funcs`: callbacks for the new plane
- `formats`: array of supported formats (DRM_FORMAT\_\*)
- `format_count`: number of elements in **formats**
- `format_modifiers`: array of struct drm_format modifiers terminated by
  DRM_FORMAT_MOD_INVALID
- `plane_type`: type of plane (overlay, primary, cursor)
- `name`: printf style format string for the plane name, or NULL for default name
- `...`: variable arguments

**Description**

Allocates and initializes a plane object of type **type**. Cleanup is
automatically handled through registering [`drm_plane_cleanup()`](#c-drm_plane_cleanup) with
[`drmm_add_action()`](/kernel/hardware/gpu/drm-internals.md#c-drmm_add_action).

The **drm_plane_funcs.destroy** hook must be NULL.

Drivers that only support the DRM_FORMAT_MOD_LINEAR modifier support may set
**format_modifiers** to NULL. The plane will advertise the linear modifier.

**Return**

Pointer to new plane, or ERR_PTR on failure.

#### <a id="c-drm_universal_plane_alloc"></a>`drm_universal_plane_alloc()`

```c
drm_universal_plane_alloc(dev, type, member, possible_crtcs, funcs, formats, format_count, format_modifiers, plane_type, name, ...)
```

Allocate and initialize an universal plane object

**Parameters**

- `dev`: DRM device
- `type`: the type of the struct which contains struct [`drm_plane`](#c-struct-drm_plane)
- `member`: the name of the [`drm_plane`](#c-struct-drm_plane) within **type**
- `possible_crtcs`: bitmask of possible CRTCs
- `funcs`: callbacks for the new plane
- `formats`: array of supported formats (DRM_FORMAT\_\*)
- `format_count`: number of elements in **formats**
- `format_modifiers`: array of struct drm_format modifiers terminated by
  DRM_FORMAT_MOD_INVALID
- `plane_type`: type of plane (overlay, primary, cursor)
- `name`: printf style format string for the plane name, or NULL for default name
- `...`: variable arguments

**Description**

Allocates and initializes a plane object of type **type**. The caller
is responsible for releasing the allocated memory with [`kfree()`](/kernel/internals/core-api/mm-api.md#c-kfree).

Drivers are encouraged to use [`drmm_universal_plane_alloc()`](#c-drmm_universal_plane_alloc) instead.

Drivers that only support the DRM_FORMAT_MOD_LINEAR modifier support may set
**format_modifiers** to NULL. The plane will advertise the linear modifier.

**Return**

Pointer to new plane, or ERR_PTR on failure.

#### <a id="c-drm_plane_index"></a>`drm_plane_index()`

```c
unsigned int drm_plane_index(const struct drm_plane *plane)
```

find the index of a registered plane

**Parameters**

- `const struct drm_plane *plane`: plane to find index for

**Description**

Given a registered plane, return the index of that plane within a DRM
device's list of planes.

#### <a id="c-drm_plane_mask"></a>`drm_plane_mask()`

```c
u32 drm_plane_mask(const struct drm_plane *plane)
```

find the mask of a registered plane

**Parameters**

- `const struct drm_plane *plane`: plane to find mask for

#### <a id="c-drm_plane_find"></a>`drm_plane_find()`

```c
struct drm_plane * drm_plane_find(struct drm_device *dev, struct drm_file *file_priv, uint32_t id)
```

find a [`drm_plane`](#c-struct-drm_plane)

**Parameters**

- `struct drm_device *dev`: DRM device
- `struct drm_file *file_priv`: drm file to check for lease against.
- `uint32_t id`: plane id

**Description**

Returns the plane with **id**, NULL if it doesn't exist. Simple wrapper around
[`drm_mode_object_find()`](#c-drm_mode_object_find).

#### <a id="c-drm_for_each_plane_mask"></a>`drm_for_each_plane_mask()`

```c
drm_for_each_plane_mask(plane, dev, plane_mask)
```

iterate over planes specified by bitmask

**Parameters**

- `plane`: the loop cursor
- `dev`: the DRM device
- `plane_mask`: bitmask of plane indices

**Description**

Iterate over all planes specified by bitmask.

#### <a id="c-drm_for_each_legacy_plane"></a>`drm_for_each_legacy_plane()`

```c
drm_for_each_legacy_plane(plane, dev)
```

iterate over all planes for legacy userspace

**Parameters**

- `plane`: the loop cursor
- `dev`: the DRM device

**Description**

Iterate over all legacy planes of **dev**, excluding primary and cursor planes.
This is useful for implementing userspace apis when userspace is not
universal plane aware. See also [`enum drm_plane_type`](#c-enum-drm_plane_type).

#### <a id="c-drm_for_each_plane"></a>`drm_for_each_plane()`

```c
drm_for_each_plane(plane, dev)
```

iterate over all planes

**Parameters**

- `plane`: the loop cursor
- `dev`: the DRM device

**Description**

Iterate over all planes of **dev**, include primary and cursor planes.



#### <a id="c-drm_universal_plane_init"></a>`drm_universal_plane_init()`

```c
int drm_universal_plane_init(struct drm_device *dev, struct drm_plane *plane, uint32_t possible_crtcs, const struct drm_plane_funcs *funcs, const uint32_t *formats, unsigned int format_count, const uint64_t *format_modifiers, enum drm_plane_type type, const char *name, ...)
```

Initialize a new universal plane object

**Parameters**

- `struct drm_device *dev`: DRM device
- `struct drm_plane *plane`: plane object to init
- `uint32_t possible_crtcs`: bitmask of possible CRTCs
- `const struct drm_plane_funcs *funcs`: callbacks for the new plane
- `const uint32_t *formats`: array of supported formats (DRM_FORMAT\_\*)
- `unsigned int format_count`: number of elements in **formats**
- `const uint64_t *format_modifiers`: array of struct drm_format modifiers terminated by
  DRM_FORMAT_MOD_INVALID
- `enum drm_plane_type type`: type of plane (overlay, primary, cursor)
- `const char *name`: printf style format string for the plane name, or NULL for default name
- `...`: variable arguments

**Description**

Initializes a plane object of type **type**. The [`drm_plane_funcs.destroy`](#c-struct-drm_plane_funcs) hook
should call [`drm_plane_cleanup()`](#c-drm_plane_cleanup) and [`kfree()`](/kernel/internals/core-api/mm-api.md#c-kfree) the plane structure. The plane
structure should not be allocated with `devm_kzalloc()`.

**Note**

consider using [`drmm_universal_plane_alloc()`](#c-drmm_universal_plane_alloc) instead of
[`drm_universal_plane_init()`](#c-drm_universal_plane_init) to let the DRM managed resource infrastructure
take care of cleanup and deallocation.

Drivers that only support the DRM_FORMAT_MOD_LINEAR modifier support may set
**format_modifiers** to NULL. The plane will advertise the linear modifier.

**Return**

Zero on success, error code on failure.

#### <a id="c-drm_plane_cleanup"></a>`drm_plane_cleanup()`

```c
void drm_plane_cleanup(struct drm_plane *plane)
```

Clean up the core plane usage

**Parameters**

- `struct drm_plane *plane`: plane to cleanup

**Description**

This function cleans up **plane** and removes it from the DRM mode setting
core. Note that the function does *not* free the plane structure itself,
this is the responsibility of the caller.

#### <a id="c-drm_plane_from_index"></a>`drm_plane_from_index()`

```c
struct drm_plane * drm_plane_from_index(struct drm_device *dev, int idx)
```

find the registered plane at an index

**Parameters**

- `struct drm_device *dev`: DRM device
- `int idx`: index of registered plane to find for

**Description**

Given a plane index, return the registered plane from DRM device's
list of planes with matching index. This is the inverse of [`drm_plane_index()`](#c-drm_plane_index).

#### <a id="c-drm_plane_force_disable"></a>`drm_plane_force_disable()`

```c
void drm_plane_force_disable(struct drm_plane *plane)
```

Forcibly disable a plane

**Parameters**

- `struct drm_plane *plane`: plane to disable

**Description**

Forces the plane to be disabled.

Used when the plane's current framebuffer is destroyed,
and when restoring fbdev mode.

Note that this function is not suitable for atomic drivers, since it doesn't
wire through the lock acquisition context properly and hence can't handle
retries or driver private locks. You probably want to use
[`drm_atomic_helper_disable_plane()`](/kernel/hardware/gpu/drm-kms-helpers.md#c-drm_atomic_helper_disable_plane) or
[`drm_atomic_helper_disable_planes_on_crtc()`](/kernel/hardware/gpu/drm-kms-helpers.md#c-drm_atomic_helper_disable_planes_on_crtc) instead.

#### <a id="c-drm_mode_plane_set_obj_prop"></a>`drm_mode_plane_set_obj_prop()`

```c
int drm_mode_plane_set_obj_prop(struct drm_plane *plane, struct drm_property *property, uint64_t value)
```

set the value of a property

**Parameters**

- `struct drm_plane *plane`: drm plane object to set property value for
- `struct drm_property *property`: property to set
- `uint64_t value`: value the property should be set to

**Description**

This functions sets a given property on a given plane object. This function
calls the driver's ->set_property callback and changes the software state of
the property if the callback succeeds.

**Return**

Zero on success, error code on failure.

#### <a id="c-drm_plane_has_format"></a>`drm_plane_has_format()`

```c
bool drm_plane_has_format(struct drm_plane *plane, u32 format, u64 modifier)
```

Check whether the plane supports this format and modifier combination

**Parameters**

- `struct drm_plane *plane`: drm plane
- `u32 format`: pixel format (DRM_FORMAT_*)
- `u64 modifier`: data layout modifier

**Return**

Whether the plane supports the specified format and modifier combination.

#### <a id="c-drm_any_plane_has_format"></a>`drm_any_plane_has_format()`

```c
bool drm_any_plane_has_format(struct drm_device *dev, u32 format, u64 modifier)
```

Check whether any plane supports this format and modifier combination

**Parameters**

- `struct drm_device *dev`: DRM device
- `u32 format`: pixel format (DRM_FORMAT_*)
- `u64 modifier`: data layout modifier

**Return**

Whether at least one plane supports the specified format and modifier combination.

#### <a id="c-drm_plane_enable_fb_damage_clips"></a>`drm_plane_enable_fb_damage_clips()`

```c
void drm_plane_enable_fb_damage_clips(struct drm_plane *plane)
```

Enables plane fb damage clips property.

**Parameters**

- `struct drm_plane *plane`: Plane on which to enable damage clips property.

**Description**

This function lets driver to enable the damage clips property on a plane.

#### <a id="c-drm_plane_get_damage_clips_count"></a>`drm_plane_get_damage_clips_count()`

```c
unsigned int drm_plane_get_damage_clips_count(const struct drm_plane_state *state)
```

Returns damage clips count.

**Parameters**

- `const struct drm_plane_state *state`: Plane state.

**Description**

Simple helper to get the number of [`drm_mode_rect`](/kernel/hardware/gpu/drm-uapi.md#c-struct-drm_mode_rect) clips set by user-space
during plane update.

**Return**

Number of clips in plane fb_damage_clips blob property.

#### <a id="c-drm_plane_get_damage_clips"></a>`drm_plane_get_damage_clips()`

```c
struct drm_mode_rect * drm_plane_get_damage_clips(const struct drm_plane_state *state)
```

Returns damage clips.

**Parameters**

- `const struct drm_plane_state *state`: Plane state.

**Description**

Note that this function returns uapi type [`drm_mode_rect`](/kernel/hardware/gpu/drm-uapi.md#c-struct-drm_mode_rect). Drivers might want
to use the helper functions [`drm_atomic_helper_damage_iter_init()`](#c-drm_atomic_helper_damage_iter_init) and
[`drm_atomic_helper_damage_iter_next()`](#c-drm_atomic_helper_damage_iter_next) or [`drm_atomic_helper_damage_merged()`](#c-drm_atomic_helper_damage_merged) if
the driver can only handle a single damage region at most.

**Return**

Damage clips in plane fb_damage_clips blob property.

#### <a id="c-drm_plane_create_scaling_filter_property"></a>`drm_plane_create_scaling_filter_property()`

```c
int drm_plane_create_scaling_filter_property(struct drm_plane *plane, unsigned int supported_filters)
```

create a new scaling filter property

**Parameters**

- `struct drm_plane *plane`: drm plane
- `unsigned int supported_filters`: bitmask of supported scaling filters, must include
  BIT(DRM_SCALING_FILTER_DEFAULT).

**Description**

This function lets driver to enable the scaling filter property on a given
plane.

**Return**

Zero for success or -errno

#### <a id="c-drm_plane_add_size_hints_property"></a>`drm_plane_add_size_hints_property()`

```c
int drm_plane_add_size_hints_property(struct drm_plane *plane, const struct drm_plane_size_hint *hints, int num_hints)
```

create a size hints property

**Parameters**

- `struct drm_plane *plane`: drm plane
- `const struct drm_plane_size_hint *hints`: size hints
- `int num_hints`: number of size hints

**Description**

Create a size hints property for the plane.

**Return**

Zero for success or -errno

#### <a id="c-drm_plane_create_color_pipeline_property"></a>`drm_plane_create_color_pipeline_property()`

```c
int drm_plane_create_color_pipeline_property(struct drm_plane *plane, const struct drm_prop_enum_list *pipelines, int num_pipelines)
```

create a new color pipeline property

**Parameters**

- `struct drm_plane *plane`: drm plane
- `const struct drm_prop_enum_list *pipelines`: list of pipelines
- `int num_pipelines`: number of pipelines

**Description**

Create the COLOR_PIPELINE plane property to specific color pipelines on
the plane.

**Return**

Zero for success or -errno


<a id="rst-plane-composition-functions-reference"></a>

### Plane Composition Functions Reference


#### <a id="c-drm_plane_create_alpha_property"></a>`drm_plane_create_alpha_property()`

```c
int drm_plane_create_alpha_property(struct drm_plane *plane)
```

create a new alpha property

**Parameters**

- `struct drm_plane *plane`: drm plane

**Description**

This function creates a generic, mutable, alpha property and enables support
for it in the DRM core. It is attached to **plane**.

The alpha property will be allowed to be within the bounds of 0
(transparent) to 0xffff (opaque).

**Return**

0 on success, negative error code on failure.

#### <a id="c-drm_plane_create_rotation_property"></a>`drm_plane_create_rotation_property()`

```c
int drm_plane_create_rotation_property(struct drm_plane *plane, unsigned int rotation, unsigned int supported_rotations)
```

create a new rotation property

**Parameters**

- `struct drm_plane *plane`: drm plane
- `unsigned int rotation`: initial value of the rotation property
- `unsigned int supported_rotations`: bitmask of supported rotations and reflections

**Description**

This creates a new property with the selected support for transformations.

Since a rotation by 180° degress is the same as reflecting both along the x
and the y axis the rotation property is somewhat redundant. Drivers can use
[`drm_rotation_simplify()`](#c-drm_rotation_simplify) to normalize values of this property.

The property exposed to userspace is a bitmask property (see
[`drm_property_create_bitmask()`](#c-drm_property_create_bitmask)) called "rotation" and has the following
bitmask enumaration values:

- DRM_MODE_ROTATE_0:
  "rotate-0"
- DRM_MODE_ROTATE_90:
  "rotate-90"
- DRM_MODE_ROTATE_180:
  "rotate-180"
- DRM_MODE_ROTATE_270:
  "rotate-270"
- DRM_MODE_REFLECT_X:
  "reflect-x"
- DRM_MODE_REFLECT_Y:
  "reflect-y"

Rotation is the specified amount in degrees in counter clockwise direction,
the X and Y axis are within the source rectangle, i.e.  the X/Y axis before
rotation. After reflection, the rotation is applied to the image sampled from
the source rectangle, before scaling it to fit the destination rectangle.

#### <a id="c-drm_rotation_simplify"></a>`drm_rotation_simplify()`

```c
unsigned int drm_rotation_simplify(unsigned int rotation, unsigned int supported_rotations)
```

Try to simplify the rotation

**Parameters**

- `unsigned int rotation`: Rotation to be simplified
- `unsigned int supported_rotations`: Supported rotations

**Description**

Attempt to simplify the rotation to a form that is supported.
Eg. if the hardware supports everything except DRM_MODE_REFLECT_X
one could call this function like this:

- drm_rotation_simplify(rotation, DRM_MODE_ROTATE_0 |

  DRM_MODE_ROTATE_90 | DRM_MODE_ROTATE_180 |
  DRM_MODE_ROTATE_270 | DRM_MODE_REFLECT_Y);

to eliminate the DRM_MODE_REFLECT_X flag. Depending on what kind of
transforms the hardware supports, this function may not
be able to produce a supported transform, so the caller should
check the result afterwards.

#### <a id="c-drm_plane_create_zpos_property"></a>`drm_plane_create_zpos_property()`

```c
int drm_plane_create_zpos_property(struct drm_plane *plane, unsigned int zpos, unsigned int min, unsigned int max)
```

create mutable zpos property

**Parameters**

- `struct drm_plane *plane`: drm plane
- `unsigned int zpos`: initial value of zpos property
- `unsigned int min`: minimal possible value of zpos property
- `unsigned int max`: maximal possible value of zpos property

**Description**

This function initializes generic mutable zpos property and enables support
for it in drm core. Drivers can then attach this property to planes to enable
support for configurable planes arrangement during blending operation.
Drivers that attach a mutable zpos property to any plane should call the
[`drm_atomic_normalize_zpos()`](#c-drm_atomic_normalize_zpos) helper during their implementation of
[`drm_mode_config_funcs.atomic_check()`](#c-struct-drm_mode_config_funcs), which will update the normalized zpos
values and store them in [`drm_plane_state.normalized_zpos`](#c-struct-drm_plane_state). Usually min
should be set to 0 and max to maximal number of planes for given crtc - 1.

If zpos of some planes cannot be changed (like fixed background or
cursor/topmost planes), drivers shall adjust the min/max values and assign
those planes immutable zpos properties with lower or higher values (for more
information, see [`drm_plane_create_zpos_immutable_property()`](#c-drm_plane_create_zpos_immutable_property) function). In such
case drivers shall also assign proper initial zpos values for all planes in
its `plane_reset()` callback, so the planes will be always sorted properly.

See also [`drm_atomic_normalize_zpos()`](#c-drm_atomic_normalize_zpos).

The property exposed to userspace is called "zpos".

**Return**

Zero on success, negative errno on failure.

#### <a id="c-drm_plane_create_zpos_immutable_property"></a>`drm_plane_create_zpos_immutable_property()`

```c
int drm_plane_create_zpos_immutable_property(struct drm_plane *plane, unsigned int zpos)
```

create immuttable zpos property

**Parameters**

- `struct drm_plane *plane`: drm plane
- `unsigned int zpos`: value of zpos property

**Description**

This function initializes generic immutable zpos property and enables
support for it in drm core. Using this property driver lets userspace
to get the arrangement of the planes for blending operation and notifies
it that the hardware (or driver) doesn't support changing of the planes'
order. For mutable zpos see [`drm_plane_create_zpos_property()`](#c-drm_plane_create_zpos_property).

The property exposed to userspace is called "zpos".

**Return**

Zero on success, negative errno on failure.

#### <a id="c-drm_atomic_normalize_zpos"></a>`drm_atomic_normalize_zpos()`

```c
int drm_atomic_normalize_zpos(struct drm_device *dev, struct drm_atomic_state *state)
```

calculate normalized zpos values for all crtcs

**Parameters**

- `struct drm_device *dev`: DRM device
- `struct drm_atomic_state *state`: atomic state of DRM device

**Description**

This function calculates normalized zpos value for all modified planes in
the provided atomic state of DRM device.

For every CRTC this function checks new states of all planes assigned to
it and calculates normalized zpos value for these planes. Planes are compared
first by their zpos values, then by plane id (if zpos is equal). The plane
with lowest zpos value is at the bottom. The [`drm_plane_state.normalized_zpos`](#c-struct-drm_plane_state)
is then filled with unique values from 0 to number of active planes in crtc
minus one.

RETURNS
Zero for success or -errno

#### <a id="c-drm_plane_create_blend_mode_property"></a>`drm_plane_create_blend_mode_property()`

```c
int drm_plane_create_blend_mode_property(struct drm_plane *plane, unsigned int supported_modes)
```

create a new blend mode property

**Parameters**

- `struct drm_plane *plane`: drm plane
- `unsigned int supported_modes`: bitmask of supported modes, must include
  BIT(DRM_MODE_BLEND_PREMULTI). Current DRM assumption is
  that alpha is premultiplied, and old userspace can break if
  the property defaults to anything else.

**Description**

This creates a new property describing the blend mode.

The property exposed to userspace is an enumeration property (see
[`drm_property_create_enum()`](#c-drm_property_create_enum)) called "pixel blend mode" and has the
following enumeration values:

- "None":
  Blend formula that ignores the pixel alpha.

- "Pre-multiplied":
  Blend formula that assumes the pixel color values have been already
  pre-multiplied with the alpha channel values.

- "Coverage":
  Blend formula that assumes the pixel color values have not been
  pre-multiplied and will do so when blending them to the background color
  values.

**Return**

Zero for success or -errno


<a id="rst-plane-damage-tracking-functions-reference"></a>

### Plane Damage Tracking Functions Reference


#### <a id="c-drm_atomic_helper_check_plane_damage"></a>`drm_atomic_helper_check_plane_damage()`

```c
void drm_atomic_helper_check_plane_damage(struct drm_atomic_state *state, struct drm_plane_state *plane_state)
```

Verify plane damage on atomic_check.

**Parameters**

- `struct drm_atomic_state *state`: The driver state object.
- `struct drm_plane_state *plane_state`: Plane state for which to verify damage.

**Description**

This helper function makes sure that damage from plane state is discarded
for full modeset. If there are more reasons a driver would want to do a full
plane update rather than processing individual damage regions, then those
cases should be taken care of here.

Note that [`drm_plane_state.fb_damage_clips`](#c-struct-drm_plane_state) == NULL in plane state means that
full plane update should happen. It also ensure helper iterator will return
[`drm_plane_state.src`](#c-struct-drm_plane_state) as damage.

#### <a id="c-drm_atomic_helper_dirtyfb"></a>`drm_atomic_helper_dirtyfb()`

```c
int drm_atomic_helper_dirtyfb(struct drm_framebuffer *fb, struct drm_file *file_priv, unsigned int flags, unsigned int color, struct drm_clip_rect *clips, unsigned int num_clips)
```

Helper for dirtyfb.

**Parameters**

- `struct drm_framebuffer *fb`: DRM framebuffer.
- `struct drm_file *file_priv`: Drm file for the ioctl call.
- `unsigned int flags`: Dirty fb annotate flags.
- `unsigned int color`: Color for annotate fill.
- `struct drm_clip_rect *clips`: Dirty region.
- `unsigned int num_clips`: Count of clip in clips.

**Description**

A helper to implement [`drm_framebuffer_funcs.dirty`](#c-struct-drm_framebuffer_funcs) using damage interface
during plane update. If num_clips is 0 then this helper will do a full plane
update. This is the same behaviour expected by DIRTFB IOCTL.

Note that this helper is blocking implementation. This is what current
drivers and userspace expect in their DIRTYFB IOCTL implementation, as a way
to rate-limit userspace and make sure its rendering doesn't get ahead of
uploading new data too much.

**Return**

Zero on success, negative errno on failure.

#### <a id="c-drm_atomic_helper_damage_iter_init"></a>`drm_atomic_helper_damage_iter_init()`

```c
void drm_atomic_helper_damage_iter_init(struct drm_atomic_helper_damage_iter *iter, const struct drm_plane_state *old_state, const struct drm_plane_state *state)
```

Initialize the damage iterator.

**Parameters**

- `struct drm_atomic_helper_damage_iter *iter`: The iterator to initialize.
- `const struct drm_plane_state *old_state`: Old plane state for validation.
- `const struct drm_plane_state *state`: Plane state from which to iterate the damage clips.

**Description**

Initialize an iterator, which clips plane damage
[`drm_plane_state.fb_damage_clips`](#c-struct-drm_plane_state) to plane [`drm_plane_state.src`](#c-struct-drm_plane_state). This iterator
returns full plane src in case damage is not present because either
user-space didn't sent or driver discarded it (it want to do full plane
update). Currently this iterator returns full plane src in case plane src
changed but that can be changed in future to return damage.

For the case when plane is not visible or plane update should not happen the
first call to iter_next will return false. Note that this helper use clipped
[`drm_plane_state.src`](#c-struct-drm_plane_state), so driver calling this helper should have called
[`drm_atomic_helper_check_plane_state()`](/kernel/hardware/gpu/drm-kms-helpers.md#c-drm_atomic_helper_check_plane_state) earlier.

#### <a id="c-drm_atomic_helper_damage_iter_next"></a>`drm_atomic_helper_damage_iter_next()`

```c
bool drm_atomic_helper_damage_iter_next(struct drm_atomic_helper_damage_iter *iter, struct drm_rect *rect)
```

Advance the damage iterator.

**Parameters**

- `struct drm_atomic_helper_damage_iter *iter`: The iterator to advance.
- `struct drm_rect *rect`: Return a rectangle in fb coordinate clipped to plane src.

**Description**

Since plane src is in 16.16 fixed point and damage clips are whole number,
this iterator round off clips that intersect with plane src. Round down for
x1/y1 and round up for x2/y2 for the intersected coordinate. Similar rounding
off for full plane src, in case it's returned as damage. This iterator will
skip damage clips outside of plane src.

If the first call to iterator next returns false then it means no need to
update the plane.

**Return**

True if the output is valid, false if reached the end.

#### <a id="c-drm_atomic_helper_damage_merged"></a>`drm_atomic_helper_damage_merged()`

```c
bool drm_atomic_helper_damage_merged(const struct drm_plane_state *old_state, const struct drm_plane_state *state, struct drm_rect *rect)
```

Merged plane damage

**Parameters**

- `const struct drm_plane_state *old_state`: Old plane state for validation.
- `const struct drm_plane_state *state`: Plane state from which to iterate the damage clips.
- `struct drm_rect *rect`: Returns the merged damage rectangle

**Description**

This function merges any valid plane damage clips into one rectangle and
returns it in **rect**.

For details see: [`drm_atomic_helper_damage_iter_init()`](#c-drm_atomic_helper_damage_iter_init) and
[`drm_atomic_helper_damage_iter_next()`](#c-drm_atomic_helper_damage_iter_next).

**Return**

True if there is valid plane damage otherwise false.



#### <a id="c-drm_atomic_for_each_plane_damage"></a>`drm_atomic_for_each_plane_damage()`

```c
drm_atomic_for_each_plane_damage(iter, rect)
```

Iterator macro for plane damage.

**Parameters**

- `iter`: The iterator to advance.
- `rect`: Return a rectangle in fb coordinate clipped to plane src.

**Description**

Note that if the first call to iterator macro return false then no need to do
plane update. Iterator will return full plane src when damage is not passed
by user-space.

#### <a id="c-struct-drm_atomic_helper_damage_iter"></a>`struct drm_atomic_helper_damage_iter`

Closure structure for damage iterator.

**Definition**

```c
struct drm_atomic_helper_damage_iter {
};
```

**Description**

This structure tracks state needed to walk the list of plane damage clips.


<a id="rst-plane-panic-feature"></a>

### Plane Panic Feature


To enable DRM panic for a driver, the primary plane must implement a
[`drm_plane_helper_funcs.get_scanout_buffer`](/kernel/hardware/gpu/drm-kms-helpers.md#c-struct-drm_plane_helper_funcs) helper function. It is then
automatically registered to the drm panic handler.
When a panic occurs, the [`drm_plane_helper_funcs.get_scanout_buffer`](/kernel/hardware/gpu/drm-kms-helpers.md#c-struct-drm_plane_helper_funcs) will be
called, and the driver can provide a framebuffer so the panic handler can
draw the panic screen on it. Currently only linear buffer and a few color
formats are supported.
Optionally the driver can also provide a [`drm_plane_helper_funcs.panic_flush`](/kernel/hardware/gpu/drm-kms-helpers.md#c-struct-drm_plane_helper_funcs)
callback, that will be called after that, to send additional commands to the
hardware to make the scanout buffer visible.


<a id="rst-plane-panic-functions-reference"></a>

### Plane Panic Functions Reference


#### <a id="c-struct-drm_scanout_buffer"></a>`struct drm_scanout_buffer`

DRM scanout buffer

**Definition**

```c
struct drm_scanout_buffer {
    const struct drm_format_info *format;
    struct iosys_map map[DRM_FORMAT_MAX_PLANES];
    struct page **pages;
    unsigned int width;
    unsigned int height;
    unsigned int pitch[DRM_FORMAT_MAX_PLANES];
    void (*set_pixel)(struct drm_scanout_buffer *sb, unsigned int x, unsigned int y, u32 color);
    void *private;
};
```

**Members**

- `format`: drm format of the scanout buffer.
- `map`: Virtual address of the scanout buffer, either in memory or iomem.
  The scanout buffer should be in linear format, and can be directly
  sent to the display hardware. Tearing is not an issue for the panic
  screen.
- `pages`: Optional, if the scanout buffer is not mapped, set this field
  to the array of pages of the scanout buffer. The panic code will use
  `kmap_local_page_try_from_panic()` to map one page at a time to write
  all the pixels. This array shouldn't be allocated from the
  `get_scanoutbuffer()` callback.
  The scanout buffer should be in linear format.
- `width`: Width of the scanout buffer, in pixels.
- `height`: Height of the scanout buffer, in pixels.
- `pitch`: Length in bytes between the start of two consecutive lines.
- `set_pixel`: Optional function, to set a pixel color on the
  framebuffer. It allows to handle special tiling format inside the
  driver. It takes precedence over the **map** and **pages** fields.
- `private`: private pointer that you can use in the callbacks
  `set_pixel()`

**Description**

This structure holds the information necessary for drm_panic to draw the
panic screen, and display it.

#### <a id="c-drm_panic_trylock"></a>`drm_panic_trylock()`

```c
drm_panic_trylock(dev, flags)
```

try to enter the panic printing critical section

**Parameters**

- `dev`: struct drm_device
- `flags`: unsigned long irq flags you need to pass to the `unlock()` counterpart

**Description**

This function must be called by any panic printing code. The panic printing
attempt must be aborted if the trylock fails.

Panic printing code can make the following assumptions while holding the
panic lock:

- Anything protected by [`drm_panic_lock()`](#c-drm_panic_lock) and [`drm_panic_unlock()`](#c-drm_panic_unlock) pairs is safe
  to access.

- Furthermore the panic printing code only registers in [`drm_dev_unregister()`](/kernel/hardware/gpu/drm-internals.md#c-drm_dev_unregister)
  and gets removed in [`drm_dev_unregister()`](/kernel/hardware/gpu/drm-internals.md#c-drm_dev_unregister). This allows the panic code to
  safely access any state which is invariant in between these two function
  calls, like the list of planes [`drm_mode_config.plane_list`](#c-struct-drm_mode_config) or most of the
  struct drm_plane structure.

Specifically thanks to the protection around plane updates in
[`drm_atomic_helper_swap_state()`](/kernel/hardware/gpu/drm-kms-helpers.md#c-drm_atomic_helper_swap_state) the following additional guarantees hold:

- It is safe to deference the drm_plane.state pointer.

- Anything in struct drm_plane_state or the driver's subclass thereof which
  stays invariant after the atomic check code has finished is safe to access.
  Specifically this includes the reference counted pointers to framebuffer
  and buffer objects.

- Anything set up by [`drm_plane_helper_funcs.fb_prepare`](/kernel/hardware/gpu/drm-kms-helpers.md#c-struct-drm_plane_helper_funcs) and cleaned up
  [`drm_plane_helper_funcs.fb_cleanup`](/kernel/hardware/gpu/drm-kms-helpers.md#c-struct-drm_plane_helper_funcs) is safe to access, as long as it stays
  invariant between these two calls. This also means that for drivers using
  dynamic buffer management the framebuffer is pinned, and therefer all
  relevant datastructures can be accessed without taking any further locks
  (which would be impossible in panic context anyway).

- Importantly, software and hardware state set up by
  [`drm_plane_helper_funcs.begin_fb_access`](/kernel/hardware/gpu/drm-kms-helpers.md#c-struct-drm_plane_helper_funcs) and
  [`drm_plane_helper_funcs.end_fb_access`](/kernel/hardware/gpu/drm-kms-helpers.md#c-struct-drm_plane_helper_funcs) is not safe to access.

Drivers must not make any assumptions about the actual state of the hardware,
unless they explicitly protected these hardware access with [`drm_panic_lock()`](#c-drm_panic_lock)
and [`drm_panic_unlock()`](#c-drm_panic_unlock).

**Return**

`0` when failing to acquire the raw spinlock, nonzero on success.

#### <a id="c-drm_panic_lock"></a>`drm_panic_lock()`

```c
drm_panic_lock(dev, flags)
```

protect panic printing relevant state

**Parameters**

- `dev`: struct drm_device
- `flags`: unsigned long irq flags you need to pass to the `unlock()` counterpart

**Description**

This function must be called to protect software and hardware state that the
panic printing code must be able to rely on. The protected sections must be
as small as possible. It uses the irqsave/irqrestore variant, and can be
called from irq handler. Examples include:

- Access to peek/poke or other similar registers, if that is the way the
  driver prints the pixels into the scanout buffer at panic time.

- Updates to pointers like [`drm_plane.state`](#c-struct-drm_plane), allowing the panic handler to
  safely deference these. This is done in [`drm_atomic_helper_swap_state()`](/kernel/hardware/gpu/drm-kms-helpers.md#c-drm_atomic_helper_swap_state).

- An state that isn't invariant and that the driver must be able to access
  during panic printing.

#### <a id="c-drm_panic_unlock"></a>`drm_panic_unlock()`

```c
drm_panic_unlock(dev, flags)
```

end of the panic printing critical section

**Parameters**

- `dev`: struct drm_device
- `flags`: irq flags that were returned when acquiring the lock

**Description**

Unlocks the raw spinlock acquired by either [`drm_panic_lock()`](#c-drm_panic_lock) or
[`drm_panic_trylock()`](#c-drm_panic_trylock).



#### <a id="c-drm_panic_is_enabled"></a>`drm_panic_is_enabled()`

```c
bool drm_panic_is_enabled(struct drm_device *dev)
```

**Parameters**

- `struct drm_device *dev`: the drm device that may supports drm_panic

**Description**

returns true if the drm device supports drm_panic


<a id="rst-colorop-abstraction"></a>

## Colorop Abstraction


When userspace signals the [`DRM_CLIENT_CAP_PLANE_COLOR_PIPELINE`](/kernel/hardware/gpu/drm-uapi.md#c-DRM_CLIENT_CAP_PLANE_COLOR_PIPELINE) it
should use the COLOR_PIPELINE plane property and associated colorops
for any color operation on the [`drm_plane`](#c-struct-drm_plane). Setting of all old color
properties, such as COLOR_ENCODING and COLOR_RANGE, will be rejected
and the values of the properties will be ignored.

Colorops are only advertised and valid for atomic drivers and atomic
userspace that signals the [`DRM_CLIENT_CAP_PLANE_COLOR_PIPELINE`](/kernel/hardware/gpu/drm-uapi.md#c-DRM_CLIENT_CAP_PLANE_COLOR_PIPELINE)
client cap.

A colorop represents a single color operation. Colorops are chained
via the NEXT property and make up color pipelines. Color pipelines
are advertised and selected via the COLOR_PIPELINE [`drm_plane`](#c-struct-drm_plane)
property.

A colorop will be of a certain type, advertised by the read-only TYPE
property. Each type of colorop will advertise a different set of
properties and is programmed in a different manner. Types can be
enumerated 1D curves, 1D LUTs, 3D LUTs, matrices, etc. See the
[`drm_colorop_type`](/kernel/hardware/gpu/drm-uapi.md#c-enum-drm_colorop_type) documentation for information on each type.

If a colorop advertises the BYPASS property it can be bypassed.

Information about colorop and color pipeline design decisions can be
found at rfc/color_pipeline.rst, but note that this document will
grow stale over time.


<a id="rst-colorop-functions-reference"></a>

### Colorop Functions Reference


#### <a id="c-enum-drm_colorop_curve_1d_type"></a>`enum drm_colorop_curve_1d_type`

type of 1D curve

**Constants**

- `DRM_COLOROP_1D_CURVE_SRGB_EOTF`: enum string "sRGB EOTF"

  sRGB piece-wise electro-optical transfer function. Transfer
  characteristics as defined by IEC 61966-2-1 sRGB. Equivalent
  to H.273 TransferCharacteristics code point 13 with
  MatrixCoefficients set to 0.
- `DRM_COLOROP_1D_CURVE_SRGB_INV_EOTF`: enum string "sRGB Inverse EOTF"

  The inverse of `DRM_COLOROP_1D_CURVE_SRGB_EOTF`
- `DRM_COLOROP_1D_CURVE_PQ_125_EOTF`: enum string "PQ 125 EOTF"

  The PQ transfer function, scaled by 125.0f, so that 10,000
  nits correspond to 125.0f.

  Transfer characteristics of the PQ function as defined by
  SMPTE ST 2084 (2014) for 10-, 12-, 14-, and 16-bit systems
  and Rec. ITU-R BT.2100-2 perceptual quantization (PQ) system,
  represented by H.273 TransferCharacteristics code point 16.
- `DRM_COLOROP_1D_CURVE_PQ_125_INV_EOTF`: enum string "PQ 125 Inverse EOTF"

  The inverse of DRM_COLOROP_1D_CURVE_PQ_125_EOTF.
- `DRM_COLOROP_1D_CURVE_BT2020_INV_OETF`: enum string "BT.2020 Inverse OETF"

  The inverse of `DRM_COLOROP_1D_CURVE_BT2020_OETF`
- `DRM_COLOROP_1D_CURVE_BT2020_OETF`: enum string "BT.2020 OETF"

  The BT.2020/BT.709 transfer function. The BT.709 and BT.2020
  transfer functions are the same, the only difference is that
  BT.2020 is defined with more precision for 10 and 12-bit
  encodings.
- `DRM_COLOROP_1D_CURVE_GAMMA22`: enum string "Gamma 2.2"

  A gamma 2.2 power function. This applies a power curve with
  gamma value of 2.2 to the input values.
- `DRM_COLOROP_1D_CURVE_GAMMA22_INV`: enum string "Gamma 2.2 Inverse"

  The inverse of `DRM_COLOROP_1D_CURVE_GAMMA22`
- `DRM_COLOROP_1D_CURVE_COUNT`: enum value denoting the size of the enum

**Description**

Describes a 1D curve to be applied by the DRM_COLOROP_1D_CURVE colorop.

#### <a id="c-struct-drm_colorop_state"></a>`struct drm_colorop_state`

mutable colorop state

**Definition**

```c
struct drm_colorop_state {
    struct drm_colorop *colorop;
    bool bypass;
    enum drm_colorop_curve_1d_type curve_1d_type;
    uint64_t multiplier;
    struct drm_property_blob *data;
    struct drm_atomic_state *state;
};
```

**Members**

- `colorop`: backpointer to the colorop
- `bypass`: When the property BYPASS exists on this colorop, this stores
  the requested bypass state: true if colorop shall be bypassed,
  false if colorop is enabled.
- `curve_1d_type`: Type of 1D curve.
- `multiplier`: Multiplier to 'gain' the plane. Format is S31.32 sign-magnitude.
- `data`: Data blob for any TYPE that requires such a blob. The
  interpretation of the blob is TYPE-specific.

  See the [`drm_colorop_type`](/kernel/hardware/gpu/drm-uapi.md#c-enum-drm_colorop_type) documentation for how blob is laid
  out.
- `state`: backpointer to global drm_atomic_state

#### <a id="c-struct-drm_colorop"></a>`struct drm_colorop`

DRM color operation control structure

**Definition**

```c
struct drm_colorop {
    struct drm_device *dev;
    struct list_head head;
    unsigned int index;
    struct drm_mode_object base;
    struct drm_plane *plane;
    struct drm_colorop_state *state;
    struct drm_object_properties properties;
    enum drm_colorop_type type;
    struct drm_colorop *next;
    struct drm_property *type_property;
    struct drm_property *bypass_property;
    uint32_t size;
    enum drm_colorop_lut1d_interpolation_type lut1d_interpolation;
    enum drm_colorop_lut3d_interpolation_type lut3d_interpolation;
    struct drm_property *lut1d_interpolation_property;
    struct drm_property *curve_1d_type_property;
    struct drm_property *multiplier_property;
    struct drm_property *size_property;
    struct drm_property *lut3d_interpolation_property;
    struct drm_property *data_property;
    struct drm_property *next_property;
};
```

**Members**

- `dev`: parent DRM device
- `head`: List of all colorops on **dev**, linked from [`drm_mode_config.colorop_list`](#c-struct-drm_mode_config).
  Invariant over the lifetime of **dev** and therefore does not need
  locking.
- `index`: Position inside the mode_config.list, can be used as an array
  index. It is invariant over the lifetime of the colorop.
- `base`: base mode object
- `plane`: The plane on which the colorop sits. A drm_colorop is always unique
  to a plane.
- `state`: Current atomic state for this colorop.

  This is protected by **mutex**. Note that nonblocking atomic commits
  access the current colorop state without taking locks.
- `properties`: property tracking for this colorop
- `type`: Read-only
  Type of color operation
- `next`: Read-only
  Pointer to next drm_colorop in pipeline
- `type_property`: Read-only "TYPE" property for specifying the type of
  this color operation. The type is enum drm_colorop_type.
- `bypass_property`: Boolean property to control enablement of the color
  operation. Only present if DRM_COLOROP_FLAG_ALLOW_BYPASS
  flag is set. When present, setting bypass to "true" shall
  always be supported to allow compositors to quickly fall
  back to alternate methods of color processing. This is
  important since setting color operations can fail due to
  unique HW constraints.
- `size`: Number of entries of the custom LUT. This should be read-only.
- `lut1d_interpolation`: Read-only
  Interpolation for DRM_COLOROP_1D_LUT
- `lut3d_interpolation`: Read-only
  Interpolation for DRM_COLOROP_3D_LUT
- `lut1d_interpolation_property`: Read-only property for DRM_COLOROP_1D_LUT interpolation
- `curve_1d_type_property`: Sub-type for DRM_COLOROP_1D_CURVE type.
- `multiplier_property`: Multiplier property for plane gain
- `size_property`: Size property for custom LUT from userspace.
- `lut3d_interpolation_property`: Read-only property for DRM_COLOROP_3D_LUT interpolation
- `data_property`: blob property for any TYPE that requires a blob of data,
  such as 1DLUT, CTM, 3DLUT, etc.

  The way this blob is interpreted depends on the TYPE of
  this
- `next_property`: Read-only property to next colorop in the pipeline

**Description**

A colorop represents one color operation. They can be chained via
the 'next' pointer to build a color pipeline.

Since colorops cannot stand-alone and are used to describe colorop
operations on a plane they don't have their own locking mechanism but
are locked and programmed along with their associated [`drm_plane`](#c-struct-drm_plane).

#### <a id="c-drm_colorop_find"></a>`drm_colorop_find()`

```c
struct drm_colorop * drm_colorop_find(struct drm_device *dev, struct drm_file *file_priv, uint32_t id)
```

look up a Colorop object from its ID

**Parameters**

- `struct drm_device *dev`: DRM device
- `struct drm_file *file_priv`: drm file to check for lease against.
- `uint32_t id`: [`drm_mode_object`](#c-struct-drm_mode_object) ID

**Description**

This can be used to look up a Colorop from its userspace ID. Only used by
drivers for legacy IOCTLs and interface, nowadays extensions to the KMS
userspace interface should be done using [`drm_property`](#c-struct-drm_property).

#### <a id="c-drm_colorop_reset"></a>`drm_colorop_reset()`

```c
void drm_colorop_reset(struct drm_colorop *colorop)
```

reset colorop atomic state

**Parameters**

- `struct drm_colorop *colorop`: drm colorop

**Description**

Resets the atomic state for **colorop** by freeing the state pointer (which might
be NULL, e.g. at driver load time) and allocating a new empty state object.

#### <a id="c-drm_colorop_index"></a>`drm_colorop_index()`

```c
unsigned int drm_colorop_index(const struct drm_colorop *colorop)
```

find the index of a registered colorop

**Parameters**

- `const struct drm_colorop *colorop`: colorop to find index for

**Description**

Given a registered colorop, return the index of that colorop within a DRM
device's list of colorops.

#### <a id="c-drm_get_colorop_type_name"></a>`drm_get_colorop_type_name()`

```c
const char * drm_get_colorop_type_name(enum drm_colorop_type type)
```

return a string for colorop type

**Parameters**

- `enum drm_colorop_type type`: colorop type to compute name of

**Description**

In contrast to the other drm_get_*_name functions this one here returns a
const pointer and hence is threadsafe.

#### <a id="c-drm_get_colorop_curve_1d_type_name"></a>`drm_get_colorop_curve_1d_type_name()`

```c
const char * drm_get_colorop_curve_1d_type_name(enum drm_colorop_curve_1d_type type)
```

return a string for 1D curve type

**Parameters**

- `enum drm_colorop_curve_1d_type type`: 1d curve type to compute name of

**Description**

In contrast to the other drm_get_*_name functions this one here returns a
const pointer and hence is threadsafe.



#### <a id="c-drm_colorop_cleanup"></a>`drm_colorop_cleanup()`

```c
void drm_colorop_cleanup(struct drm_colorop *colorop)
```

Cleanup a drm_colorop object in color_pipeline

**Parameters**

- `struct drm_colorop *colorop`: The drm_colorop object to be cleaned

#### <a id="c-drm_colorop_pipeline_destroy"></a>`drm_colorop_pipeline_destroy()`

```c
void drm_colorop_pipeline_destroy(struct drm_device *dev)
```

Helper for color pipeline destruction

**Parameters**

- `struct drm_device *dev`:

  - The drm_device containing the drm_planes with the color_pipelines

**Description**

Provides a default color pipeline destroy handler for drm_device.

#### <a id="c-drm_plane_colorop_curve_1d_init"></a>`drm_plane_colorop_curve_1d_init()`

```c
int drm_plane_colorop_curve_1d_init(struct drm_device *dev, struct drm_colorop *colorop, struct drm_plane *plane, u64 supported_tfs, uint32_t flags)
```

Initialize a DRM_COLOROP_1D_CURVE

**Parameters**

- `struct drm_device *dev`: DRM device
- `struct drm_colorop *colorop`: The drm_colorop object to initialize
- `struct drm_plane *plane`: The associated drm_plane
- `u64 supported_tfs`: A bitfield of supported drm_plane_colorop_curve_1d_init enum values,
  created using BIT(curve_type) and combined with the OR '|'
  operator.
- `uint32_t flags`: bitmask of misc, see DRM_COLOROP_FLAG_* defines.
  **return** zero on success, -E value on failure

#### <a id="c-drm_plane_colorop_curve_1d_lut_init"></a>`drm_plane_colorop_curve_1d_lut_init()`

```c
int drm_plane_colorop_curve_1d_lut_init(struct drm_device *dev, struct drm_colorop *colorop, struct drm_plane *plane, uint32_t lut_size, enum drm_colorop_lut1d_interpolation_type interpolation, uint32_t flags)
```

Initialize a DRM_COLOROP_1D_LUT

**Parameters**

- `struct drm_device *dev`: DRM device
- `struct drm_colorop *colorop`: The drm_colorop object to initialize
- `struct drm_plane *plane`: The associated drm_plane
- `uint32_t lut_size`: LUT size supported by driver
- `enum drm_colorop_lut1d_interpolation_type interpolation`: 1D LUT interpolation type
- `uint32_t flags`: bitmask of misc, see DRM_COLOROP_FLAG_* defines.
  **return** zero on success, -E value on failure

#### <a id="c-drm_plane_colorop_mult_init"></a>`drm_plane_colorop_mult_init()`

```c
int drm_plane_colorop_mult_init(struct drm_device *dev, struct drm_colorop *colorop, struct drm_plane *plane, uint32_t flags)
```

Initialize a DRM_COLOROP_MULTIPLIER

**Parameters**

- `struct drm_device *dev`: DRM device
- `struct drm_colorop *colorop`: The drm_colorop object to initialize
- `struct drm_plane *plane`: The associated drm_plane
- `uint32_t flags`: bitmask of misc, see DRM_COLOROP_FLAG_* defines.
  **return** zero on success, -E value on failure

#### <a id="c-drm_colorop_set_next_property"></a>`drm_colorop_set_next_property()`

```c
void drm_colorop_set_next_property(struct drm_colorop *colorop, struct drm_colorop *next)
```

sets the next pointer

**Parameters**

- `struct drm_colorop *colorop`: drm colorop
- `struct drm_colorop *next`: next colorop

**Description**

Should be used when constructing the color pipeline


<a id="rst-display-modes-function-reference"></a>

## Display Modes Function Reference


#### <a id="c-enum-drm_mode_status"></a>`enum drm_mode_status`

hardware support status of a mode

**Constants**

- `MODE_OK`: Mode OK
- `MODE_HSYNC`: hsync out of range
- `MODE_VSYNC`: vsync out of range
- `MODE_H_ILLEGAL`: mode has illegal horizontal timings
- `MODE_V_ILLEGAL`: mode has illegal vertical timings
- `MODE_BAD_WIDTH`: requires an unsupported linepitch
- `MODE_NOMODE`: no mode with a matching name
- `MODE_NO_INTERLACE`: interlaced mode not supported
- `MODE_NO_DBLESCAN`: doublescan mode not supported
- `MODE_NO_VSCAN`: multiscan mode not supported
- `MODE_MEM`: insufficient video memory
- `MODE_VIRTUAL_X`: mode width too large for specified virtual size
- `MODE_VIRTUAL_Y`: mode height too large for specified virtual size
- `MODE_MEM_VIRT`: insufficient video memory given virtual size
- `MODE_NOCLOCK`: no fixed clock available
- `MODE_CLOCK_HIGH`: clock required is too high
- `MODE_CLOCK_LOW`: clock required is too low
- `MODE_CLOCK_RANGE`: clock/mode isn't in a ClockRange
- `MODE_BAD_HVALUE`: horizontal timing was out of range
- `MODE_BAD_VVALUE`: vertical timing was out of range
- `MODE_BAD_VSCAN`: VScan value out of range
- `MODE_HSYNC_NARROW`: horizontal sync too narrow
- `MODE_HSYNC_WIDE`: horizontal sync too wide
- `MODE_HBLANK_NARROW`: horizontal blanking too narrow
- `MODE_HBLANK_WIDE`: horizontal blanking too wide
- `MODE_VSYNC_NARROW`: vertical sync too narrow
- `MODE_VSYNC_WIDE`: vertical sync too wide
- `MODE_VBLANK_NARROW`: vertical blanking too narrow
- `MODE_VBLANK_WIDE`: vertical blanking too wide
- `MODE_PANEL`: exceeds panel dimensions
- `MODE_INTERLACE_WIDTH`: width too large for interlaced mode
- `MODE_ONE_WIDTH`: only one width is supported
- `MODE_ONE_HEIGHT`: only one height is supported
- `MODE_ONE_SIZE`: only one resolution is supported
- `MODE_NO_REDUCED`: monitor doesn't accept reduced blanking
- `MODE_NO_STEREO`: stereo modes not supported
- `MODE_NO_420`: ycbcr 420 modes not supported
- `MODE_STALE`: mode has become stale
- `MODE_BAD`: unspecified reason
- `MODE_ERROR`: error condition

**Description**

This enum is used to filter out modes not supported by the driver/hardware
combination.

#### <a id="c-DRM_MODE_RES_MM"></a>`DRM_MODE_RES_MM()`

```c
DRM_MODE_RES_MM(res, dpi)
```

Calculates the display size from resolution and DPI

**Parameters**

- `res`: The resolution in pixel
- `dpi`: The number of dots per inch

#### <a id="c-DRM_MODE_INIT"></a>`DRM_MODE_INIT()`

```c
DRM_MODE_INIT(hz, hd, vd, hd_mm, vd_mm)
```

Initialize display mode

**Parameters**

- `hz`: Vertical refresh rate in Hertz
- `hd`: Horizontal resolution, width
- `vd`: Vertical resolution, height
- `hd_mm`: Display width in millimeters
- `vd_mm`: Display height in millimeters

**Description**

This macro initializes a [`drm_display_mode`](#c-struct-drm_display_mode) that contains information about
refresh rate, resolution and physical size.

#### <a id="c-DRM_SIMPLE_MODE"></a>`DRM_SIMPLE_MODE()`

```c
DRM_SIMPLE_MODE(hd, vd, hd_mm, vd_mm)
```

Simple display mode

**Parameters**

- `hd`: Horizontal resolution, width
- `vd`: Vertical resolution, height
- `hd_mm`: Display width in millimeters
- `vd_mm`: Display height in millimeters

**Description**

This macro initializes a [`drm_display_mode`](#c-struct-drm_display_mode) that only contains info about
resolution and physical size.

#### <a id="c-struct-drm_display_mode"></a>`struct drm_display_mode`

DRM kernel-internal display mode structure

**Definition**

```c
struct drm_display_mode {
    int clock;
    u16 hdisplay;
    u16 hsync_start;
    u16 hsync_end;
    u16 htotal;
    u16 hskew;
    u16 vdisplay;
    u16 vsync_start;
    u16 vsync_end;
    u16 vtotal;
    u16 vscan;
    u32 flags;
    int crtc_clock;
    u16 crtc_hdisplay;
    u16 crtc_hblank_start;
    u16 crtc_hblank_end;
    u16 crtc_hsync_start;
    u16 crtc_hsync_end;
    u16 crtc_htotal;
    u16 crtc_hskew;
    u16 crtc_vdisplay;
    u16 crtc_vblank_start;
    u16 crtc_vblank_end;
    u16 crtc_vsync_start;
    u16 crtc_vsync_end;
    u16 crtc_vtotal;
    u16 width_mm;
    u16 height_mm;
    u8 type;
    bool expose_to_userspace;
    struct list_head head;
    char name[DRM_DISPLAY_MODE_LEN];
    enum drm_mode_status status;
    enum hdmi_picture_aspect picture_aspect_ratio;
};
```

**Members**

- `clock`: Pixel clock in kHz.
- `hdisplay`: horizontal display size
- `hsync_start`: horizontal sync start
- `hsync_end`: horizontal sync end
- `htotal`: horizontal total size
- `hskew`: horizontal skew?!
- `vdisplay`: vertical display size
- `vsync_start`: vertical sync start
- `vsync_end`: vertical sync end
- `vtotal`: vertical total size
- `vscan`: vertical scan?!
- `flags`: Sync and timing flags:

  - DRM_MODE_FLAG_PHSYNC: horizontal sync is active high.
  - DRM_MODE_FLAG_NHSYNC: horizontal sync is active low.
  - DRM_MODE_FLAG_PVSYNC: vertical sync is active high.
  - DRM_MODE_FLAG_NVSYNC: vertical sync is active low.
  - DRM_MODE_FLAG_INTERLACE: mode is interlaced.
  - DRM_MODE_FLAG_DBLSCAN: mode uses doublescan.
  - DRM_MODE_FLAG_CSYNC: mode uses composite sync.
  - DRM_MODE_FLAG_PCSYNC: composite sync is active high.
  - DRM_MODE_FLAG_NCSYNC: composite sync is active low.
  - DRM_MODE_FLAG_HSKEW: hskew provided (not used?).
  - DRM_MODE_FLAG_BCAST: \<deprecated>
  - DRM_MODE_FLAG_PIXMUX: \<deprecated>
  - DRM_MODE_FLAG_DBLCLK: double-clocked mode.
  - DRM_MODE_FLAG_CLKDIV2: half-clocked mode.

  Additionally there's flags to specify how 3D modes are packed:

  - DRM_MODE_FLAG_3D_NONE: normal, non-3D mode.
  - DRM_MODE_FLAG_3D_FRAME_PACKING: 2 full frames for left and right.
  - DRM_MODE_FLAG_3D_FIELD_ALTERNATIVE: interleaved like fields.
  - DRM_MODE_FLAG_3D_LINE_ALTERNATIVE: interleaved lines.
  - DRM_MODE_FLAG_3D_SIDE_BY_SIDE_FULL: side-by-side full frames.
  - DRM_MODE_FLAG_3D_L_DEPTH: ?
  - DRM_MODE_FLAG_3D_L_DEPTH_GFX_GFX_DEPTH: ?
  - DRM_MODE_FLAG_3D_TOP_AND_BOTTOM: frame split into top and bottom
    parts.
  - DRM_MODE_FLAG_3D_SIDE_BY_SIDE_HALF: frame split into left and
    right parts.
- `crtc_clock`: Actual pixel or dot clock in the hardware. This differs from the
  logical **clock** when e.g. using interlacing, double-clocking, stereo
  modes or other fancy stuff that changes the timings and signals
  actually sent over the wire.

  This is again in kHz.

  Note that with digital outputs like HDMI or DP there's usually a
  massive confusion between the dot clock and the signal clock at the
  bit encoding level. Especially when a 8b/10b encoding is used and the
  difference is exactly a factor of 10.
- `crtc_hdisplay`: hardware mode horizontal display size
- `crtc_hblank_start`: hardware mode horizontal blank start
- `crtc_hblank_end`: hardware mode horizontal blank end
- `crtc_hsync_start`: hardware mode horizontal sync start
- `crtc_hsync_end`: hardware mode horizontal sync end
- `crtc_htotal`: hardware mode horizontal total size
- `crtc_hskew`: hardware mode horizontal skew?!
- `crtc_vdisplay`: hardware mode vertical display size
- `crtc_vblank_start`: hardware mode vertical blank start
- `crtc_vblank_end`: hardware mode vertical blank end
- `crtc_vsync_start`: hardware mode vertical sync start
- `crtc_vsync_end`: hardware mode vertical sync end
- `crtc_vtotal`: hardware mode vertical total size
- `width_mm`: Addressable size of the output in mm, projectors should set this to
  0.
- `height_mm`: Addressable size of the output in mm, projectors should set this to
  0.
- `type`: A bitmask of flags, mostly about the source of a mode. Possible flags
  are:

  - DRM_MODE_TYPE_PREFERRED: Preferred mode, usually the native
    resolution of an LCD panel. There should only be one preferred
    mode per connector at any given time.
  - DRM_MODE_TYPE_DRIVER: Mode created by the driver, which is all of
    them really. Drivers must set this bit for all modes they create
    and expose to userspace.
  - DRM_MODE_TYPE_USERDEF: Mode defined or selected via the kernel
    command line.

  Plus a big list of flags which shouldn't be used at all, but are
  still around since these flags are also used in the userspace ABI.
  We no longer accept modes with these types though:

  - DRM_MODE_TYPE_BUILTIN: Meant for hard-coded modes, unused.
    Use DRM_MODE_TYPE_DRIVER instead.
  - DRM_MODE_TYPE_DEFAULT: Again a leftover, use
    DRM_MODE_TYPE_PREFERRED instead.
  - DRM_MODE_TYPE_CLOCK_C and DRM_MODE_TYPE_CRTC_C: Define leftovers
    which are stuck around for hysterical raisins only. No one has an
    idea what they were meant for. Don't use.
- `expose_to_userspace`: Indicates whether the mode is to be exposed to the userspace.
  This is to maintain a set of exposed modes while preparing
  user-mode's list in drm_mode_getconnector ioctl. The purpose of
  this only lies in the ioctl function, and is not to be used
  outside the function.
- `head`: struct list_head for mode lists.
- `name`: Human-readable name of the mode, filled out with [`drm_mode_set_name()`](#c-drm_mode_set_name).
- `status`: Status of the mode, used to filter out modes not supported by the
  hardware. See enum [`drm_mode_status`](#c-enum-drm_mode_status).
- `picture_aspect_ratio`: Field for setting the HDMI picture aspect ratio of a mode.

**Description**

This is the kernel API display mode information structure. For the
user-space version see struct drm_mode_modeinfo.

The horizontal and vertical timings are defined per the following diagram.

```text
          Active                 Front           Sync           Back
         Region                 Porch                          Porch
<-----------------------><----------------><-------------><-------------->
  //////////////////////|
 ////////////////////// |
//////////////////////  |..................               ................
                                           _______________
<----- [hv]display ----->
<------------- [hv]sync_start ------------>
<--------------------- [hv]sync_end --------------------->
<-------------------------------- [hv]total ----------------------------->*
```

This structure contains two copies of timings. First are the plain timings,
which specify the logical mode, as it would be for a progressive 1:1 scanout
at the refresh rate userspace can observe through vblank timestamps. Then
there's the hardware timings, which are corrected for interlacing,
double-clocking and similar things. They are provided as a convenience, and
can be appropriately computed using [`drm_mode_set_crtcinfo()`](#c-drm_mode_set_crtcinfo).

For printing you can use `DRM_MODE_FMT` and [`DRM_MODE_ARG()`](#c-DRM_MODE_ARG).

#### <a id="c-DRM_MODE_FMT"></a>`DRM_MODE_FMT`

```c
DRM_MODE_FMT
```

printf string for [`struct drm_display_mode`](#c-struct-drm_display_mode)

#### <a id="c-DRM_MODE_ARG"></a>`DRM_MODE_ARG()`

```c
DRM_MODE_ARG(m)
```

printf arguments for [`struct drm_display_mode`](#c-struct-drm_display_mode)

**Parameters**

- `m`: display mode

#### <a id="c-drm_mode_is_stereo"></a>`drm_mode_is_stereo()`

```c
bool drm_mode_is_stereo(const struct drm_display_mode *mode)
```

check for stereo mode flags

**Parameters**

- `const struct drm_display_mode *mode`: drm_display_mode to check

**Return**

True if the mode is one of the stereo modes (like side-by-side), false if
not.



#### <a id="c-drm_mode_debug_printmodeline"></a>`drm_mode_debug_printmodeline()`

```c
void drm_mode_debug_printmodeline(const struct drm_display_mode *mode)
```

print a mode to dmesg

**Parameters**

- `const struct drm_display_mode *mode`: mode to print

**Description**

Describe **mode** using DRM_DEBUG.

#### <a id="c-drm_mode_create"></a>`drm_mode_create()`

```c
struct drm_display_mode * drm_mode_create(struct drm_device *dev)
```

create a new display mode

**Parameters**

- `struct drm_device *dev`: DRM device

**Description**

Create a new, cleared drm_display_mode with kzalloc, allocate an ID for it
and return it.

**Return**

Pointer to new mode on success, NULL on error.

#### <a id="c-drm_mode_destroy"></a>`drm_mode_destroy()`

```c
void drm_mode_destroy(struct drm_device *dev, struct drm_display_mode *mode)
```

remove a mode

**Parameters**

- `struct drm_device *dev`: DRM device
- `struct drm_display_mode *mode`: mode to remove

**Description**

Release **mode**'s unique ID, then free it **mode** structure itself using kfree.

#### <a id="c-drm_mode_probed_add"></a>`drm_mode_probed_add()`

```c
void drm_mode_probed_add(struct drm_connector *connector, struct drm_display_mode *mode)
```

add a mode to a connector's probed_mode list

**Parameters**

- `struct drm_connector *connector`: connector the new mode
- `struct drm_display_mode *mode`: mode data

**Description**

Add **mode** to **connector**'s probed_mode list for later use. This list should
then in a second step get filtered and all the modes actually supported by
the hardware moved to the **connector**'s modes list.

#### <a id="c-drm_analog_tv_mode"></a>`drm_analog_tv_mode()`

```c
struct drm_display_mode * drm_analog_tv_mode(struct drm_device *dev, enum drm_connector_tv_mode tv_mode, unsigned long pixel_clock_hz, unsigned int hdisplay, unsigned int vdisplay, bool interlace)
```

create a display mode for an analog TV

**Parameters**

- `struct drm_device *dev`: drm device
- `enum drm_connector_tv_mode tv_mode`: TV Mode standard to create a mode for. See DRM_MODE_TV_MODE_*.
- `unsigned long pixel_clock_hz`: Pixel Clock Frequency, in Hertz
- `unsigned int hdisplay`: hdisplay size
- `unsigned int vdisplay`: vdisplay size
- `bool interlace`: whether to compute an interlaced mode

**Description**

This function creates a struct drm_display_mode instance suited for
an analog TV output, for one of the usual analog TV modes. Where
this is DRM_MODE_TV_MODE_MONOCHROME, a 625-line mode will be created.

Note that **hdisplay** is larger than the usual constraints for the PAL
and NTSC timings, and we'll choose to ignore most timings constraints
to reach those resolutions.

**Return**

A pointer to the mode, allocated with [`drm_mode_create()`](#c-drm_mode_create). Returns NULL
on error.

#### <a id="c-drm_cvt_mode"></a>`drm_cvt_mode()`

```c
struct drm_display_mode * drm_cvt_mode(struct drm_device *dev, int hdisplay, int vdisplay, int vrefresh, bool reduced, bool interlaced, bool margins)
```

create a modeline based on the CVT algorithm

**Parameters**

- `struct drm_device *dev`: drm device
- `int hdisplay`: hdisplay size
- `int vdisplay`: vdisplay size
- `int vrefresh`: vrefresh rate
- `bool reduced`: whether to use reduced blanking
- `bool interlaced`: whether to compute an interlaced mode
- `bool margins`: whether to add margins (borders)

**Description**

This function is called to generate the modeline based on CVT algorithm
according to the hdisplay, vdisplay, vrefresh.
It is based from the VESA(TM) Coordinated Video Timing Generator by
Graham Loveridge April 9, 2003 available at
http://www.elo.utfsm.cl/~elo212/docs/CVTd6r1.xls

And it is copied from xf86CVTmode in xserver/hw/xfree86/modes/xf86cvt.c.
What I have done is to translate it by using integer calculation.

**Return**

The modeline based on the CVT algorithm stored in a drm_display_mode object.
The display mode object is allocated with [`drm_mode_create()`](#c-drm_mode_create). Returns NULL
when no mode could be allocated.

#### <a id="c-drm_gtf_mode_complex"></a>`drm_gtf_mode_complex()`

```c
struct drm_display_mode * drm_gtf_mode_complex(struct drm_device *dev, int hdisplay, int vdisplay, int vrefresh, bool interlaced, int margins, int GTF_M, int GTF_2C, int GTF_K, int GTF_2J)
```

create the modeline based on the full GTF algorithm

**Parameters**

- `struct drm_device *dev`: drm device
- `int hdisplay`: hdisplay size
- `int vdisplay`: vdisplay size
- `int vrefresh`: vrefresh rate.
- `bool interlaced`: whether to compute an interlaced mode
- `int margins`: desired margin (borders) size
- `int GTF_M`: extended GTF formula parameters
- `int GTF_2C`: extended GTF formula parameters
- `int GTF_K`: extended GTF formula parameters
- `int GTF_2J`: extended GTF formula parameters

**Description**

GTF feature blocks specify C and J in multiples of 0.5, so we pass them
in here multiplied by two.  For a C of 40, pass in 80.

**Return**

The modeline based on the full GTF algorithm stored in a drm_display_mode object.
The display mode object is allocated with [`drm_mode_create()`](#c-drm_mode_create). Returns NULL
when no mode could be allocated.

#### <a id="c-drm_gtf_mode"></a>`drm_gtf_mode()`

```c
struct drm_display_mode * drm_gtf_mode(struct drm_device *dev, int hdisplay, int vdisplay, int vrefresh, bool interlaced, int margins)
```

create the modeline based on the GTF algorithm

**Parameters**

- `struct drm_device *dev`: drm device
- `int hdisplay`: hdisplay size
- `int vdisplay`: vdisplay size
- `int vrefresh`: vrefresh rate.
- `bool interlaced`: whether to compute an interlaced mode
- `int margins`: desired margin (borders) size

**Description**

return the modeline based on GTF algorithm

This function is to create the modeline based on the GTF algorithm.
Generalized Timing Formula is derived from:

GTF Spreadsheet by Andy Morrish (1/5/97)
available at https://www.vesa.org

And it is copied from the file of xserver/hw/xfree86/modes/xf86gtf.c.
What I have done is to translate it by using integer calculation.
I also refer to the function of fb_get_mode in the file of
drivers/video/fbmon.c

Standard GTF parameters:

```text
M = 600
C = 40
K = 128
J = 20
```

**Return**

The modeline based on the GTF algorithm stored in a drm_display_mode object.
The display mode object is allocated with [`drm_mode_create()`](#c-drm_mode_create). Returns NULL
when no mode could be allocated.

#### <a id="c-drm_display_mode_from_videomode"></a>`drm_display_mode_from_videomode()`

```c
void drm_display_mode_from_videomode(const struct videomode *vm, struct drm_display_mode *dmode)
```

fill in **dmode** using **vm**,

**Parameters**

- `const struct videomode *vm`: videomode structure to use as source
- `struct drm_display_mode *dmode`: drm_display_mode structure to use as destination

**Description**

Fills out **dmode** using the display mode specified in **vm**.

#### <a id="c-drm_display_mode_to_videomode"></a>`drm_display_mode_to_videomode()`

```c
void drm_display_mode_to_videomode(const struct drm_display_mode *dmode, struct videomode *vm)
```

fill in **vm** using **dmode**,

**Parameters**

- `const struct drm_display_mode *dmode`: drm_display_mode structure to use as source
- `struct videomode *vm`: videomode structure to use as destination

**Description**

Fills out **vm** using the display mode specified in **dmode**.

#### <a id="c-drm_bus_flags_from_videomode"></a>`drm_bus_flags_from_videomode()`

```c
void drm_bus_flags_from_videomode(const struct videomode *vm, u32 *bus_flags)
```

extract information about pixelclk and DE polarity from videomode and store it in a separate variable

**Parameters**

- `const struct videomode *vm`: videomode structure to use
- `u32 *bus_flags`: information about pixelclk, sync and DE polarity will be stored
  here

**Description**

Sets DRM_BUS_FLAG_DE_(LOW|HIGH),  DRM_BUS_FLAG_PIXDATA_DRIVE_(POS|NEG)EDGE
and DISPLAY_FLAGS_SYNC_(POS|NEG)EDGE in **bus_flags** according to DISPLAY_FLAGS
found in **vm**

#### <a id="c-of_get_drm_display_mode"></a>`of_get_drm_display_mode()`

```c
int of_get_drm_display_mode(struct device_node *np, struct drm_display_mode *dmode, u32 *bus_flags, int index)
```

get a drm_display_mode from devicetree

**Parameters**

- `struct device_node *np`: device_node with the timing specification
- `struct drm_display_mode *dmode`: will be set to the return value
- `u32 *bus_flags`: information about pixelclk, sync and DE polarity
- `int index`: index into the list of display timings in devicetree

**Description**

This function is expensive and should only be used, if only one mode is to be
read from DT. To get multiple modes start with of_get_display_timings and
work with that instead.

**Return**

0 on success, a negative errno code when no of videomode node was found.

#### <a id="c-of_get_drm_panel_display_mode"></a>`of_get_drm_panel_display_mode()`

```c
int of_get_drm_panel_display_mode(struct device_node *np, struct drm_display_mode *dmode, u32 *bus_flags)
```

get a panel-timing drm_display_mode from devicetree

**Parameters**

- `struct device_node *np`: device_node with the panel-timing specification
- `struct drm_display_mode *dmode`: will be set to the return value
- `u32 *bus_flags`: information about pixelclk, sync and DE polarity

**Description**

The mandatory Device Tree properties width-mm and height-mm
are read and set on the display mode.

**Return**

Zero on success, negative error code on failure.

#### <a id="c-drm_mode_set_name"></a>`drm_mode_set_name()`

```c
void drm_mode_set_name(struct drm_display_mode *mode)
```

set the name on a mode

**Parameters**

- `struct drm_display_mode *mode`: name will be set in this mode

**Description**

Set the name of **mode** to a standard format which is \<hdisplay>x\<vdisplay>
with an optional 'i' suffix for interlaced modes.

#### <a id="c-drm_mode_vrefresh"></a>`drm_mode_vrefresh()`

```c
int drm_mode_vrefresh(const struct drm_display_mode *mode)
```

get the vrefresh of a mode

**Parameters**

- `const struct drm_display_mode *mode`: mode

**Return**

**modes**'s vrefresh rate in Hz, rounded to the nearest integer.

#### <a id="c-drm_mode_get_hv_timing"></a>`drm_mode_get_hv_timing()`

```c
void drm_mode_get_hv_timing(const struct drm_display_mode *mode, int *hdisplay, int *vdisplay)
```

Fetches hdisplay/vdisplay for given mode

**Parameters**

- `const struct drm_display_mode *mode`: mode to query
- `int *hdisplay`: hdisplay value to fill in
- `int *vdisplay`: vdisplay value to fill in

**Description**

The vdisplay value will be doubled if the specified mode is a stereo mode of
the appropriate layout.

#### <a id="c-drm_mode_set_crtcinfo"></a>`drm_mode_set_crtcinfo()`

```c
void drm_mode_set_crtcinfo(struct drm_display_mode *p, int adjust_flags)
```

set CRTC modesetting timing parameters

**Parameters**

- `struct drm_display_mode *p`: mode
- `int adjust_flags`: a combination of adjustment flags

**Description**

Setup the CRTC modesetting timing parameters for **p**, adjusting if necessary.

- The CRTC_INTERLACE_HALVE_V flag can be used to halve vertical timings of
  interlaced modes.
- The CRTC_STEREO_DOUBLE flag can be used to compute the timings for
  buffers containing two eyes (only adjust the timings when needed, eg. for
  "frame packing" or "side by side full").
- The CRTC_NO_DBLSCAN and CRTC_NO_VSCAN flags request that adjustment *not*
  be performed for doublescan and vscan > 1 modes respectively.

#### <a id="c-drm_mode_copy"></a>`drm_mode_copy()`

```c
void drm_mode_copy(struct drm_display_mode *dst, const struct drm_display_mode *src)
```

copy the mode

**Parameters**

- `struct drm_display_mode *dst`: mode to overwrite
- `const struct drm_display_mode *src`: mode to copy

**Description**

Copy an existing mode into another mode, preserving the
list head of the destination mode.

#### <a id="c-drm_mode_init"></a>`drm_mode_init()`

```c
void drm_mode_init(struct drm_display_mode *dst, const struct drm_display_mode *src)
```

initialize the mode from another mode

**Parameters**

- `struct drm_display_mode *dst`: mode to overwrite
- `const struct drm_display_mode *src`: mode to copy

**Description**

Copy an existing mode into another mode, zeroing the
list head of the destination mode. Typically used
to guarantee the list head is not left with stack
garbage in on-stack modes.

#### <a id="c-drm_mode_duplicate"></a>`drm_mode_duplicate()`

```c
struct drm_display_mode * drm_mode_duplicate(struct drm_device *dev, const struct drm_display_mode *mode)
```

allocate and duplicate an existing mode

**Parameters**

- `struct drm_device *dev`: drm_device to allocate the duplicated mode for
- `const struct drm_display_mode *mode`: mode to duplicate

**Description**

Just allocate a new mode, copy the existing mode into it, and return
a pointer to it.  Used to create new instances of established modes.

**Return**

Pointer to duplicated mode on success, NULL on error.

#### <a id="c-drm_mode_match"></a>`drm_mode_match()`

```c
bool drm_mode_match(const struct drm_display_mode *mode1, const struct drm_display_mode *mode2, unsigned int match_flags)
```

test modes for (partial) equality

**Parameters**

- `const struct drm_display_mode *mode1`: first mode
- `const struct drm_display_mode *mode2`: second mode
- `unsigned int match_flags`: which parts need to match (DRM_MODE_MATCH_*)

**Description**

Check to see if **mode1** and **mode2** are equivalent.

**Return**

True if the modes are (partially) equal, false otherwise.

#### <a id="c-drm_mode_equal"></a>`drm_mode_equal()`

```c
bool drm_mode_equal(const struct drm_display_mode *mode1, const struct drm_display_mode *mode2)
```

test modes for equality

**Parameters**

- `const struct drm_display_mode *mode1`: first mode
- `const struct drm_display_mode *mode2`: second mode

**Description**

Check to see if **mode1** and **mode2** are equivalent.

**Return**

True if the modes are equal, false otherwise.

#### <a id="c-drm_mode_equal_no_clocks"></a>`drm_mode_equal_no_clocks()`

```c
bool drm_mode_equal_no_clocks(const struct drm_display_mode *mode1, const struct drm_display_mode *mode2)
```

test modes for equality

**Parameters**

- `const struct drm_display_mode *mode1`: first mode
- `const struct drm_display_mode *mode2`: second mode

**Description**

Check to see if **mode1** and **mode2** are equivalent, but
don't check the pixel clocks.

**Return**

True if the modes are equal, false otherwise.

#### <a id="c-drm_mode_equal_no_clocks_no_stereo"></a>`drm_mode_equal_no_clocks_no_stereo()`

```c
bool drm_mode_equal_no_clocks_no_stereo(const struct drm_display_mode *mode1, const struct drm_display_mode *mode2)
```

test modes for equality

**Parameters**

- `const struct drm_display_mode *mode1`: first mode
- `const struct drm_display_mode *mode2`: second mode

**Description**

Check to see if **mode1** and **mode2** are equivalent, but
don't check the pixel clocks nor the stereo layout.

**Return**

True if the modes are equal, false otherwise.

#### <a id="c-drm_mode_validate_driver"></a>`drm_mode_validate_driver()`

```c
enum drm_mode_status drm_mode_validate_driver(struct drm_device *dev, const struct drm_display_mode *mode)
```

make sure the mode is somewhat sane

**Parameters**

- `struct drm_device *dev`: drm device
- `const struct drm_display_mode *mode`: mode to check

**Description**

First do basic validation on the mode, and then allow the driver
to check for device/driver specific limitations via the optional
[`drm_mode_config_helper_funcs.mode_valid`](/kernel/hardware/gpu/drm-kms-helpers.md#c-struct-drm_mode_config_helper_funcs) hook.

**Return**

The mode status

#### <a id="c-drm_mode_validate_size"></a>`drm_mode_validate_size()`

```c
enum drm_mode_status drm_mode_validate_size(const struct drm_display_mode *mode, int maxX, int maxY)
```

make sure modes adhere to size constraints

**Parameters**

- `const struct drm_display_mode *mode`: mode to check
- `int maxX`: maximum width
- `int maxY`: maximum height

**Description**

This function is a helper which can be used to validate modes against size
limitations of the DRM device/connector. If a mode is too big its status
member is updated with the appropriate validation failure code. The list
itself is not changed.

**Return**

The mode status

#### <a id="c-drm_mode_validate_ycbcr420"></a>`drm_mode_validate_ycbcr420()`

```c
enum drm_mode_status drm_mode_validate_ycbcr420(const struct drm_display_mode *mode, struct drm_connector *connector)
```

add 'ycbcr420-only' modes only when allowed

**Parameters**

- `const struct drm_display_mode *mode`: mode to check
- `struct drm_connector *connector`: drm connector under action

**Description**

This function is a helper which can be used to filter out any YCBCR420
only mode, when the source doesn't support it.

**Return**

The mode status

#### <a id="c-drm_mode_prune_invalid"></a>`drm_mode_prune_invalid()`

```c
void drm_mode_prune_invalid(struct drm_device *dev, struct list_head *mode_list, bool verbose)
```

remove invalid modes from mode list

**Parameters**

- `struct drm_device *dev`: DRM device
- `struct list_head *mode_list`: list of modes to check
- `bool verbose`: be verbose about it

**Description**

This helper function can be used to prune a display mode list after
validation has been completed. All modes whose status is not MODE_OK will be
removed from the list, and if **verbose** the status code and mode name is also
printed to dmesg.

#### <a id="c-drm_mode_sort"></a>`drm_mode_sort()`

```c
void drm_mode_sort(struct list_head *mode_list)
```

sort mode list

**Parameters**

- `struct list_head *mode_list`: list of drm_display_mode structures to sort

**Description**

Sort **mode_list** by favorability, moving good modes to the head of the list.

#### <a id="c-drm_connector_list_update"></a>`drm_connector_list_update()`

```c
void drm_connector_list_update(struct drm_connector *connector)
```

update the mode list for the connector

**Parameters**

- `struct drm_connector *connector`: the connector to update

**Description**

This moves the modes from the **connector** probed_modes list
to the actual mode list. It compares the probed mode against the current
list and only adds different/new modes.

This is just a helper functions doesn't validate any modes itself and also
doesn't prune any invalid modes. Callers need to do that themselves.

#### <a id="c-drm_mode_parse_command_line_for_connector"></a>`drm_mode_parse_command_line_for_connector()`

```c
bool drm_mode_parse_command_line_for_connector(const char *mode_option, const struct drm_connector *connector, struct drm_cmdline_mode *mode)
```

parse command line modeline for connector

**Parameters**

- `const char *mode_option`: optional per connector mode option
- `const struct drm_connector *connector`: connector to parse modeline for
- `struct drm_cmdline_mode *mode`: preallocated drm_cmdline_mode structure to fill out

**Description**

This parses **mode_option** command line modeline for modes and options to
configure the connector.

This uses the same parameters as the fb modedb.c, except for an extra
force-enable, force-enable-digital and force-disable bit at the end:

```text
<xres>x<yres>[M][R][-<bpp>][@<refresh>][i][m][eDd]
```

Additionals options can be provided following the mode, using a comma to
separate each option. Valid options can be found in
Documentation/fb/modedb.rst.

The intermediate drm_cmdline_mode structure is required to store additional
options from the command line modline like the force-enable/disable flag.

**Return**

True if a valid modeline has been parsed, false otherwise.

#### <a id="c-drm_mode_create_from_cmdline_mode"></a>`drm_mode_create_from_cmdline_mode()`

```c
struct drm_display_mode * drm_mode_create_from_cmdline_mode(struct drm_device *dev, struct drm_cmdline_mode *cmd)
```

convert a command line modeline into a DRM display mode

**Parameters**

- `struct drm_device *dev`: DRM device to create the new mode for
- `struct drm_cmdline_mode *cmd`: input command line modeline

**Return**

Pointer to converted mode on success, NULL on error.

#### <a id="c-drm_mode_is_420_only"></a>`drm_mode_is_420_only()`

```c
bool drm_mode_is_420_only(const struct drm_display_info *display, const struct drm_display_mode *mode)
```

if a given videomode can be only supported in YCBCR420 output format

**Parameters**

- `const struct drm_display_info *display`: display under action
- `const struct drm_display_mode *mode`: video mode to be tested.

**Return**

true if the mode can be supported in YCBCR420 format
false if not.

#### <a id="c-drm_mode_is_420_also"></a>`drm_mode_is_420_also()`

```c
bool drm_mode_is_420_also(const struct drm_display_info *display, const struct drm_display_mode *mode)
```

if a given videomode can be supported in YCBCR420 output format also (along with RGB/YCBCR444/422)

**Parameters**

- `const struct drm_display_info *display`: display under action.
- `const struct drm_display_mode *mode`: video mode to be tested.

**Return**

true if the mode can be support YCBCR420 format
false if not.

#### <a id="c-drm_mode_is_420"></a>`drm_mode_is_420()`

```c
bool drm_mode_is_420(const struct drm_display_info *display, const struct drm_display_mode *mode)
```

if a given videomode can be supported in YCBCR420 output format

**Parameters**

- `const struct drm_display_info *display`: display under action.
- `const struct drm_display_mode *mode`: video mode to be tested.

**Return**

true if the mode can be supported in YCBCR420 format
false if not.

#### <a id="c-drm_set_preferred_mode"></a>`drm_set_preferred_mode()`

```c
void drm_set_preferred_mode(struct drm_connector *connector, int hpref, int vpref)
```

Sets the preferred mode of a connector

**Parameters**

- `struct drm_connector *connector`: connector whose mode list should be processed
- `int hpref`: horizontal resolution of preferred mode
- `int vpref`: vertical resolution of preferred mode

**Description**

Marks a mode as preferred if it matches the resolution specified by **hpref**
and **vpref**.


<a id="rst-connector-abstraction"></a>

## Connector Abstraction


In DRM connectors are the general abstraction for display sinks, and include
also fixed panels or anything else that can display pixels in some form. As
opposed to all other KMS objects representing hardware (like CRTC, encoder or
plane abstractions) connectors can be hotplugged and unplugged at runtime.
Hence they are reference-counted using [`drm_connector_get()`](#c-drm_connector_get) and
[`drm_connector_put()`](#c-drm_connector_put).

KMS driver must create, initialize, register and attach at a [`struct drm_connector`](#c-struct-drm_connector) for each such sink. The instance is created as other KMS
objects and initialized by setting the following fields. The connector is
initialized with a call to [`drm_connector_init()`](#c-drm_connector_init) with a pointer to the
[`struct drm_connector_funcs`](#c-struct-drm_connector_funcs) and a connector type, and then exposed to
userspace with a call to [`drm_connector_register()`](#c-drm_connector_register).

Connectors must be attached to an encoder to be used. For devices that map
connectors to encoders 1:1, the connector should be attached at
initialization time with a call to [`drm_connector_attach_encoder()`](#c-drm_connector_attach_encoder). The
driver must also set the [`drm_connector.encoder`](#c-struct-drm_connector) field to point to the
attached encoder.

For connectors which are not fixed (like built-in panels) the driver needs to
support hotplug notifications. The simplest way to do that is by using the
probe helpers, see [`drm_kms_helper_poll_init()`](/kernel/hardware/gpu/drm-kms-helpers.md#c-drm_kms_helper_poll_init) for connectors which don't have
hardware support for hotplug interrupts. Connectors with hardware hotplug
support can instead use e.g. [`drm_helper_hpd_irq_event()`](/kernel/hardware/gpu/drm-kms-helpers.md#c-drm_helper_hpd_irq_event).


<a id="rst-connector-functions-reference"></a>

### Connector Functions Reference


#### <a id="c-enum-drm_connector_status"></a>`enum drm_connector_status`

status for a [`drm_connector`](#c-struct-drm_connector)

**Constants**

- `connector_status_connected`: The connector is definitely connected to
  a sink device, and can be enabled.
- `connector_status_disconnected`: The connector isn't connected to a
  sink device which can be autodetect. For digital outputs like DP or
  HDMI (which can be realiable probed) this means there's really
  nothing there. It is driver-dependent whether a connector with this
  status can be lit up or not.
- `connector_status_unknown`: The connector's status could not be
  reliably detected. This happens when probing would either cause
  flicker (like load-detection when the connector is in use), or when a
  hardware resource isn't available (like when load-detection needs a
  free CRTC). It should be possible to light up the connector with one
  of the listed fallback modes. For default configuration userspace
  should only try to light up connectors with unknown status when
  there's not connector with **connector_status_connected**.

**Description**

This enum is used to track the connector status. There are no separate
\#defines for the uapi!

#### <a id="c-enum-drm_connector_registration_state"></a>`enum drm_connector_registration_state`

userspace registration status for a [`drm_connector`](#c-struct-drm_connector)

**Constants**

- `DRM_CONNECTOR_INITIALIZING`: The connector has just been created,
  but has yet to be exposed to userspace. There should be no
  additional restrictions to how the state of this connector may be
  modified.
- `DRM_CONNECTOR_REGISTERED`: The connector has been fully initialized
  and registered with sysfs, as such it has been exposed to
  userspace. There should be no additional restrictions to how the
  state of this connector may be modified.
- `DRM_CONNECTOR_UNREGISTERED`: The connector has either been exposed
  to userspace and has since been unregistered and removed from
  userspace, or the connector was unregistered before it had a chance
  to be exposed to userspace (e.g. still in the
  **DRM_CONNECTOR_INITIALIZING** state). When a connector is
  unregistered, there are additional restrictions to how its state
  may be modified:

  - An unregistered connector may only have its DPMS changed from
    On->Off. Once DPMS is changed to Off, it may not be switched back
    to On.
  - Modesets are not allowed on unregistered connectors, unless they
    would result in disabling its assigned CRTCs. This means
    disabling a CRTC on an unregistered connector is OK, but enabling
    one is not.
  - Removing a CRTC from an unregistered connector is OK, but new
    CRTCs may never be assigned to an unregistered connector.

**Description**

This enum is used to track the status of initializing a connector and
registering it with userspace, so that DRM can prevent bogus modesets on
connectors that no longer exist.

#### <a id="c-enum-drm_connector_tv_mode"></a>`enum drm_connector_tv_mode`

Analog TV output mode

**Constants**

- `DRM_MODE_TV_MODE_NTSC`: CCIR System M (aka 525-lines)
  together with the NTSC Color Encoding.
- `DRM_MODE_TV_MODE_NTSC_443`: Variant of
  **DRM_MODE_TV_MODE_NTSC**. Uses a color subcarrier frequency
  of 4.43 MHz.
- `DRM_MODE_TV_MODE_NTSC_J`: Variant of **DRM_MODE_TV_MODE_NTSC**
  used in Japan. Uses a black level equals to the blanking
  level.
- `DRM_MODE_TV_MODE_PAL`: CCIR System B together with the PAL
  color system.
- `DRM_MODE_TV_MODE_PAL_M`: CCIR System M (aka 525-lines)
  together with the PAL color encoding
- `DRM_MODE_TV_MODE_PAL_N`: CCIR System N together with the PAL
  color encoding. It uses 625 lines, but has a color subcarrier
  frequency of 3.58MHz, the SECAM color space, and narrower
  channels compared to most of the other PAL variants.
- `DRM_MODE_TV_MODE_SECAM`: CCIR System B together with the
  SECAM color system.
- `DRM_MODE_TV_MODE_MONOCHROME`: Use timings appropriate to
  the DRM mode, including equalizing pulses for a 525-line
  or 625-line mode, with no pedestal or color encoding.
- `DRM_MODE_TV_MODE_MAX`: Number of analog TV output modes.

  Internal implementation detail; this is not uABI.

**Description**

This enum is used to indicate the TV output mode used on an analog TV
connector.

WARNING: The values of this enum is uABI since they're exposed in the
"TV mode" connector property.

#### <a id="c-struct-drm_scrambling"></a>`struct drm_scrambling`

sink's scrambling support.

**Definition**

```c
struct drm_scrambling {
    bool supported;
    bool low_rates;
};
```

**Members**

- `supported`: scrambling supported for rates > 340 Mhz.
- `low_rates`: scrambling supported for rates \<= 340 Mhz.

#### <a id="c-struct-drm_hdmi_dsc_cap"></a>`struct drm_hdmi_dsc_cap`

DSC capabilities of HDMI sink

**Definition**

```c
struct drm_hdmi_dsc_cap {
    bool v_1p2;
    bool native_420;
    bool all_bpp;
    u8 bpc_supported;
    u8 max_slices;
    int clk_per_slice;
    u8 max_lanes;
    u8 max_frl_rate_per_lane;
    u8 total_chunk_kbytes;
};
```

**Members**

- `v_1p2`: flag for dsc1.2 version support by sink
- `native_420`: Does sink support DSC with 4:2:0 compression
- `all_bpp`: Does sink support all bpp with 4:4:4: or 4:2:2
  compressed formats
- `bpc_supported`: compressed bpc supported by sink : 10, 12 or 16 bpc
- `max_slices`: maximum number of Horizontal slices supported by
- `clk_per_slice`: max pixel clock in MHz supported per slice
- `max_lanes`: dsc max lanes supported for Fixed rate Link training
- `max_frl_rate_per_lane`: maximum frl rate with DSC per lane
- `total_chunk_kbytes`: max size of chunks in KBs supported per line

**Description**

Describes the DSC support provided by HDMI 2.1 sink.
The information is fetched fom additional HFVSDB blocks defined
for HDMI 2.1.

#### <a id="c-struct-drm_hdmi_info"></a>`struct drm_hdmi_info`

runtime information about the connected HDMI sink

**Definition**

```c
struct drm_hdmi_info {
    struct drm_scdc scdc;
    unsigned long y420_vdb_modes[BITS_TO_LONGS(256)];
    unsigned long y420_cmdb_modes[BITS_TO_LONGS(256)];
    u8 y420_dc_modes;
    u8 max_frl_rate_per_lane;
    u8 max_lanes;
    struct drm_hdmi_dsc_cap dsc_cap;
};
```

**Members**

- `scdc`: sink's scdc support and capabilities
- `y420_vdb_modes`: bitmap of modes which can support ycbcr420
  output only (not normal RGB/YCBCR444/422 outputs). The max VIC
  defined by the CEA-861-G spec is 219, so the size is 256 bits to map
  up to 256 VICs.
- `y420_cmdb_modes`: bitmap of modes which can support ycbcr420
  output also, along with normal HDMI outputs. The max VIC defined by
  the CEA-861-G spec is 219, so the size is 256 bits to map up to 256
  VICs.
- `y420_dc_modes`: bitmap of deep color support index
- `max_frl_rate_per_lane`: support fixed rate link
- `max_lanes`: supported by sink
- `dsc_cap`: DSC capabilities of the sink

**Description**

Describes if a given display supports advanced HDMI 2.0 features.
This information is available in CEA-861-F extension blocks (like HF-VSDB).

#### <a id="c-enum-drm_link_status"></a>`enum drm_link_status`

connector's link_status property value

**Constants**

- `DRM_LINK_STATUS_GOOD`: DP Link is Good as a result of successful
  link training
- `DRM_LINK_STATUS_BAD`: DP Link is BAD as a result of link training
  failure

**Description**

This enum is used as the connector's link status property value.
It is set to the values defined in uapi.

#### <a id="c-enum-drm_panel_orientation"></a>`enum drm_panel_orientation`

panel_orientation info for [`drm_display_info`](#c-struct-drm_display_info)

**Constants**

- `DRM_MODE_PANEL_ORIENTATION_UNKNOWN`: The drm driver has not provided any
  panel orientation information (normal
  for non panels) in this case the "panel
  orientation" connector prop will not be
  attached.
- `DRM_MODE_PANEL_ORIENTATION_NORMAL`: The top side of the panel matches the
  top side of the device's casing.
- `DRM_MODE_PANEL_ORIENTATION_BOTTOM_UP`: The top side of the panel matches the
  bottom side of the device's casing, iow
  the panel is mounted upside-down.
- `DRM_MODE_PANEL_ORIENTATION_LEFT_UP`: The left side of the panel matches the
  top side of the device's casing.
- `DRM_MODE_PANEL_ORIENTATION_RIGHT_UP`: The right side of the panel matches the
  top side of the device's casing.

**Description**

This enum is used to track the (LCD) panel orientation. There are no
separate #defines for the uapi!

#### <a id="c-enum-drm_hdmi_broadcast_rgb"></a>`enum drm_hdmi_broadcast_rgb`

Broadcast RGB Selection for an HDMI **drm_connector**

**Constants**

- `DRM_HDMI_BROADCAST_RGB_AUTO`: The RGB range is selected
  automatically based on the mode.
- `DRM_HDMI_BROADCAST_RGB_FULL`: Full range RGB is forced.
- `DRM_HDMI_BROADCAST_RGB_LIMITED`: Limited range RGB is forced.

#### <a id="c-struct-drm_monitor_range_info"></a>`struct drm_monitor_range_info`

Panel's Monitor range in EDID for [`drm_display_info`](#c-struct-drm_display_info)

**Definition**

```c
struct drm_monitor_range_info {
    u16 min_vfreq;
    u16 max_vfreq;
};
```

**Members**

- `min_vfreq`: This is the min supported refresh rate in Hz from
  EDID's detailed monitor range.
- `max_vfreq`: This is the max supported refresh rate in Hz from
  EDID's detailed monitor range

**Description**

This struct is used to store a frequency range supported by panel
as parsed from EDID's detailed monitor range descriptor block.

#### <a id="c-struct-drm_luminance_range_info"></a>`struct drm_luminance_range_info`

Panel's luminance range for [`drm_display_info`](#c-struct-drm_display_info). Calculated using data in EDID

**Definition**

```c
struct drm_luminance_range_info {
    u32 min_luminance;
    u32 max_luminance;
};
```

**Members**

- `min_luminance`: This is the min supported luminance value
- `max_luminance`: This is the max supported luminance value

**Description**

This struct is used to store a luminance range supported by panel
as calculated using data from EDID's static hdr metadata.

#### <a id="c-enum-drm_privacy_screen_status"></a>`enum drm_privacy_screen_status`

privacy screen status

**Constants**

- `PRIVACY_SCREEN_DISABLED`: The privacy-screen on the panel is disabled
- `PRIVACY_SCREEN_ENABLED`: The privacy-screen on the panel is enabled
- `PRIVACY_SCREEN_DISABLED_LOCKED`: The privacy-screen on the panel is disabled and locked (cannot be changed)
- `PRIVACY_SCREEN_ENABLED_LOCKED`: The privacy-screen on the panel is enabled and locked (cannot be changed)

**Description**

This enum is used to track and control the state of the integrated privacy
screen present on some display panels, via the "privacy-screen sw-state"
and "privacy-screen hw-state" properties. Note the _LOCKED enum values
are only valid for the "privacy-screen hw-state" property.

#### <a id="c-enum-drm_colorspace"></a>`enum drm_colorspace`

color space

**Constants**

- `DRM_MODE_COLORIMETRY_DEFAULT`: Driver specific behavior.
- `DRM_MODE_COLORIMETRY_NO_DATA`: Driver specific behavior.
- `DRM_MODE_COLORIMETRY_SMPTE_170M_YCC`: (HDMI)
  SMPTE ST 170M colorimetry format
- `DRM_MODE_COLORIMETRY_BT709_YCC`: (HDMI, DP)
  ITU-R BT.709 colorimetry format
- `DRM_MODE_COLORIMETRY_XVYCC_601`: (HDMI, DP)
  xvYCC601 colorimetry format
- `DRM_MODE_COLORIMETRY_XVYCC_709`: (HDMI, DP)
  xvYCC709 colorimetry format
- `DRM_MODE_COLORIMETRY_SYCC_601`: (HDMI, DP)
  sYCC601 colorimetry format
- `DRM_MODE_COLORIMETRY_OPYCC_601`: (HDMI, DP)
  opYCC601 colorimetry format
- `DRM_MODE_COLORIMETRY_OPRGB`: (HDMI, DP)
  opRGB colorimetry format
- `DRM_MODE_COLORIMETRY_BT2020_CYCC`: (HDMI, DP)
  ITU-R BT.2020 Y'c C'bc C'rc (constant luminance) colorimetry format
- `DRM_MODE_COLORIMETRY_BT2020_RGB`: (HDMI, DP)
  ITU-R BT.2020 R' G' B' colorimetry format
- `DRM_MODE_COLORIMETRY_BT2020_YCC`: (HDMI, DP)
  ITU-R BT.2020 Y' C'b C'r colorimetry format
- `DRM_MODE_COLORIMETRY_DCI_P3_RGB_D65`: (HDMI)
  SMPTE ST 2113 P3D65 colorimetry format
- `DRM_MODE_COLORIMETRY_DCI_P3_RGB_THEATER`: (HDMI)
  SMPTE ST 2113 P3DCI colorimetry format
- `DRM_MODE_COLORIMETRY_RGB_WIDE_FIXED`: (DP)
  RGB wide gamut fixed point colorimetry format
- `DRM_MODE_COLORIMETRY_RGB_WIDE_FLOAT`: (DP)
  RGB wide gamut floating point
  (scRGB (IEC 61966-2-2)) colorimetry format
- `DRM_MODE_COLORIMETRY_BT601_YCC`: (DP)
  ITU-R BT.601 colorimetry format
  The DP spec does not say whether this is the 525 or the 625
  line version.
- `DRM_MODE_COLORIMETRY_COUNT`: Not a valid value; merely used four counting

**Description**

This enum is a consolidated colorimetry list supported by HDMI and
DP protocol standard. The respective connectors will register
a property with the subset of this list (supported by that
respective protocol). Userspace will set the colorspace through
a colorspace property which will be created and exposed to
userspace.

DP definitions come from the DP v2.0 spec
HDMI definitions come from the CTA-861-H spec

#### <a id="c-enum-drm_bus_flags"></a>`enum drm_bus_flags`

bus_flags info for [`drm_display_info`](#c-struct-drm_display_info)

**Constants**

- `DRM_BUS_FLAG_DE_LOW`: The Data Enable signal is active low
- `DRM_BUS_FLAG_DE_HIGH`: The Data Enable signal is active high
- `DRM_BUS_FLAG_PIXDATA_DRIVE_POSEDGE`: Data is driven on the rising edge of the pixel clock
- `DRM_BUS_FLAG_PIXDATA_DRIVE_NEGEDGE`: Data is driven on the falling edge of the pixel clock
- `DRM_BUS_FLAG_PIXDATA_SAMPLE_POSEDGE`: Data is sampled on the rising edge of the pixel clock
- `DRM_BUS_FLAG_PIXDATA_SAMPLE_NEGEDGE`: Data is sampled on the falling edge of the pixel clock
- `DRM_BUS_FLAG_DATA_MSB_TO_LSB`: Data is transmitted MSB to LSB on the bus
- `DRM_BUS_FLAG_DATA_LSB_TO_MSB`: Data is transmitted LSB to MSB on the bus
- `DRM_BUS_FLAG_SYNC_DRIVE_POSEDGE`: Sync signals are driven on the rising edge of the pixel clock
- `DRM_BUS_FLAG_SYNC_DRIVE_NEGEDGE`: Sync signals are driven on the falling edge of the pixel clock
- `DRM_BUS_FLAG_SYNC_SAMPLE_POSEDGE`: Sync signals are sampled on the rising edge of the pixel clock
- `DRM_BUS_FLAG_SYNC_SAMPLE_NEGEDGE`: Sync signals are sampled on the falling edge of the pixel clock
- `DRM_BUS_FLAG_SHARP_SIGNALS`: Set if the Sharp-specific signals (SPL, CLS, PS, REV) must be used

**Description**

This enum defines signal polarities and clock edge information for signals on
a bus as bitmask flags.

The clock edge information is conveyed by two sets of symbols,
DRM_BUS_FLAGS_*_DRIVE_\* and DRM_BUS_FLAGS_*_SAMPLE_\*. When this enum is
used to describe a bus from the point of view of the transmitter, the
\*_DRIVE_\* flags should be used. When used from the point of view of the
receiver, the \*_SAMPLE_\* flags should be used. The \*_DRIVE_\* and
\*_SAMPLE_\* flags alias each other, with the \*_SAMPLE_POSEDGE and
\*_SAMPLE_NEGEDGE flags being equal to \*_DRIVE_NEGEDGE and \*_DRIVE_POSEDGE
respectively. This simplifies code as signals are usually sampled on the
opposite edge of the driving edge. Transmitters and receivers may however
need to take other signal timings into account to convert between driving
and sample edges.

#### <a id="c-struct-drm_display_info"></a>`struct drm_display_info`

runtime data about the connected sink

**Definition**

```c
struct drm_display_info {
        unsigned int width_mm;
        unsigned int height_mm;
        unsigned int bpc;
        enum subpixel_order subpixel_order;
    #define DRM_COLOR_FORMAT_RGB444         (1<<0);
    #define DRM_COLOR_FORMAT_YCBCR444       (1<<1);
    #define DRM_COLOR_FORMAT_YCBCR422       (1<<2);
    #define DRM_COLOR_FORMAT_YCBCR420       (1<<3);
        int panel_orientation;
        u32 color_formats;
        const u32 *bus_formats;
        unsigned int num_bus_formats;
        u32 bus_flags;
        int max_tmds_clock;
        bool dvi_dual;
        bool is_hdmi;
        bool has_audio;
        bool has_hdmi_infoframe;
        bool rgb_quant_range_selectable;
        u8 edid_hdmi_rgb444_dc_modes;
        u8 edid_hdmi_ycbcr444_dc_modes;
        u8 cea_rev;
        struct drm_hdmi_info hdmi;
        struct hdr_sink_metadata hdr_sink_metadata;
        bool non_desktop;
        struct drm_monitor_range_info monitor_range;
        struct drm_luminance_range_info luminance_range;
        u8 mso_stream_count;
        u8 mso_pixel_overlap;
        u32 max_dsc_bpp;
        u8 *vics;
        int vics_len;
        u32 quirks;
        u16 source_physical_address;
};
```

**Members**

- `width_mm`: Physical width in mm.
- `height_mm`: Physical height in mm.
- `bpc`: Maximum bits per color channel. Used by HDMI and DP outputs.
- `subpixel_order`: Subpixel order of LCD panels.
- `panel_orientation`: Read only connector property for built-in panels,
  indicating the orientation of the panel vs the device's casing.
  [`drm_connector_init()`](#c-drm_connector_init) sets this to DRM_MODE_PANEL_ORIENTATION_UNKNOWN.
  When not UNKNOWN this gets used by the drm_fb_helpers to rotate the
  fb to compensate and gets exported as prop to userspace.
- `color_formats`: HDMI Color formats, selects between RGB and YCrCb
  modes. Used DRM_COLOR_FORMAT\_ defines, which are _not_ the same ones
  as used to describe the pixel format in framebuffers, and also don't
  match the formats in **bus_formats** which are shared with v4l.
- `bus_formats`: Pixel data format on the wire, somewhat redundant with
  **color_formats**. Array of size **num_bus_formats** encoded using
  MEDIA_BUS_FMT\_ defines shared with v4l and media drivers.
- `num_bus_formats`: Size of **bus_formats** array.
- `bus_flags`: Additional information (like pixel signal polarity) for
  the pixel data on the bus, using [`enum drm_bus_flags`](#c-enum-drm_bus_flags) values
  DRM_BUS_FLAGS\_.
- `max_tmds_clock`: Maximum TMDS clock rate supported by the
  sink in kHz. 0 means undefined.
- `dvi_dual`: Dual-link DVI sink?
- `is_hdmi`: True if the sink is an HDMI device.

  This field shall be used instead of calling
  [`drm_detect_hdmi_monitor()`](/kernel/hardware/gpu/drm-kms-helpers.md#c-drm_detect_hdmi_monitor) when possible.
- `has_audio`: True if the sink supports audio.

  This field shall be used instead of calling
  [`drm_detect_monitor_audio()`](/kernel/hardware/gpu/drm-kms-helpers.md#c-drm_detect_monitor_audio) when possible.
- `has_hdmi_infoframe`: Does the sink support the HDMI infoframe?
- `rgb_quant_range_selectable`: Does the sink support selecting
  the RGB quantization range?
- `edid_hdmi_rgb444_dc_modes`: Mask of supported hdmi deep color modes
  in RGB 4:4:4. Even more stuff redundant with **bus_formats**.
- `edid_hdmi_ycbcr444_dc_modes`: Mask of supported hdmi deep color
  modes in YCbCr 4:4:4. Even more stuff redundant with **bus_formats**.
- `cea_rev`: CEA revision of the HDMI sink.
- `hdmi`: advance features of a HDMI sink.
- `hdr_sink_metadata`: HDR Metadata Information read from sink
- `non_desktop`: Non desktop display (HMD).
- `monitor_range`: Frequency range supported by monitor range descriptor
- `luminance_range`: Luminance range supported by panel
- `mso_stream_count`: eDP Multi-SST Operation (MSO) stream count from
  the DisplayID VESA vendor block. 0 for conventional Single-Stream
  Transport (SST), or 2 or 4 MSO streams.
- `mso_pixel_overlap`: eDP MSO segment pixel overlap, 0-8 pixels.
- `max_dsc_bpp`: Maximum DSC target bitrate, if it is set to 0 the
  monitor's default value is used instead.
- `vics`: Array of vics_len VICs. Internal to EDID parsing.
- `vics_len`: Number of elements in vics. Internal to EDID parsing.
- `quirks`: EDID based quirks. DRM core and drivers can query the
  **drm_edid_quirk** quirks using `drm_edid_has_quirk()`, the rest of
  the quirks also tracked here are internal to EDID parsing.
- `source_physical_address`: Source Physical Address from HDMI
  Vendor-Specific Data Block, for CEC usage.

  Defaults to CEC_PHYS_ADDR_INVALID (0xffff).

**Description**

Describes a given display (e.g. CRT or flat panel) and its limitations. For
fixed display sinks like built-in panels there's not much difference between
this and [`struct drm_connector`](#c-struct-drm_connector). But for sinks with a real cable this
structure is meant to describe all the things at the other end of the cable.

For sinks which provide an EDID this can be filled out by calling
[`drm_add_edid_modes()`](/kernel/hardware/gpu/drm-kms-helpers.md#c-drm_add_edid_modes).

#### <a id="c-struct-drm_connector_tv_margins"></a>`struct drm_connector_tv_margins`

TV connector related margins

**Definition**

```c
struct drm_connector_tv_margins {
    unsigned int bottom;
    unsigned int left;
    unsigned int right;
    unsigned int top;
};
```

**Members**

- `bottom`: Bottom margin in pixels.
- `left`: Left margin in pixels.
- `right`: Right margin in pixels.
- `top`: Top margin in pixels.

**Description**

Describes the margins in pixels to put around the image on TV
connectors to deal with overscan.

#### <a id="c-struct-drm_tv_connector_state"></a>`struct drm_tv_connector_state`

TV connector related states

**Definition**

```c
struct drm_tv_connector_state {
    enum drm_mode_subconnector select_subconnector;
    enum drm_mode_subconnector subconnector;
    struct drm_connector_tv_margins margins;
    unsigned int legacy_mode;
    unsigned int mode;
    unsigned int brightness;
    unsigned int contrast;
    unsigned int flicker_reduction;
    unsigned int overscan;
    unsigned int saturation;
    unsigned int hue;
};
```

**Members**

- `select_subconnector`: selected subconnector
- `subconnector`: detected subconnector
- `margins`: TV margins
- `legacy_mode`: Legacy TV mode, driver specific value
- `mode`: TV mode
- `brightness`: brightness in percent
- `contrast`: contrast in percent
- `flicker_reduction`: flicker reduction in percent
- `overscan`: overscan in percent
- `saturation`: saturation in percent
- `hue`: hue in percent

#### <a id="c-struct-drm_connector_hdmi_infoframe"></a>`struct drm_connector_hdmi_infoframe`

HDMI Infoframe container

**Definition**

```c
struct drm_connector_hdmi_infoframe {
    union hdmi_infoframe data;
    bool set;
};
```

**Members**

- `data`: HDMI Infoframe structure
- `set`: Is the content of **data** valid?

#### <a id="c-struct-drm_connector_state"></a>`struct drm_connector_state`

mutable connector state

**Definition**

```c
struct drm_connector_state {
    struct drm_connector *connector;
    struct drm_crtc *crtc;
    struct drm_encoder *best_encoder;
    enum drm_link_status link_status;
    struct drm_atomic_state *state;
    struct drm_crtc_commit *commit;
    struct drm_tv_connector_state tv;
    bool self_refresh_aware;
    enum hdmi_picture_aspect picture_aspect_ratio;
    unsigned int content_type;
    unsigned int hdcp_content_type;
    unsigned int scaling_mode;
    unsigned int content_protection;
    enum drm_colorspace colorspace;
    struct drm_writeback_job *writeback_job;
    u8 max_requested_bpc;
    u8 max_bpc;
    enum drm_privacy_screen_status privacy_screen_sw_state;
    struct drm_property_blob *hdr_output_metadata;
    struct drm_connector_hdmi_state hdmi;
};
```

**Members**

- `connector`: backpointer to the connector
- `crtc`: CRTC to connect connector to, NULL if disabled.

  Do not change this directly, use [`drm_atomic_set_crtc_for_connector()`](#c-drm_atomic_set_crtc_for_connector)
  instead.
- `best_encoder`: Used by the atomic helpers to select the encoder, through the
  [`drm_connector_helper_funcs.atomic_best_encoder`](/kernel/hardware/gpu/drm-kms-helpers.md#c-struct-drm_connector_helper_funcs) or
  [`drm_connector_helper_funcs.best_encoder`](/kernel/hardware/gpu/drm-kms-helpers.md#c-struct-drm_connector_helper_funcs) callbacks.

  This is also used in the atomic helpers to map encoders to their
  current and previous connectors, see
  [`drm_atomic_get_old_connector_for_encoder()`](#c-drm_atomic_get_old_connector_for_encoder) and
  [`drm_atomic_get_new_connector_for_encoder()`](#c-drm_atomic_get_new_connector_for_encoder).

  NOTE: Atomic drivers must fill this out (either themselves or through
  helpers), for otherwise the GETCONNECTOR and GETENCODER IOCTLs will
  not return correct data to userspace.
- `link_status`: Connector link_status to keep track of whether link is
  GOOD or BAD to notify userspace if retraining is necessary.
- `state`: backpointer to global drm_atomic_state
- `commit`: Tracks the pending commit to prevent use-after-free conditions.

  Is only set when **crtc** is NULL.
- `tv`: TV connector state
- `self_refresh_aware`: This tracks whether a connector is aware of the self refresh state.
  It should be set to true for those connector implementations which
  understand the self refresh state. This is needed since the crtc
  registers the self refresh helpers and it doesn't know if the
  connectors downstream have implemented self refresh entry/exit.

  Drivers should set this to true in atomic_check if they know how to
  handle self_refresh requests.
- `picture_aspect_ratio`: Connector property to control the
  HDMI infoframe aspect ratio setting.

  The `DRM_MODE_PICTURE_ASPECT_`\* values much match the
  values for `enum hdmi_picture_aspect`
- `content_type`: Connector property to control the
  HDMI infoframe content type setting.
  The `DRM_MODE_CONTENT_TYPE_`\* values much
  match the values.
- `hdcp_content_type`: Connector property to pass the type of
  protected content. This is most commonly used for HDCP.
- `scaling_mode`: Connector property to control the
  upscaling, mostly used for built-in panels.
- `content_protection`: Connector property to request content
  protection. This is most commonly used for HDCP.
- `colorspace`: State variable for Connector property to request
  colorspace change on Sink. This is most commonly used to switch
  to wider color gamuts like BT2020.
- `writeback_job`: Writeback job for writeback connectors

  Holds the framebuffer and out-fence for a writeback connector. As
  the writeback completion may be asynchronous to the normal commit
  cycle, the writeback job lifetime is managed separately from the
  normal atomic state by this object.

  See also: [`drm_writeback_queue_job()`](#c-drm_writeback_queue_job) and
  [`drm_writeback_signal_completion()`](#c-drm_writeback_signal_completion)
- `max_requested_bpc`: Connector property to limit the maximum bit
  depth of the pixels.
- `max_bpc`: Connector max_bpc based on the requested max_bpc property
  and the connector bpc limitations obtained from edid.
- `privacy_screen_sw_state`: See Standard Connector
  Properties
- `hdr_output_metadata`: DRM blob property for HDR output metadata
- `hdmi`: HDMI-related variable and properties. Filled by
  **drm_atomic_helper_connector_hdmi_check()**.

#### <a id="c-struct-drm_connector_cec_funcs"></a>`struct drm_connector_cec_funcs`

drm_hdmi_connector control functions

**Definition**

```c
struct drm_connector_cec_funcs {
    void (*phys_addr_invalidate)(struct drm_connector *connector);
    void (*phys_addr_set)(struct drm_connector *connector, u16 addr);
};
```

**Members**

- `phys_addr_invalidate`: mark CEC physical address as invalid

  The callback to mark CEC physical address as invalid, abstracting
  the operation.
- `phys_addr_set`: set CEC physical address

  The callback to set CEC physical address, abstracting the operation.

#### <a id="c-struct-drm_connector_infoframe_funcs"></a>`struct drm_connector_infoframe_funcs`

InfoFrame-related functions

**Definition**

```c
struct drm_connector_infoframe_funcs {
    int (*clear_infoframe)(struct drm_connector *connector);
    int (*write_infoframe)(struct drm_connector *connector, const u8 *buffer, size_t len);
};
```

**Members**

- `clear_infoframe`: This callback is invoked through
  **drm_atomic_helper_connector_hdmi_update_infoframes** during a
  commit to clear the infoframes into the hardware. It will be
  called once for each frame type to be disabled.

  The **clear_infoframe** callback is mandatory for AVI and HDMI-VS
  InfoFrame types.

  Returns:
  0 on success, a negative error code otherwise
- `write_infoframe`: This callback is invoked through
  **drm_atomic_helper_connector_hdmi_update_infoframes** during a
  commit to program the infoframes into the hardware. It will
  be called for every updated infoframe type.

  The **write_infoframe** callback is mandatory for AVI and HDMI-VS
  InfoFrame types.

  Returns:
  0 on success, a negative error code otherwise

#### <a id="c-struct-drm_connector_hdmi_funcs"></a>`struct drm_connector_hdmi_funcs`

drm_hdmi_connector control functions

**Definition**

```c
struct drm_connector_hdmi_funcs {
    enum drm_mode_status (*tmds_char_rate_valid)(const struct drm_connector *connector, const struct drm_display_mode *mode, unsigned long long tmds_rate);
    const struct drm_edid *(*read_edid)(struct drm_connector *connector);
    struct drm_connector_infoframe_funcs avi;
    struct drm_connector_infoframe_funcs hdmi;
    struct drm_connector_infoframe_funcs audio;
    struct drm_connector_infoframe_funcs hdr_drm;
    struct drm_connector_infoframe_funcs spd;
};
```

**Members**

- `tmds_char_rate_valid`: This callback is invoked at atomic_check time to figure out
  whether a particular TMDS character rate is supported by the
  driver.

  The **tmds_char_rate_valid** callback is optional.

  Returns:

  Either [`drm_mode_status.MODE_OK`](#c-enum-drm_mode_status) or one of the failure reasons
  in [`enum drm_mode_status`](#c-enum-drm_mode_status).
- `read_edid`: This callback is used by the framework as a replacement for reading
  the EDID from connector->ddc. It is still recommended to provide
  connector->ddc instead of implementing this callback. Returned EDID
  should be freed via the [`drm_edid_free()`](/kernel/hardware/gpu/drm-kms-helpers.md#c-drm_edid_free).

  The **read_edid** callback is optional.

  Returns:
  Valid EDID on success, NULL in case of failure.
- `avi`: Set of callbacks for handling the AVI InfoFrame. These callbacks are
  mandatory.
- `hdmi`: Set of callbacks for handling the HDMI Vendor-Specific InfoFrame.
  These callbacks are mandatory.
- `audio`: Set of callbacks for handling the Audio InfoFrame. These callbacks
  are optional, but they are required for drivers which use
  [`drm_atomic_helper_connector_hdmi_update_audio_infoframe()`](/kernel/hardware/gpu/drm-kms-helpers.md#c-drm_atomic_helper_connector_hdmi_update_audio_infoframe).
- `hdr_drm`: Set of callbacks for handling the HDR DRM InfoFrame. These callbacks
  are mandatory if HDR output is to be supported.
- `spd`: Set of callbacks for handling the SPD InfoFrame. These callbacks are
  optional.

#### <a id="c-struct-drm_connector_funcs"></a>`struct drm_connector_funcs`

control connectors on a given device

**Definition**

```c
struct drm_connector_funcs {
    int (*dpms)(struct drm_connector *connector, int mode);
    void (*reset)(struct drm_connector *connector);
    enum drm_connector_status (*detect)(struct drm_connector *connector, bool force);
    void (*force)(struct drm_connector *connector);
    int (*fill_modes)(struct drm_connector *connector, uint32_t max_width, uint32_t max_height);
    int (*set_property)(struct drm_connector *connector, struct drm_property *property, uint64_t val);
    int (*late_register)(struct drm_connector *connector);
    void (*early_unregister)(struct drm_connector *connector);
    void (*destroy)(struct drm_connector *connector);
    struct drm_connector_state *(*atomic_duplicate_state)(struct drm_connector *connector);
    void (*atomic_destroy_state)(struct drm_connector *connector, struct drm_connector_state *state);
    int (*atomic_set_property)(struct drm_connector *connector, struct drm_connector_state *state, struct drm_property *property, uint64_t val);
    int (*atomic_get_property)(struct drm_connector *connector, const struct drm_connector_state *state, struct drm_property *property, uint64_t *val);
    void (*atomic_print_state)(struct drm_printer *p, const struct drm_connector_state *state);
    void (*oob_hotplug_event)(struct drm_connector *connector, enum drm_connector_status status);
    void (*debugfs_init)(struct drm_connector *connector, struct dentry *root);
};
```

**Members**

- `dpms`: Legacy entry point to set the per-connector DPMS state. Legacy DPMS
  is exposed as a standard property on the connector, but diverted to
  this callback in the drm core. Note that atomic drivers don't
  implement the 4 level DPMS support on the connector any more, but
  instead only have an on/off "ACTIVE" property on the CRTC object.

  This hook is not used by atomic drivers, remapping of the legacy DPMS
  property is entirely handled in the DRM core.

  RETURNS:

  0 on success or a negative error code on failure.
- `reset`: Reset connector hardware and software state to off. This function isn't
  called by the core directly, only through [`drm_mode_config_reset()`](#c-drm_mode_config_reset).
  It's not a helper hook only for historical reasons.

  Atomic drivers can use [`drm_atomic_helper_connector_reset()`](/kernel/hardware/gpu/drm-kms-helpers.md#c-drm_atomic_helper_connector_reset) to reset
  atomic state using this hook.
- `detect`: Check to see if anything is attached to the connector. The parameter
  force is set to false whilst polling, true when checking the
  connector due to a user request. force can be used by the driver to
  avoid expensive, destructive operations during automated probing.

  This callback is optional, if not implemented the connector will be
  considered as always being attached.

  FIXME:

  Note that this hook is only called by the probe helper. It's not in
  the helper library vtable purely for historical reasons. The only DRM
  core entry point to probe connector state is **fill_modes**.

  Note that the helper library will already hold
  [`drm_mode_config.connection_mutex`](#c-struct-drm_mode_config). Drivers which need to grab additional
  locks to avoid races with concurrent modeset changes need to use
  [`drm_connector_helper_funcs.detect_ctx`](/kernel/hardware/gpu/drm-kms-helpers.md#c-struct-drm_connector_helper_funcs) instead.

  Also note that this callback can be called no matter the
  state the connector is in. Drivers that need the underlying
  device to be powered to perform the detection will first need
  to make sure it's been properly enabled.

  RETURNS:

  drm_connector_status indicating the connector's status.
- `force`: This function is called to update internal encoder state when the
  connector is forced to a certain state by userspace, either through
  the sysfs interfaces or on the kernel cmdline. In that case the
  **detect** callback isn't called.

  FIXME:

  Note that this hook is only called by the probe helper. It's not in
  the helper library vtable purely for historical reasons. The only DRM
  core entry point to probe connector state is **fill_modes**.
- `fill_modes`: Entry point for output detection and basic mode validation. The
  driver should reprobe the output if needed (e.g. when hotplug
  handling is unreliable), add all detected modes to [`drm_connector.modes`](#c-struct-drm_connector)
  and filter out any the device can't support in any configuration. It
  also needs to filter out any modes wider or higher than the
  parameters max_width and max_height indicate.

  The drivers must also prune any modes no longer valid from
  [`drm_connector.modes`](#c-struct-drm_connector). Furthermore it must update
  [`drm_connector.status`](#c-struct-drm_connector) and [`drm_connector.edid`](#c-struct-drm_connector).  If no EDID has been
  received for this output connector->edid must be NULL.

  Drivers using the probe helpers should use
  [`drm_helper_probe_single_connector_modes()`](/kernel/hardware/gpu/drm-kms-helpers.md#c-drm_helper_probe_single_connector_modes) to implement this
  function.

  RETURNS:

  The number of modes detected and filled into [`drm_connector.modes`](#c-struct-drm_connector).
- `set_property`: This is the legacy entry point to update a property attached to the
  connector.

  This callback is optional if the driver does not support any legacy
  driver-private properties. For atomic drivers it is not used because
  property handling is done entirely in the DRM core.

  RETURNS:

  0 on success or a negative error code on failure.
- `late_register`: This optional hook can be used to register additional userspace
  interfaces attached to the connector, light backlight control, i2c,
  DP aux or similar interfaces. It is called late in the driver load
  sequence from [`drm_connector_register()`](#c-drm_connector_register) when registering all the
  core drm connector interfaces. Everything added from this callback
  should be unregistered in the early_unregister callback.

  This is called while holding [`drm_connector.mutex`](#c-struct-drm_connector).

  Returns:

  0 on success, or a negative error code on failure.
- `early_unregister`: This optional hook should be used to unregister the additional
  userspace interfaces attached to the connector from
  `late_register()`. It is called from [`drm_connector_unregister()`](#c-drm_connector_unregister),
  early in the driver unload sequence to disable userspace access
  before data structures are torndown.

  This is called while holding [`drm_connector.mutex`](#c-struct-drm_connector).
- `destroy`: Clean up connector resources. This is called at driver unload time
  through [`drm_mode_config_cleanup()`](#c-drm_mode_config_cleanup). It can also be called at runtime
  when a connector is being hot-unplugged for drivers that support
  connector hotplugging (e.g. DisplayPort MST).
- `atomic_duplicate_state`: Duplicate the current atomic state for this connector and return it.
  The core and helpers guarantee that any atomic state duplicated with
  this hook and still owned by the caller (i.e. not transferred to the
  driver by calling [`drm_mode_config_funcs.atomic_commit`](#c-struct-drm_mode_config_funcs)) will be
  cleaned up by calling the **atomic_destroy_state** hook in this
  structure.

  This callback is mandatory for atomic drivers.

  Atomic drivers which don't subclass [`struct drm_connector_state`](#c-struct-drm_connector_state) should use
  [`drm_atomic_helper_connector_duplicate_state()`](/kernel/hardware/gpu/drm-kms-helpers.md#c-drm_atomic_helper_connector_duplicate_state). Drivers that subclass the
  state structure to extend it with driver-private state should use
  [`__drm_atomic_helper_connector_duplicate_state()`](/kernel/hardware/gpu/drm-kms-helpers.md#c-__drm_atomic_helper_connector_duplicate_state) to make sure shared state is
  duplicated in a consistent fashion across drivers.

  It is an error to call this hook before [`drm_connector.state`](#c-struct-drm_connector) has been
  initialized correctly.

  NOTE:

  If the duplicate state references refcounted resources this hook must
  acquire a reference for each of them. The driver must release these
  references again in **atomic_destroy_state**.

  RETURNS:

  Duplicated atomic state or NULL when the allocation failed.
- `atomic_destroy_state`: Destroy a state duplicated with **atomic_duplicate_state** and release
  or unreference all resources it references

  This callback is mandatory for atomic drivers.
- `atomic_set_property`: Decode a driver-private property value and store the decoded value
  into the passed-in state structure. Since the atomic core decodes all
  standardized properties (even for extensions beyond the core set of
  properties which might not be implemented by all drivers) this
  requires drivers to subclass the state structure.

  Such driver-private properties should really only be implemented for
  truly hardware/vendor specific state. Instead it is preferred to
  standardize atomic extension and decode the properties used to expose
  such an extension in the core.

  Do not call this function directly, use
  `drm_atomic_connector_set_property()` instead.

  This callback is optional if the driver does not support any
  driver-private atomic properties.

  NOTE:

  This function is called in the state assembly phase of atomic
  modesets, which can be aborted for any reason (including on
  userspace's request to just check whether a configuration would be
  possible). Drivers MUST NOT touch any persistent state (hardware or
  software) or data structures except the passed in **state** parameter.

  Also since userspace controls in which order properties are set this
  function must not do any input validation (since the state update is
  incomplete and hence likely inconsistent). Instead any such input
  validation must be done in the various atomic_check callbacks.

  RETURNS:

  0 if the property has been found, -EINVAL if the property isn't
  implemented by the driver (which shouldn't ever happen, the core only
  asks for properties attached to this connector). No other validation
  is allowed by the driver. The core already checks that the property
  value is within the range (integer, valid enum value, ...) the driver
  set when registering the property.
- `atomic_get_property`: Reads out the decoded driver-private property. This is used to
  implement the GETCONNECTOR IOCTL.

  Do not call this function directly, use
  `drm_atomic_connector_get_property()` instead.

  This callback is optional if the driver does not support any
  driver-private atomic properties.

  RETURNS:

  0 on success, -EINVAL if the property isn't implemented by the
  driver (which shouldn't ever happen, the core only asks for
  properties attached to this connector).
- `atomic_print_state`: If driver subclasses [`struct drm_connector_state`](#c-struct-drm_connector_state), it should implement
  this optional hook for printing additional driver specific state.

  Do not call this directly, use `drm_atomic_connector_print_state()`
  instead.
- `oob_hotplug_event`: This will get called when a hotplug-event for a drm-connector
  has been received from a source outside the display driver / device.
- `debugfs_init`: Allows connectors to create connector-specific debugfs files.

**Description**

Each CRTC may have one or more connectors attached to it.  The functions
below allow the core DRM code to control connectors, enumerate available modes,
etc.

#### <a id="c-struct-drm_cmdline_mode"></a>`struct drm_cmdline_mode`

DRM Mode passed through the kernel command-line

**Definition**

```c
struct drm_cmdline_mode {
    char name[DRM_DISPLAY_MODE_LEN];
    bool specified;
    bool refresh_specified;
    bool bpp_specified;
    unsigned int pixel_clock;
    int xres;
    int yres;
    int bpp;
    int refresh;
    bool rb;
    bool interlace;
    bool cvt;
    bool margins;
    enum drm_connector_force force;
    unsigned int rotation_reflection;
    enum drm_panel_orientation panel_orientation;
    struct drm_connector_tv_margins tv_margins;
    enum drm_connector_tv_mode tv_mode;
    bool tv_mode_specified;
};
```

**Members**

- `name`: Name of the mode.
- `specified`: Has a mode been read from the command-line?
- `refresh_specified`: Did the mode have a preferred refresh rate?
- `bpp_specified`: Did the mode have a preferred BPP?
- `pixel_clock`: Pixel Clock in kHz. Optional.
- `xres`: Active resolution on the X axis, in pixels.
- `yres`: Active resolution on the Y axis, in pixels.
- `bpp`: Bits per pixels for the mode.
- `refresh`: Refresh rate, in Hertz.
- `rb`: Do we need to use reduced blanking?
- `interlace`: The mode is interlaced.
- `cvt`: The timings will be calculated using the VESA Coordinated
  Video Timings instead of looking up the mode from a table.
- `margins`: Add margins to the mode calculation (1.8% of xres rounded
  down to 8 pixels and 1.8% of yres).
- `force`: Ignore the hotplug state of the connector, and force its
  state to one of the DRM_FORCE_* values.
- `rotation_reflection`: Initial rotation and reflection of the mode setup from the
  command line. See DRM_MODE_ROTATE_* and
  DRM_MODE_REFLECT_*. The only rotations supported are
  DRM_MODE_ROTATE_0 and DRM_MODE_ROTATE_180.
- `panel_orientation`: drm-connector "panel orientation" property override value,
  DRM_MODE_PANEL_ORIENTATION_UNKNOWN if not set.
- `tv_margins`: TV margins to apply to the mode.
- `tv_mode`: TV mode standard. See DRM_MODE_TV_MODE_*.
- `tv_mode_specified`: Did the mode have a preferred TV mode?

**Description**

Each connector can have an initial mode with additional options
passed through the kernel command line. This structure allows to
express those parameters and will be filled by the command-line
parser.

#### <a id="c-struct-drm_connector_hdmi_audio"></a>`struct drm_connector_hdmi_audio`

DRM gemeric HDMI Codec-related structure

**Definition**

```c
struct drm_connector_hdmi_audio {
    const struct drm_connector_hdmi_audio_funcs *funcs;
    struct platform_device *codec_pdev;
    struct mutex lock;
    void (*plugged_cb)(struct device *dev, bool plugged);
    struct device *plugged_cb_dev;
    bool last_state;
    int dai_port;
};
```

**Members**

- `funcs`: Implementation of the HDMI codec functionality to be used by the DRM
  HDMI Codec framework.
- `codec_pdev`: Platform device created to hold the HDMI Codec. It will be
  automatically unregistered during [`drm_connector_cleanup()`](#c-drm_connector_cleanup).
- `lock`: Mutex to protect **last_state**, **plugged_cb** and **plugged_cb_dev**.
- `plugged_cb`: Callback to be called when the HDMI sink get plugged to or unplugged
  from this connector. This is assigned by the framework when
  requested by the ASoC code.
- `plugged_cb_dev`: The data for **plugged_cb()**. It is being provided by the ASoC.
- `last_state`: Last plugged state recored by the framework. It is used to correctly
  report the state to **plugged_cb()**.
- `dai_port`: The port in DT that is used for the Codec DAI.

**Description**

HDMI drivers usually incorporate a HDMI Codec. This structure expresses the
generic HDMI Codec as used by the DRM HDMI Codec framework.

#### <a id="c-struct-drm_connector_cec"></a>`struct drm_connector_cec`

DRM Connector CEC-related structure

**Definition**

```c
struct drm_connector_cec {
    struct mutex mutex;
    const struct drm_connector_cec_funcs *funcs;
    void *data;
};
```

**Members**

- `mutex`: protects all fields in this structure.
- `funcs`: CEC Control Functions
- `data`: CEC implementation-specific data

#### <a id="c-struct-drm_connector"></a>`struct drm_connector`

central DRM connector control structure

**Definition**

```c
struct drm_connector {
        struct drm_device *dev;
        struct device *kdev;
        struct device_attribute *attr;
        struct fwnode_handle *fwnode;
        struct list_head head;
        struct list_head global_connector_list_entry;
        struct drm_mode_object base;
        char *name;
        struct mutex mutex;
        unsigned index;
        int connector_type;
        int connector_type_id;
        bool interlace_allowed;
        bool doublescan_allowed;
        bool stereo_allowed;
        bool ycbcr_420_allowed;
        enum drm_connector_registration_state registration_state;
        struct list_head modes;
        enum drm_connector_status status;
        struct list_head probed_modes;
        struct drm_display_info display_info;
        const struct drm_connector_funcs *funcs;
        struct drm_property_blob *edid_blob_ptr;
        struct drm_object_properties properties;
        struct drm_property *scaling_mode_property;
        struct drm_property *vrr_capable_property;
        struct drm_property *colorspace_property;
        struct drm_property_blob *path_blob_ptr;
        unsigned int max_bpc;
        struct drm_property *max_bpc_property;
        struct drm_privacy_screen *privacy_screen;
        struct notifier_block privacy_screen_notifier;
        struct drm_property *privacy_screen_sw_state_property;
        struct drm_property *privacy_screen_hw_state_property;
        struct drm_property *broadcast_rgb_property;
    #define DRM_CONNECTOR_POLL_HPD (1 << 0);
    #define DRM_CONNECTOR_POLL_CONNECT (1 << 1);
    #define DRM_CONNECTOR_POLL_DISCONNECT (1 << 2);
        uint8_t polled;
        int dpms;
        const struct drm_connector_helper_funcs *helper_private;
        struct drm_cmdline_mode cmdline_mode;
        enum drm_connector_force force;
        const struct drm_edid *edid_override;
        struct mutex edid_override_mutex;
        u64 epoch_counter;
        u32 possible_encoders;
        struct drm_encoder *encoder;
    #define MAX_ELD_BYTES   128;
        uint8_t eld[MAX_ELD_BYTES];
        struct mutex eld_mutex;
        bool latency_present[2];
        int video_latency[2];
        int audio_latency[2];
        struct i2c_adapter *ddc;
        int null_edid_counter;
        unsigned bad_edid_counter;
        bool edid_corrupt;
        u8 real_edid_checksum;
        struct dentry *debugfs_entry;
        struct drm_connector_state *state;
        struct drm_property_blob *tile_blob_ptr;
        bool has_tile;
        struct drm_tile_group *tile_group;
        bool tile_is_single_monitor;
        uint8_t num_h_tile, num_v_tile;
        uint8_t tile_h_loc, tile_v_loc;
        uint16_t tile_h_size, tile_v_size;
        struct llist_node free_node;
        struct drm_connector_hdmi hdmi;
        struct drm_connector_hdmi_audio hdmi_audio;
        struct drm_connector_cec cec;
};
```

**Members**

- `dev`: parent DRM device
- `kdev`: kernel device for sysfs attributes
- `attr`: sysfs attributes
- `fwnode`: associated fwnode supplied by platform firmware

  Drivers can set this to associate a fwnode with a connector, drivers
  are expected to get a reference on the fwnode when setting this.
  [`drm_connector_cleanup()`](#c-drm_connector_cleanup) will call `fwnode_handle_put()` on this.
- `head`: List of all connectors on a **dev**, linked from
  [`drm_mode_config.connector_list`](#c-struct-drm_mode_config). Protected by
  [`drm_mode_config.connector_list_lock`](#c-struct-drm_mode_config), but please only use
  [`drm_connector_list_iter`](#c-struct-drm_connector_list_iter) to walk this list.
- `global_connector_list_entry`: Connector entry in the global connector-list, used by
  `drm_connector_find_by_fwnode()`.
- `base`: base KMS object
- `name`: human readable name, can be overwritten by the driver
- `mutex`: Lock for general connector state, but currently only protects
  **registered**. Most of the connector state is still protected by
  [`drm_mode_config.mutex`](#c-struct-drm_mode_config).
- `index`: Compacted connector index, which matches the position inside
  the mode_config.list for drivers not supporting hot-add/removing. Can
  be used as an array index. It is invariant over the lifetime of the
  connector.
- `connector_type`: one of the DRM_MODE_CONNECTOR_\<foo> types from drm_mode.h
- `connector_type_id`: index into connector type enum
- `interlace_allowed`: Can this connector handle interlaced modes? Only used by
  [`drm_helper_probe_single_connector_modes()`](/kernel/hardware/gpu/drm-kms-helpers.md#c-drm_helper_probe_single_connector_modes) for mode filtering.
- `doublescan_allowed`: Can this connector handle doublescan? Only used by
  [`drm_helper_probe_single_connector_modes()`](/kernel/hardware/gpu/drm-kms-helpers.md#c-drm_helper_probe_single_connector_modes) for mode filtering.
- `stereo_allowed`: Can this connector handle stereo modes? Only used by
  [`drm_helper_probe_single_connector_modes()`](/kernel/hardware/gpu/drm-kms-helpers.md#c-drm_helper_probe_single_connector_modes) for mode filtering.
- `ycbcr_420_allowed`: This bool indicates if this connector is
  capable of handling YCBCR 420 output. While parsing the EDID
  blocks it's very helpful to know if the source is capable of
  handling YCBCR 420 outputs.
- `registration_state`: Is this connector initializing, exposed
  (registered) with userspace, or unregistered?

  Protected by **mutex**.
- `modes`: Modes available on this connector (from `fill_modes()` + user).
  Protected by [`drm_mode_config.mutex`](#c-struct-drm_mode_config).
- `status`: One of the drm_connector_status enums (connected, not, or unknown).
  Protected by [`drm_mode_config.mutex`](#c-struct-drm_mode_config).
- `probed_modes`: These are modes added by probing with DDC or the BIOS, before
  filtering is applied. Used by the probe helpers. Protected by
  [`drm_mode_config.mutex`](#c-struct-drm_mode_config).
- `display_info`: Display information is filled from EDID information
  when a display is detected. For non hot-pluggable displays such as
  flat panels in embedded systems, the driver should initialize the
  [`drm_display_info.width_mm`](#c-struct-drm_display_info) and [`drm_display_info.height_mm`](#c-struct-drm_display_info) fields
  with the physical size of the display.

  Protected by [`drm_mode_config.mutex`](#c-struct-drm_mode_config).
- `funcs`: connector control functions
- `edid_blob_ptr`: DRM property containing EDID if present. Protected by
  [`drm_mode_config.mutex`](#c-struct-drm_mode_config).

  This must be updated only by calling [`drm_edid_connector_update()`](/kernel/hardware/gpu/drm-kms-helpers.md#c-drm_edid_connector_update) or
  [`drm_connector_update_edid_property()`](/kernel/hardware/gpu/drm-kms-helpers.md#c-drm_connector_update_edid_property).

  This must not be used by drivers directly.
- `properties`: property tracking for this connector
- `scaling_mode_property`: Optional atomic property to control the
  upscaling. See [`drm_connector_attach_content_protection_property()`](/kernel/hardware/gpu/drm-kms-helpers.md#c-drm_connector_attach_content_protection_property).
- `vrr_capable_property`: Optional property to help userspace
  query hardware support for variable refresh rate on a connector.
  connector. Drivers can add the property to a connector by
  calling [`drm_connector_attach_vrr_capable_property()`](#c-drm_connector_attach_vrr_capable_property).

  This should be updated only by calling
  [`drm_connector_set_vrr_capable_property()`](#c-drm_connector_set_vrr_capable_property).
- `colorspace_property`: Connector property to set the suitable
  colorspace supported by the sink.
- `path_blob_ptr`: DRM blob property data for the DP MST path property. This should only
  be updated by calling [`drm_connector_set_path_property()`](#c-drm_connector_set_path_property).
- `max_bpc`: Maximum bits per color channel the connector supports.
- `max_bpc_property`: Default connector property for the max bpc to be
  driven out of the connector.
- `privacy_screen`: drm_privacy_screen for this connector, or NULL.
- `privacy_screen_notifier`: privacy-screen notifier_block
- `privacy_screen_sw_state_property`: Optional atomic property for the
  connector to control the integrated privacy screen.
- `privacy_screen_hw_state_property`: Optional atomic property for the
  connector to report the actual integrated privacy screen state.
- `broadcast_rgb_property`: Connector property to set the
  Broadcast RGB selection to output with.
- `polled`: Connector polling mode, a combination of

  - DRM_CONNECTOR_POLL_HPD:
    The connector generates hotplug events and doesn't need to be
    periodically polled. The CONNECT and DISCONNECT flags must not
    be set together with the HPD flag.

  - DRM_CONNECTOR_POLL_CONNECT:
    Periodically poll the connector for connection.

  - DRM_CONNECTOR_POLL_DISCONNECT:
    Periodically poll the connector for disconnection, without
    causing flickering even when the connector is in use. DACs should
    rarely do this without a lot of testing.

  Set to 0 for connectors that don't support connection status
  discovery.
- `dpms`: Current dpms state. For legacy drivers the
  [`drm_connector_funcs.dpms`](#c-struct-drm_connector_funcs) callback must update this. For atomic
  drivers, this is handled by the core atomic code, and drivers must
  only take [`drm_crtc_state.active`](#c-struct-drm_crtc_state) into account.
- `helper_private`: mid-layer private data
- `cmdline_mode`: mode line parsed from the kernel cmdline for this connector
- `force`: a DRM_FORCE_\<foo> state for forced mode sets
- `edid_override`: Override EDID set via debugfs.

  Do not modify or access outside of the drm_edid_override_* family of
  functions.
- `edid_override_mutex`: Protect access to edid_override.
- `epoch_counter`: used to detect any other changes in connector, besides status
- `possible_encoders`: Bit mask of encoders that can drive this
  connector, [`drm_encoder_index()`](#c-drm_encoder_index) determines the index into the bitfield
  and the bits are set with [`drm_connector_attach_encoder()`](#c-drm_connector_attach_encoder).
- `encoder`: Currently bound encoder driving this connector, if any.
  Only really meaningful for non-atomic drivers. Atomic drivers should
  instead look at [`drm_connector_state.best_encoder`](#c-struct-drm_connector_state), and in case they
  need the CRTC driving this output, [`drm_connector_state.crtc`](#c-struct-drm_connector_state).
- `eld`: EDID-like data, if present, protected by **eld_mutex**
- `eld_mutex`: protection for concurrenct access to **eld**
- `latency_present`: AV delay info from ELD, if found
- `video_latency`: Video latency info from ELD, if found.
  \[0\]: progressive, \[1\]: interlaced
- `audio_latency`: audio latency info from ELD, if found
  \[0\]: progressive, \[1\]: interlaced
- `ddc`: associated ddc adapter.
  A connector usually has its associated ddc adapter. If a driver uses
  this field, then an appropriate symbolic link is created in connector
  sysfs directory to make it easy for the user to tell which i2c
  adapter is for a particular display.

  The field should be set by calling [`drm_connector_init_with_ddc()`](#c-drm_connector_init_with_ddc).
- `null_edid_counter`: track sinks that give us all zeros for the EDID.
  Needed to workaround some HW bugs where we get all 0s
- `bad_edid_counter`: track sinks that give us an EDID with invalid checksum
- `edid_corrupt`: Indicates whether the last read EDID was corrupt. Used
  in Displayport compliance testing - Displayport Link CTS Core 1.2
  rev1.1 4.2.2.6
- `real_edid_checksum`: real edid checksum for corrupted edid block.
  Required in Displayport 1.4 compliance testing
  rev1.1 4.2.2.6
- `debugfs_entry`: debugfs directory for this connector
- `state`: Current atomic state for this connector.

  This is protected by [`drm_mode_config.connection_mutex`](#c-struct-drm_mode_config). Note that
  nonblocking atomic commits access the current connector state without
  taking locks. Either by going through the [`struct drm_atomic_state`](#c-struct-drm_atomic_state)
  pointers, see [`for_each_oldnew_connector_in_state()`](#c-for_each_oldnew_connector_in_state),
  [`for_each_old_connector_in_state()`](#c-for_each_old_connector_in_state) and
  [`for_each_new_connector_in_state()`](#c-for_each_new_connector_in_state). Or through careful ordering of
  atomic commit operations as implemented in the atomic helpers, see
  [`struct drm_crtc_commit`](#c-struct-drm_crtc_commit).
- `tile_blob_ptr`: DRM blob property data for the tile property (used mostly by DP MST).
  This is meant for screens which are driven through separate display
  pipelines represented by [`drm_crtc`](#c-struct-drm_crtc), which might not be running with
  genlocked clocks. For tiled panels which are genlocked, like
  dual-link LVDS or dual-link DSI, the driver should try to not expose
  the tiling and virtualize both [`drm_crtc`](#c-struct-drm_crtc) and [`drm_plane`](#c-struct-drm_plane) if needed.

  This should only be updated by calling
  [`drm_connector_set_tile_property()`](#c-drm_connector_set_tile_property).
- `has_tile`: is this connector connected to a tiled monitor
- `tile_group`: tile group for the connected monitor
- `tile_is_single_monitor`: whether the tile is one monitor housing
- `num_h_tile`: number of horizontal tiles in the tile group
- `num_v_tile`: number of vertical tiles in the tile group
- `tile_h_loc`: horizontal location of this tile
- `tile_v_loc`: vertical location of this tile
- `tile_h_size`: horizontal size of this tile.
- `tile_v_size`: vertical size of this tile.
- `free_node`: List used only by [`drm_connector_list_iter`](#c-struct-drm_connector_list_iter) to be able to clean up a
  connector from any context, in conjunction with
  [`drm_mode_config.connector_free_work`](#c-struct-drm_mode_config).
- `hdmi`: HDMI-related variable and properties.
- `hdmi_audio`: HDMI codec properties and non-DRM state.
- `cec`: CEC-related data.

**Description**

Each connector may be connected to one or more CRTCs, or may be clonable by
another connector if they can share a CRTC.  Each connector also has a specific
position in the broader display (referred to as a 'screen' though it could
span multiple monitors).

#### <a id="c-drm_connector_lookup"></a>`drm_connector_lookup()`

```c
struct drm_connector * drm_connector_lookup(struct drm_device *dev, struct drm_file *file_priv, uint32_t id)
```

lookup connector object

**Parameters**

- `struct drm_device *dev`: DRM device
- `struct drm_file *file_priv`: drm file to check for lease against.
- `uint32_t id`: connector object id

**Description**

This function looks up the connector object specified by id
add takes a reference to it.

#### <a id="c-drm_connector_get"></a>`drm_connector_get()`

```c
void drm_connector_get(struct drm_connector *connector)
```

acquire a connector reference

**Parameters**

- `struct drm_connector *connector`: DRM connector

**Description**

This function increments the connector's refcount.

#### <a id="c-drm_connector_put"></a>`drm_connector_put()`

```c
void drm_connector_put(struct drm_connector *connector)
```

release a connector reference

**Parameters**

- `struct drm_connector *connector`: DRM connector

**Description**

This function decrements the connector's reference count and frees the
object if the reference count drops to zero.

#### <a id="c-drm_connector_is_unregistered"></a>`drm_connector_is_unregistered()`

```c
bool drm_connector_is_unregistered(struct drm_connector *connector)
```

has the connector been unregistered from userspace?

**Parameters**

- `struct drm_connector *connector`: DRM connector

**Description**

Checks whether or not **connector** has been unregistered from userspace.

**Return**

True if the connector was unregistered, false if the connector is
registered or has not yet been registered with userspace.

#### <a id="c-struct-drm_tile_group"></a>`struct drm_tile_group`

Tile group metadata

**Definition**

```c
struct drm_tile_group {
    struct kref refcount;
    struct drm_device *dev;
    int id;
    u8 group_data[8];
};
```

**Members**

- `refcount`: reference count
- `dev`: DRM device
- `id`: tile group id exposed to userspace
- `group_data`: Sink-private data identifying this group

**Description**

**group_data** corresponds to displayid vend/prod/serial for external screens
with an EDID.

#### <a id="c-struct-drm_connector_list_iter"></a>`struct drm_connector_list_iter`

connector_list iterator

**Definition**

```c
struct drm_connector_list_iter {
};
```

**Description**

This iterator tracks state needed to be able to walk the connector_list
within struct drm_mode_config. Only use together with
[`drm_connector_list_iter_begin()`](#c-drm_connector_list_iter_begin), [`drm_connector_list_iter_end()`](#c-drm_connector_list_iter_end) and
[`drm_connector_list_iter_next()`](#c-drm_connector_list_iter_next) respectively the convenience macro
[`drm_for_each_connector_iter()`](#c-drm_for_each_connector_iter).

Note that the return value of [`drm_connector_list_iter_next()`](#c-drm_connector_list_iter_next) is only valid
up to the next [`drm_connector_list_iter_next()`](#c-drm_connector_list_iter_next) or
[`drm_connector_list_iter_end()`](#c-drm_connector_list_iter_end) call. If you want to use the connector later,
then you need to grab your own reference first using [`drm_connector_get()`](#c-drm_connector_get).

#### <a id="c-drm_for_each_connector_iter"></a>`drm_for_each_connector_iter()`

```c
drm_for_each_connector_iter(connector, iter)
```

connector_list iterator macro

**Parameters**

- `connector`: [`struct drm_connector`](#c-struct-drm_connector) pointer used as cursor
- `iter`: [`struct drm_connector_list_iter`](#c-struct-drm_connector_list_iter)

**Description**

Note that **connector** is only valid within the list body, if you want to use
**connector** after calling [`drm_connector_list_iter_end()`](#c-drm_connector_list_iter_end) then you need to grab
your own reference first using [`drm_connector_get()`](#c-drm_connector_get).

#### <a id="c-drm_connector_for_each_possible_encoder"></a>`drm_connector_for_each_possible_encoder()`

```c
drm_connector_for_each_possible_encoder(connector, encoder)
```

iterate connector's possible encoders

**Parameters**

- `connector`: [`struct drm_connector`](#c-struct-drm_connector) pointer
- `encoder`: [`struct drm_encoder`](#c-struct-drm_encoder) pointer used as cursor



#### <a id="c-drm_get_connector_type_name"></a>`drm_get_connector_type_name()`

```c
const char * drm_get_connector_type_name(unsigned int type)
```

return a string for connector type

**Parameters**

- `unsigned int type`: The connector type (DRM_MODE_CONNECTOR_*)

**Return**

the name of the connector type, or NULL if the type is not valid.

#### <a id="c-drm_connector_init"></a>`drm_connector_init()`

```c
int drm_connector_init(struct drm_device *dev, struct drm_connector *connector, const struct drm_connector_funcs *funcs, int connector_type)
```

Init a preallocated connector

**Parameters**

- `struct drm_device *dev`: DRM device
- `struct drm_connector *connector`: the connector to init
- `const struct drm_connector_funcs *funcs`: callbacks for this connector
- `int connector_type`: user visible type of the connector

**Description**

Initialises a preallocated connector. Connectors should be
subclassed as part of driver connector objects.

At driver unload time the driver's [`drm_connector_funcs.destroy`](#c-struct-drm_connector_funcs) hook
should call [`drm_connector_cleanup()`](#c-drm_connector_cleanup) and free the connector structure.
The connector structure should not be allocated with `devm_kzalloc()`.

**Note**

consider using [`drmm_connector_init()`](#c-drmm_connector_init) instead of
[`drm_connector_init()`](#c-drm_connector_init) to let the DRM managed resource infrastructure
take care of cleanup and deallocation.

**Return**

Zero on success, error code on failure.

#### <a id="c-drm_connector_dynamic_init"></a>`drm_connector_dynamic_init()`

```c
int drm_connector_dynamic_init(struct drm_device *dev, struct drm_connector *connector, const struct drm_connector_funcs *funcs, int connector_type, struct i2c_adapter *ddc)
```

Init a preallocated dynamic connector

**Parameters**

- `struct drm_device *dev`: DRM device
- `struct drm_connector *connector`: the connector to init
- `const struct drm_connector_funcs *funcs`: callbacks for this connector
- `int connector_type`: user visible type of the connector
- `struct i2c_adapter *ddc`: pointer to the associated ddc adapter

**Description**

Initialises a preallocated dynamic connector. Connectors should be
subclassed as part of driver connector objects. The connector
structure should not be allocated with `devm_kzalloc()`.

Drivers should call this for dynamic connectors which can be hotplugged
after [`drm_dev_register()`](/kernel/hardware/gpu/drm-internals.md#c-drm_dev_register) has been called already, e.g. DP MST connectors.
For all other - static - connectors, drivers should call one of the
drm_connector_init*()/drmm_connector_init*() functions.

After calling this function the drivers must call
[`drm_connector_dynamic_register()`](#c-drm_connector_dynamic_register).

To remove the connector the driver must call [`drm_connector_unregister()`](#c-drm_connector_unregister)
followed by [`drm_connector_put()`](#c-drm_connector_put). Putting the last reference will call the
driver's [`drm_connector_funcs.destroy`](#c-struct-drm_connector_funcs) hook, which in turn must call
[`drm_connector_cleanup()`](#c-drm_connector_cleanup) and free the connector structure.

**Return**

Zero on success, error code on failure.

#### <a id="c-drm_connector_init_with_ddc"></a>`drm_connector_init_with_ddc()`

```c
int drm_connector_init_with_ddc(struct drm_device *dev, struct drm_connector *connector, const struct drm_connector_funcs *funcs, int connector_type, struct i2c_adapter *ddc)
```

Init a preallocated connector

**Parameters**

- `struct drm_device *dev`: DRM device
- `struct drm_connector *connector`: the connector to init
- `const struct drm_connector_funcs *funcs`: callbacks for this connector
- `int connector_type`: user visible type of the connector
- `struct i2c_adapter *ddc`: pointer to the associated ddc adapter

**Description**

Initialises a preallocated connector. Connectors should be
subclassed as part of driver connector objects.

At driver unload time the driver's [`drm_connector_funcs.destroy`](#c-struct-drm_connector_funcs) hook
should call [`drm_connector_cleanup()`](#c-drm_connector_cleanup) and free the connector structure.
The connector structure should not be allocated with `devm_kzalloc()`.

Ensures that the ddc field of the connector is correctly set.

**Note**

consider using [`drmm_connector_init()`](#c-drmm_connector_init) instead of
[`drm_connector_init_with_ddc()`](#c-drm_connector_init_with_ddc) to let the DRM managed resource
infrastructure take care of cleanup and deallocation.

**Return**

Zero on success, error code on failure.

#### <a id="c-drmm_connector_init"></a>`drmm_connector_init()`

```c
int drmm_connector_init(struct drm_device *dev, struct drm_connector *connector, const struct drm_connector_funcs *funcs, int connector_type, struct i2c_adapter *ddc)
```

Init a preallocated connector

**Parameters**

- `struct drm_device *dev`: DRM device
- `struct drm_connector *connector`: the connector to init
- `const struct drm_connector_funcs *funcs`: callbacks for this connector
- `int connector_type`: user visible type of the connector
- `struct i2c_adapter *ddc`: optional pointer to the associated ddc adapter

**Description**

Initialises a preallocated connector. Connectors should be
subclassed as part of driver connector objects.

Cleanup is automatically handled with a call to
[`drm_connector_cleanup()`](#c-drm_connector_cleanup) in a DRM-managed action.

The connector structure should be allocated with [`drmm_kzalloc()`](/kernel/hardware/gpu/drm-internals.md#c-drmm_kzalloc).

The **drm_connector_funcs.destroy** hook must be NULL.

**Return**

Zero on success, error code on failure.

#### <a id="c-drmm_connector_hdmi_init"></a>`drmm_connector_hdmi_init()`

```c
int drmm_connector_hdmi_init(struct drm_device *dev, struct drm_connector *connector, const char *vendor, const char *product, const struct drm_connector_funcs *funcs, const struct drm_connector_hdmi_funcs *hdmi_funcs, int connector_type, struct i2c_adapter *ddc, unsigned long supported_formats, unsigned int max_bpc)
```

Init a preallocated HDMI connector

**Parameters**

- `struct drm_device *dev`: DRM device
- `struct drm_connector *connector`: A pointer to the HDMI connector to init
- `const char *vendor`: HDMI Controller Vendor name
- `const char *product`: HDMI Controller Product name
- `const struct drm_connector_funcs *funcs`: callbacks for this connector
- `const struct drm_connector_hdmi_funcs *hdmi_funcs`: HDMI-related callbacks for this connector
- `int connector_type`: user visible type of the connector
- `struct i2c_adapter *ddc`: optional pointer to the associated ddc adapter
- `unsigned long supported_formats`: Bitmask of **hdmi_colorspace** listing supported output formats
- `unsigned int max_bpc`: Maximum bits per char the HDMI connector supports

**Description**

Initialises a preallocated HDMI connector. Connectors can be
subclassed as part of driver connector objects.

Cleanup is automatically handled with a call to
[`drm_connector_cleanup()`](#c-drm_connector_cleanup) in a DRM-managed action.

The connector structure should be allocated with [`drmm_kzalloc()`](/kernel/hardware/gpu/drm-internals.md#c-drmm_kzalloc).

The **drm_connector_funcs.destroy** hook must be NULL.

**Return**

Zero on success, error code on failure.

#### <a id="c-drm_connector_attach_edid_property"></a>`drm_connector_attach_edid_property()`

```c
void drm_connector_attach_edid_property(struct drm_connector *connector)
```

attach edid property.

**Parameters**

- `struct drm_connector *connector`: the connector

**Description**

Some connector types like DRM_MODE_CONNECTOR_VIRTUAL do not get a
edid property attached by default.  This function can be used to
explicitly enable the edid property in these cases.

#### <a id="c-drm_connector_attach_encoder"></a>`drm_connector_attach_encoder()`

```c
int drm_connector_attach_encoder(struct drm_connector *connector, struct drm_encoder *encoder)
```

attach a connector to an encoder

**Parameters**

- `struct drm_connector *connector`: connector to attach
- `struct drm_encoder *encoder`: encoder to attach **connector** to

**Description**

This function links up a connector to an encoder. Note that the routing
restrictions between encoders and crtcs are exposed to userspace through the
possible_clones and possible_crtcs bitmasks.

**Return**

Zero on success, negative errno on failure.

#### <a id="c-drm_connector_has_possible_encoder"></a>`drm_connector_has_possible_encoder()`

```c
bool drm_connector_has_possible_encoder(struct drm_connector *connector, struct drm_encoder *encoder)
```

check if the connector and encoder are associated with each other

**Parameters**

- `struct drm_connector *connector`: the connector
- `struct drm_encoder *encoder`: the encoder

**Return**

True if **encoder** is one of the possible encoders for **connector**.

#### <a id="c-drm_connector_cec_phys_addr_invalidate"></a>`drm_connector_cec_phys_addr_invalidate()`

```c
void drm_connector_cec_phys_addr_invalidate(struct drm_connector *connector)
```

invalidate CEC physical address

**Parameters**

- `struct drm_connector *connector`: connector undergoing CEC operation

**Description**

Invalidated CEC physical address set for this DRM connector.

#### <a id="c-drm_connector_cec_phys_addr_set"></a>`drm_connector_cec_phys_addr_set()`

```c
void drm_connector_cec_phys_addr_set(struct drm_connector *connector)
```

propagate CEC physical address

**Parameters**

- `struct drm_connector *connector`: connector undergoing CEC operation

**Description**

Propagate CEC physical address from the display_info to this DRM connector.

#### <a id="c-drm_connector_cleanup"></a>`drm_connector_cleanup()`

```c
void drm_connector_cleanup(struct drm_connector *connector)
```

cleans up an initialised connector

**Parameters**

- `struct drm_connector *connector`: connector to cleanup

**Description**

Cleans up the connector but doesn't free the object.

#### <a id="c-drm_connector_register"></a>`drm_connector_register()`

```c
int drm_connector_register(struct drm_connector *connector)
```

register a connector

**Parameters**

- `struct drm_connector *connector`: the connector to register

**Description**

Register userspace interfaces for a connector. Drivers shouldn't call this
function. Static connectors will be registered automatically by DRM core
from [`drm_dev_register()`](/kernel/hardware/gpu/drm-internals.md#c-drm_dev_register), dynamic connectors (MST) should be registered by
drivers calling [`drm_connector_dynamic_register()`](#c-drm_connector_dynamic_register).

When the connector is no longer available, callers must call
[`drm_connector_unregister()`](#c-drm_connector_unregister).

**Note**

Existing uses of this function in drivers should be a nop already and
are scheduled to be removed.

**Return**

Zero on success, error code on failure.

#### <a id="c-drm_connector_dynamic_register"></a>`drm_connector_dynamic_register()`

```c
int drm_connector_dynamic_register(struct drm_connector *connector)
```

register a dynamic connector

**Parameters**

- `struct drm_connector *connector`: the connector to register

**Description**

Register userspace interfaces for a connector. Only call this for connectors
initialized by calling [`drm_connector_dynamic_init()`](#c-drm_connector_dynamic_init). All other connectors
will be registered automatically when calling [`drm_dev_register()`](/kernel/hardware/gpu/drm-internals.md#c-drm_dev_register).

When the connector is no longer available the driver must call
[`drm_connector_unregister()`](#c-drm_connector_unregister).

**Return**

Zero on success, error code on failure.

#### <a id="c-drm_connector_unregister"></a>`drm_connector_unregister()`

```c
void drm_connector_unregister(struct drm_connector *connector)
```

unregister a connector

**Parameters**

- `struct drm_connector *connector`: the connector to unregister

**Description**

Unregister userspace interfaces for a connector. Drivers should call this
for dynamic connectors (MST) only, which were registered explicitly by
calling [`drm_connector_dynamic_register()`](#c-drm_connector_dynamic_register). All other - static - connectors
will be unregistered automatically by DRM core and drivers shouldn't call
this function for those.

**Note**

Existing uses of this function in drivers for static connectors
should be a nop already and are scheduled to be removed.

#### <a id="c-drm_get_connector_status_name"></a>`drm_get_connector_status_name()`

```c
const char * drm_get_connector_status_name(enum drm_connector_status status)
```

return a string for connector status

**Parameters**

- `enum drm_connector_status status`: connector status to compute name of

**Description**

In contrast to the other drm_get_*_name functions this one here returns a
const pointer and hence is threadsafe.

**Return**

connector status string

#### <a id="c-drm_connector_list_iter_begin"></a>`drm_connector_list_iter_begin()`

```c
void drm_connector_list_iter_begin(struct drm_device *dev, struct drm_connector_list_iter *iter)
```

initialize a connector_list iterator

**Parameters**

- `struct drm_device *dev`: DRM device
- `struct drm_connector_list_iter *iter`: connector_list iterator

**Description**

Sets **iter** up to walk the [`drm_mode_config.connector_list`](#c-struct-drm_mode_config) of **dev**. **iter**
must always be cleaned up again by calling [`drm_connector_list_iter_end()`](#c-drm_connector_list_iter_end).
Iteration itself happens using [`drm_connector_list_iter_next()`](#c-drm_connector_list_iter_next) or
[`drm_for_each_connector_iter()`](#c-drm_for_each_connector_iter).

#### <a id="c-drm_connector_list_iter_next"></a>`drm_connector_list_iter_next()`

```c
struct drm_connector * drm_connector_list_iter_next(struct drm_connector_list_iter *iter)
```

return next connector

**Parameters**

- `struct drm_connector_list_iter *iter`: connector_list iterator

**Return**

the next connector for **iter**, or NULL when the list walk has
completed.

#### <a id="c-drm_connector_list_iter_end"></a>`drm_connector_list_iter_end()`

```c
void drm_connector_list_iter_end(struct drm_connector_list_iter *iter)
```

tear down a connector_list iterator

**Parameters**

- `struct drm_connector_list_iter *iter`: connector_list iterator

**Description**

Tears down **iter** and releases any resources (like [`drm_connector`](#c-struct-drm_connector) references)
acquired while walking the list. This must always be called, both when the
iteration completes fully or when it was aborted without walking the entire
list.

#### <a id="c-drm_get_subpixel_order_name"></a>`drm_get_subpixel_order_name()`

```c
const char * drm_get_subpixel_order_name(enum subpixel_order order)
```

return a string for a given subpixel enum

**Parameters**

- `enum subpixel_order order`: enum of subpixel_order

**Description**

Note you could abuse this and return something out of bounds, but that
would be a caller error.  No unscrubbed user data should make it here.

**Return**

string describing an enumerated subpixel property

#### <a id="c-drm_display_info_set_bus_formats"></a>`drm_display_info_set_bus_formats()`

```c
int drm_display_info_set_bus_formats(struct drm_display_info *info, const u32 *formats, unsigned int num_formats)
```

set the supported bus formats

**Parameters**

- `struct drm_display_info *info`: display info to store bus formats in
- `const u32 *formats`: array containing the supported bus formats
- `unsigned int num_formats`: the number of entries in the fmts array

**Description**

Store the supported bus formats in display info structure.
See MEDIA_BUS_FMT_* definitions in include/uapi/linux/media-bus-format.h for
a full list of available formats.

**Return**

0 on success or a negative error code on failure.

#### <a id="c-drm_get_tv_mode_from_name"></a>`drm_get_tv_mode_from_name()`

```c
int drm_get_tv_mode_from_name(const char *name, size_t len)
```

Translates a TV mode name into its enum value

**Parameters**

- `const char *name`: TV Mode name we want to convert
- `size_t len`: Length of **name**

**Description**

Translates **name** into an enum drm_connector_tv_mode.

**Return**

the enum value on success, a negative errno otherwise.

#### <a id="c-drm_mode_create_dvi_i_properties"></a>`drm_mode_create_dvi_i_properties()`

```c
int drm_mode_create_dvi_i_properties(struct drm_device *dev)
```

create DVI-I specific connector properties

**Parameters**

- `struct drm_device *dev`: DRM device

**Description**

Called by a driver the first time a DVI-I connector is made.

**Return**

`0`

#### <a id="c-drm_connector_attach_dp_subconnector_property"></a>`drm_connector_attach_dp_subconnector_property()`

```c
void drm_connector_attach_dp_subconnector_property(struct drm_connector *connector)
```

create subconnector property for DP

**Parameters**

- `struct drm_connector *connector`: drm_connector to attach property

**Description**

Called by a driver when DP connector is created.

#### <a id="c-drm_connector_attach_content_type_property"></a>`drm_connector_attach_content_type_property()`

```c
int drm_connector_attach_content_type_property(struct drm_connector *connector)
```

attach content-type property

**Parameters**

- `struct drm_connector *connector`: connector to attach content type property on.

**Description**

Called by a driver the first time a HDMI connector is made.

**Return**

`0`

#### <a id="c-drm_connector_attach_tv_margin_properties"></a>`drm_connector_attach_tv_margin_properties()`

```c
void drm_connector_attach_tv_margin_properties(struct drm_connector *connector)
```

attach TV connector margin properties

**Parameters**

- `struct drm_connector *connector`: DRM connector

**Description**

Called by a driver when it needs to attach TV margin props to a connector.
Typically used on SDTV and HDMI connectors.

#### <a id="c-drm_mode_create_tv_margin_properties"></a>`drm_mode_create_tv_margin_properties()`

```c
int drm_mode_create_tv_margin_properties(struct drm_device *dev)
```

create TV connector margin properties

**Parameters**

- `struct drm_device *dev`: DRM device

**Description**

Called by a driver's HDMI connector initialization routine, this function
creates the TV margin properties for a given device. No need to call this
function for an SDTV connector, it's already called from
[`drm_mode_create_tv_properties_legacy()`](#c-drm_mode_create_tv_properties_legacy).

**Return**

0 on success or a negative error code on failure.

#### <a id="c-drm_mode_create_tv_properties_legacy"></a>`drm_mode_create_tv_properties_legacy()`

```c
int drm_mode_create_tv_properties_legacy(struct drm_device *dev, unsigned int num_modes, const char * const modes[])
```

create TV specific connector properties

**Parameters**

- `struct drm_device *dev`: DRM device
- `unsigned int num_modes`: number of different TV formats (modes) supported
- `const char * const modes[]`: array of pointers to strings containing name of each format

**Description**

Called by a driver's TV initialization routine, this function creates
the TV specific connector properties for a given device.  Caller is
responsible for allocating a list of format names and passing them to
this routine.

**NOTE**

This functions registers the deprecated "mode" connector
property to select the analog TV mode (ie, NTSC, PAL, etc.). New
drivers must use [`drm_mode_create_tv_properties()`](#c-drm_mode_create_tv_properties) instead.

**Return**

0 on success or a negative error code on failure.

#### <a id="c-drm_mode_create_tv_properties"></a>`drm_mode_create_tv_properties()`

```c
int drm_mode_create_tv_properties(struct drm_device *dev, unsigned int supported_tv_modes)
```

create TV specific connector properties

**Parameters**

- `struct drm_device *dev`: DRM device
- `unsigned int supported_tv_modes`: Bitmask of TV modes supported (See DRM_MODE_TV_MODE_*)

**Description**

Called by a driver's TV initialization routine, this function creates
the TV specific connector properties for a given device.

**Return**

0 on success or a negative error code on failure.

#### <a id="c-drm_mode_create_scaling_mode_property"></a>`drm_mode_create_scaling_mode_property()`

```c
int drm_mode_create_scaling_mode_property(struct drm_device *dev)
```

create scaling mode property

**Parameters**

- `struct drm_device *dev`: DRM device

**Description**

Called by a driver the first time it's needed, must be attached to desired
connectors.

Atomic drivers should use [`drm_connector_attach_scaling_mode_property()`](#c-drm_connector_attach_scaling_mode_property)
instead to correctly assign [`drm_connector_state.scaling_mode`](#c-struct-drm_connector_state)
in the atomic state.

**Return**

`0`

#### <a id="c-drm_connector_attach_vrr_capable_property"></a>`drm_connector_attach_vrr_capable_property()`

```c
int drm_connector_attach_vrr_capable_property(struct drm_connector *connector)
```

creates the vrr_capable property

**Parameters**

- `struct drm_connector *connector`: connector to create the vrr_capable property on.

**Description**

This is used by atomic drivers to add support for querying
variable refresh rate capability for a connector.

**Return**

Zero on success, negative errno on failure.

#### <a id="c-drm_connector_attach_scaling_mode_property"></a>`drm_connector_attach_scaling_mode_property()`

```c
int drm_connector_attach_scaling_mode_property(struct drm_connector *connector, u32 scaling_mode_mask)
```

attach atomic scaling mode property

**Parameters**

- `struct drm_connector *connector`: connector to attach scaling mode property on.
- `u32 scaling_mode_mask`: or'ed mask of BIT(`DRM_MODE_SCALE_`\*).

**Description**

This is used to add support for scaling mode to atomic drivers.
The scaling mode will be set to [`drm_connector_state.scaling_mode`](#c-struct-drm_connector_state)
and can be used from [`drm_connector_helper_funcs->atomic_check`](/kernel/hardware/gpu/drm-kms-helpers.md#c-struct-drm_connector_helper_funcs) for validation.

This is the atomic version of [`drm_mode_create_scaling_mode_property()`](#c-drm_mode_create_scaling_mode_property).

**Return**

Zero on success, negative errno on failure.

#### <a id="c-drm_mode_create_aspect_ratio_property"></a>`drm_mode_create_aspect_ratio_property()`

```c
int drm_mode_create_aspect_ratio_property(struct drm_device *dev)
```

create aspect ratio property

**Parameters**

- `struct drm_device *dev`: DRM device

**Description**

Called by a driver the first time it's needed, must be attached to desired
connectors.

**Return**

Zero on success, negative errno on failure.

#### <a id="c-drm_mode_create_hdmi_colorspace_property"></a>`drm_mode_create_hdmi_colorspace_property()`

```c
int drm_mode_create_hdmi_colorspace_property(struct drm_connector *connector, u32 supported_colorspaces)
```

create hdmi colorspace property

**Parameters**

- `struct drm_connector *connector`: connector to create the Colorspace property on.
- `u32 supported_colorspaces`: bitmap of supported color spaces

**Description**

Called by a driver the first time it's needed, must be attached to desired
HDMI connectors.

**Return**

Zero on success, negative errno on failure.

#### <a id="c-drm_mode_create_dp_colorspace_property"></a>`drm_mode_create_dp_colorspace_property()`

```c
int drm_mode_create_dp_colorspace_property(struct drm_connector *connector, u32 supported_colorspaces)
```

create dp colorspace property

**Parameters**

- `struct drm_connector *connector`: connector to create the Colorspace property on.
- `u32 supported_colorspaces`: bitmap of supported color spaces

**Description**

Called by a driver the first time it's needed, must be attached to desired
DP connectors.

**Return**

Zero on success, negative errno on failure.

#### <a id="c-drm_mode_create_content_type_property"></a>`drm_mode_create_content_type_property()`

```c
int drm_mode_create_content_type_property(struct drm_device *dev)
```

create content type property

**Parameters**

- `struct drm_device *dev`: DRM device

**Description**

Called by a driver the first time it's needed, must be attached to desired
connectors.

**Return**

Zero on success, negative errno on failure.

#### <a id="c-drm_mode_create_suggested_offset_properties"></a>`drm_mode_create_suggested_offset_properties()`

```c
int drm_mode_create_suggested_offset_properties(struct drm_device *dev)
```

create suggests offset properties

**Parameters**

- `struct drm_device *dev`: DRM device

**Description**

Create the suggested x/y offset property for connectors.

**Return**

0 on success or a negative error code on failure.

#### <a id="c-drm_connector_set_path_property"></a>`drm_connector_set_path_property()`

```c
int drm_connector_set_path_property(struct drm_connector *connector, const char *path)
```

set tile property on connector

**Parameters**

- `struct drm_connector *connector`: connector to set property on.
- `const char *path`: path to use for property; must not be NULL.

**Description**

This creates a property to expose to userspace to specify a
connector path. This is mainly used for DisplayPort MST where
connectors have a topology and we want to allow userspace to give
them more meaningful names.

**Return**

Zero on success, negative errno on failure.

#### <a id="c-drm_connector_set_tile_property"></a>`drm_connector_set_tile_property()`

```c
int drm_connector_set_tile_property(struct drm_connector *connector)
```

set tile property on connector

**Parameters**

- `struct drm_connector *connector`: connector to set property on.

**Description**

This looks up the tile information for a connector, and creates a
property for userspace to parse if it exists. The property is of
the form of 8 integers using ':' as a separator.
This is used for dual port tiled displays with DisplayPort SST
or DisplayPort MST connectors.

**Return**

Zero on success, errno on failure.

#### <a id="c-drm_connector_set_link_status_property"></a>`drm_connector_set_link_status_property()`

```c
void drm_connector_set_link_status_property(struct drm_connector *connector, uint64_t link_status)
```

Set link status property of a connector

**Parameters**

- `struct drm_connector *connector`: drm connector
- `uint64_t link_status`: new value of link status property (0: Good, 1: Bad)

**Description**

In usual working scenario, this link status property will always be set to
"GOOD". If something fails during or after a mode set, the kernel driver
may set this link status property to "BAD". The caller then needs to send a
hotplug uevent for userspace to re-check the valid modes through
GET_CONNECTOR_IOCTL and retry modeset.

**Note**

Drivers cannot rely on userspace to support this property and
issue a modeset. As such, they may choose to handle issues (like
re-training a link) without userspace's intervention.

The reason for adding this property is to handle link training failures, but
it is not limited to DP or link training. For example, if we implement
asynchronous setcrtc, this property can be used to report any failures in that.

#### <a id="c-drm_connector_attach_max_bpc_property"></a>`drm_connector_attach_max_bpc_property()`

```c
int drm_connector_attach_max_bpc_property(struct drm_connector *connector, int min, int max)
```

attach "max bpc" property

**Parameters**

- `struct drm_connector *connector`: connector to attach max bpc property on.
- `int min`: The minimum bit depth supported by the connector.
- `int max`: The maximum bit depth supported by the connector.

**Description**

This is used to add support for limiting the bit depth on a connector.

**Return**

Zero on success, negative errno on failure.

#### <a id="c-drm_connector_attach_hdr_output_metadata_property"></a>`drm_connector_attach_hdr_output_metadata_property()`

```c
int drm_connector_attach_hdr_output_metadata_property(struct drm_connector *connector)
```

attach "HDR_OUTPUT_METADA" property

**Parameters**

- `struct drm_connector *connector`: connector to attach the property on.

**Description**

This is used to allow the userspace to send HDR Metadata to the
driver.

**Return**

Zero on success, negative errno on failure.

#### <a id="c-drm_connector_attach_broadcast_rgb_property"></a>`drm_connector_attach_broadcast_rgb_property()`

```c
int drm_connector_attach_broadcast_rgb_property(struct drm_connector *connector)
```

attach "Broadcast RGB" property

**Parameters**

- `struct drm_connector *connector`: connector to attach the property on.

**Description**

This is used to add support for forcing the RGB range on a connector

**Return**

Zero on success, negative errno on failure.

#### <a id="c-drm_connector_attach_colorspace_property"></a>`drm_connector_attach_colorspace_property()`

```c
int drm_connector_attach_colorspace_property(struct drm_connector *connector)
```

attach "Colorspace" property

**Parameters**

- `struct drm_connector *connector`: connector to attach the property on.

**Description**

This is used to allow the userspace to signal the output colorspace
to the driver.

**Return**

Zero on success, negative errno on failure.

#### <a id="c-drm_connector_atomic_hdr_metadata_equal"></a>`drm_connector_atomic_hdr_metadata_equal()`

```c
bool drm_connector_atomic_hdr_metadata_equal(struct drm_connector_state *old_state, struct drm_connector_state *new_state)
```

checks if the hdr metadata changed

**Parameters**

- `struct drm_connector_state *old_state`: old connector state to compare
- `struct drm_connector_state *new_state`: new connector state to compare

**Description**

This is used by HDR-enabled drivers to test whether the HDR metadata
have changed between two different connector state (and thus probably
requires a full blown mode change).

**Return**

True if the metadata are equal, False otherwise

#### <a id="c-drm_connector_set_vrr_capable_property"></a>`drm_connector_set_vrr_capable_property()`

```c
void drm_connector_set_vrr_capable_property(struct drm_connector *connector, bool capable)
```

sets the variable refresh rate capable property for a connector

**Parameters**

- `struct drm_connector *connector`: drm connector
- `bool capable`: True if the connector is variable refresh rate capable

**Description**

Should be used by atomic drivers to update the indicated support for
variable refresh rate over a connector.

#### <a id="c-drm_connector_set_panel_orientation"></a>`drm_connector_set_panel_orientation()`

```c
int drm_connector_set_panel_orientation(struct drm_connector *connector, enum drm_panel_orientation panel_orientation)
```

sets the connector's panel_orientation

**Parameters**

- `struct drm_connector *connector`: connector for which to set the panel-orientation property.
- `enum drm_panel_orientation panel_orientation`: drm_panel_orientation value to set

**Description**

This function sets the connector's panel_orientation and attaches
a "panel orientation" property to the connector.

Calling this function on a connector where the panel_orientation has
already been set is a no-op (e.g. the orientation has been overridden with
a kernel commandline option).

It is allowed to call this function with a panel_orientation of
DRM_MODE_PANEL_ORIENTATION_UNKNOWN, in which case it is a no-op.

The function shouldn't be called in panel after drm is registered (i.e.
[`drm_dev_register()`](/kernel/hardware/gpu/drm-internals.md#c-drm_dev_register) is called in drm).

**Return**

Zero on success, negative errno on failure.

#### <a id="c-drm_connector_set_panel_orientation_with_quirk"></a>`drm_connector_set_panel_orientation_with_quirk()`

```c
int drm_connector_set_panel_orientation_with_quirk(struct drm_connector *connector, enum drm_panel_orientation panel_orientation, int width, int height)
```

set the connector's panel_orientation after checking for quirks

**Parameters**

- `struct drm_connector *connector`: connector for which to init the panel-orientation property.
- `enum drm_panel_orientation panel_orientation`: drm_panel_orientation value to set
- `int width`: width in pixels of the panel, used for panel quirk detection
- `int height`: height in pixels of the panel, used for panel quirk detection

**Description**

Like [`drm_connector_set_panel_orientation()`](#c-drm_connector_set_panel_orientation), but with a check for platform
specific (e.g. DMI based) quirks overriding the passed in panel_orientation.

**Return**

Zero on success, negative errno on failure.

#### <a id="c-drm_connector_set_orientation_from_panel"></a>`drm_connector_set_orientation_from_panel()`

```c
int drm_connector_set_orientation_from_panel(struct drm_connector *connector, struct drm_panel *panel)
```

set the connector's panel_orientation from panel's callback.

**Parameters**

- `struct drm_connector *connector`: connector for which to init the panel-orientation property.
- `struct drm_panel *panel`: panel that can provide orientation information.

**Description**

Drm drivers should call this function before [`drm_dev_register()`](/kernel/hardware/gpu/drm-internals.md#c-drm_dev_register).
Orientation is obtained from panel's .`get_orientation()` callback.

**Return**

Zero on success, negative errno on failure.

#### <a id="c-drm_connector_create_privacy_screen_properties"></a>`drm_connector_create_privacy_screen_properties()`

```c
void drm_connector_create_privacy_screen_properties(struct drm_connector *connector)
```

create the drm connecter's privacy-screen properties.

**Parameters**

- `struct drm_connector *connector`: connector for which to create the privacy-screen properties

**Description**

This function creates the "privacy-screen sw-state" and "privacy-screen
hw-state" properties for the connector. They are not attached.

#### <a id="c-drm_connector_attach_privacy_screen_properties"></a>`drm_connector_attach_privacy_screen_properties()`

```c
void drm_connector_attach_privacy_screen_properties(struct drm_connector *connector)
```

attach the drm connecter's privacy-screen properties.

**Parameters**

- `struct drm_connector *connector`: connector on which to attach the privacy-screen properties

**Description**

This function attaches the "privacy-screen sw-state" and "privacy-screen
hw-state" properties to the connector. The initial state of both is set
to "Disabled".

#### <a id="c-drm_connector_attach_privacy_screen_provider"></a>`drm_connector_attach_privacy_screen_provider()`

```c
void drm_connector_attach_privacy_screen_provider(struct drm_connector *connector, struct drm_privacy_screen *priv)
```

attach a privacy-screen to the connector

**Parameters**

- `struct drm_connector *connector`: connector to attach the privacy-screen to
- `struct drm_privacy_screen *priv`: drm_privacy_screen to attach

**Description**

Create and attach the standard privacy-screen properties and register
a generic notifier for generating sysfs-connector-status-events
on external changes to the privacy-screen status.
This function takes ownership of the passed in drm_privacy_screen and will
call [`drm_privacy_screen_put()`](/kernel/hardware/gpu/drm-kms-helpers.md#c-drm_privacy_screen_put) on it when the connector is destroyed.

#### <a id="c-drm_connector_update_privacy_screen"></a>`drm_connector_update_privacy_screen()`

```c
void drm_connector_update_privacy_screen(const struct drm_connector_state *connector_state)
```

update connector's privacy-screen sw-state

**Parameters**

- `const struct drm_connector_state *connector_state`: connector-state to update the privacy-screen for

**Description**

This function calls [`drm_privacy_screen_set_sw_state()`](/kernel/hardware/gpu/drm-kms-helpers.md#c-drm_privacy_screen_set_sw_state) on the connector's
privacy-screen.

If the connector has no privacy-screen, then this is a no-op.

#### <a id="c-drm_connector_oob_hotplug_event"></a>`drm_connector_oob_hotplug_event()`

```c
void drm_connector_oob_hotplug_event(struct fwnode_handle *connector_fwnode, enum drm_connector_status status)
```

Report out-of-band hotplug event to connector

**Parameters**

- `struct fwnode_handle *connector_fwnode`: fwnode_handle to report the event on
- `enum drm_connector_status status`: hot plug detect logical state

**Description**

On some hardware a hotplug event notification may come from outside the display
driver / device. An example of this is some USB Type-C setups where the hardware
muxes the DisplayPort data and aux-lines but does not pass the altmode HPD
status bit to the GPU's DP HPD pin.

This function can be used to report these out-of-band events after obtaining
a drm_connector reference through calling `drm_connector_find_by_fwnode()`.

#### <a id="c-drm_mode_put_tile_group"></a>`drm_mode_put_tile_group()`

```c
void drm_mode_put_tile_group(struct drm_device *dev, struct drm_tile_group *tg)
```

drop a reference to a tile group.

**Parameters**

- `struct drm_device *dev`: DRM device
- `struct drm_tile_group *tg`: tile group to drop reference to.

**Description**

drop reference to tile group and free if 0.

#### <a id="c-drm_mode_get_tile_group"></a>`drm_mode_get_tile_group()`

```c
struct drm_tile_group * drm_mode_get_tile_group(struct drm_device *dev, const char topology[8])
```

get a reference to an existing tile group

**Parameters**

- `struct drm_device *dev`: DRM device
- `const char topology[8]`: 8-bytes unique per monitor.

**Description**

Use the unique bytes to get a reference to an existing tile group.

**Return**

tile group or NULL if not found.

#### <a id="c-drm_mode_create_tile_group"></a>`drm_mode_create_tile_group()`

```c
struct drm_tile_group * drm_mode_create_tile_group(struct drm_device *dev, const char topology[8])
```

create a tile group from a displayid description

**Parameters**

- `struct drm_device *dev`: DRM device
- `const char topology[8]`: 8-bytes unique per monitor.

**Description**

Create a tile group for the unique monitor, and get a unique
identifier for the tile group.

**Return**

new tile group or NULL.


<a id="rst-writeback-connectors"></a>

### Writeback Connectors


Writeback connectors are used to expose hardware which can write the output
from a CRTC to a memory buffer. They are used and act similarly to other
types of connectors, with some important differences:

* Writeback connectors don't provide a way to output visually to the user.

* Writeback connectors are visible to userspace only when the client sets
  DRM_CLIENT_CAP_WRITEBACK_CONNECTORS.

* Writeback connectors don't have EDID.

A framebuffer may only be attached to a writeback connector when the
connector is attached to a CRTC. The WRITEBACK_FB_ID property which sets the
framebuffer applies only to a single commit (see below). A framebuffer may
not be attached while the CRTC is off.

Unlike with planes, when a writeback framebuffer is removed by userspace DRM
makes no attempt to remove it from active use by the connector. This is
because no method is provided to abort a writeback operation, and in any
case making a new commit whilst a writeback is ongoing is undefined (see
WRITEBACK_OUT_FENCE_PTR below). As soon as the current writeback is finished,
the framebuffer will automatically no longer be in active use. As it will
also have already been removed from the framebuffer list, there will be no
way for any userspace application to retrieve a reference to it in the
intervening period.

Writeback connectors have some additional properties, which userspace
can use to query and control them:

- "WRITEBACK_FB_ID":
  Write-only object property storing a DRM_MODE_OBJECT_FB: it stores the
  framebuffer to be written by the writeback connector. This property is
  similar to the FB_ID property on planes, but will always read as zero
  and is not preserved across commits.
  Userspace must set this property to an output buffer every time it
  wishes the buffer to get filled.

 - "WRITEBACK_PIXEL_FORMATS":
   Immutable blob property to store the supported pixel formats table. The
   data is an array of u32 DRM_FORMAT_* fourcc values.
   Userspace can use this blob to find out what pixel formats are supported
   by the connector's writeback engine.

 - "WRITEBACK_OUT_FENCE_PTR":
   Userspace can use this property to provide a pointer for the kernel to
   fill with a sync_file file descriptor, which will signal once the
   writeback is finished. The value should be the address of a 32-bit
   signed integer, cast to a u64.
   Userspace should wait for this fence to signal before making another
   commit affecting any of the same CRTCs, Planes or Connectors.
   **Failure to do so will result in undefined behaviour.**
   For this reason it is strongly recommended that all userspace
   applications making use of writeback connectors *always* retrieve an
   out-fence for the commit and use it appropriately.
   From userspace, this property will always read as zero.



#### <a id="c-struct-drm_writeback_connector"></a>`struct drm_writeback_connector`

DRM writeback connector

**Definition**

```c
struct drm_writeback_connector {
    struct drm_connector base;
    struct drm_encoder encoder;
    struct drm_property_blob *pixel_formats_blob_ptr;
    spinlock_t job_lock;
    struct list_head job_queue;
    unsigned int fence_context;
    spinlock_t fence_lock;
    unsigned long fence_seqno;
    char timeline_name[32];
};
```

**Members**

- `base`: base drm_connector object
- `encoder`: Internal encoder used by the connector to fulfill
  the DRM framework requirements. The users of the
  **drm_writeback_connector** control the behaviour of the **encoder**
  by passing the **enc_funcs** parameter to [`drm_writeback_connector_init()`](#c-drm_writeback_connector_init)
  function.
  For users of [`drm_writeback_connector_init_with_encoder()`](#c-drm_writeback_connector_init_with_encoder), this field
  is not valid as the encoder is managed within their drivers.
- `pixel_formats_blob_ptr`: DRM blob property data for the pixel formats list on writeback
  connectors
  See also [`drm_writeback_connector_init()`](#c-drm_writeback_connector_init)
- `job_lock`: Protects job_queue
- `job_queue`: Holds a list of a connector's writeback jobs; the last item is the
  most recent. The first item may be either waiting for the hardware
  to begin writing, or currently being written.

  See also: [`drm_writeback_queue_job()`](#c-drm_writeback_queue_job) and
  [`drm_writeback_signal_completion()`](#c-drm_writeback_signal_completion)
- `fence_context`: timeline context used for fence operations.
- `fence_lock`: spinlock to protect the fences in the fence_context.
- `fence_seqno`: Seqno variable used as monotonic counter for the fences
  created on the connector's timeline.
- `timeline_name`: The name of the connector's fence timeline.

#### <a id="c-struct-drm_writeback_job"></a>`struct drm_writeback_job`

DRM writeback job

**Definition**

```c
struct drm_writeback_job {
    struct drm_writeback_connector *connector;
    bool prepared;
    struct work_struct cleanup_work;
    struct list_head list_entry;
    struct drm_framebuffer *fb;
    struct dma_fence *out_fence;
    void *priv;
};
```

**Members**

- `connector`: Back-pointer to the writeback connector associated with the job
- `prepared`: Set when the job has been prepared with `drm_writeback_prepare_job()`
- `cleanup_work`: Used to allow drm_writeback_signal_completion to defer dropping the
  framebuffer reference to a workqueue
- `list_entry`: List item for the writeback connector's **job_queue**
- `fb`: Framebuffer to be written to by the writeback connector. Do not set
  directly, use `drm_writeback_set_fb()`
- `out_fence`: Fence which will signal once the writeback has completed
- `priv`: Driver-private data



#### <a id="c-drm_writeback_connector_init"></a>`drm_writeback_connector_init()`

```c
int drm_writeback_connector_init(struct drm_device *dev, struct drm_writeback_connector *wb_connector, const struct drm_connector_funcs *con_funcs, const struct drm_encoder_helper_funcs *enc_helper_funcs, const u32 *formats, int n_formats, u32 possible_crtcs)
```

Initialize a writeback connector and its properties

**Parameters**

- `struct drm_device *dev`: DRM device
- `struct drm_writeback_connector *wb_connector`: Writeback connector to initialize
- `const struct drm_connector_funcs *con_funcs`: Connector funcs vtable
- `const struct drm_encoder_helper_funcs *enc_helper_funcs`: Encoder helper funcs vtable to be used by the internal encoder
- `const u32 *formats`: Array of supported pixel formats for the writeback engine
- `int n_formats`: Length of the formats array
- `u32 possible_crtcs`: possible crtcs for the internal writeback encoder

**Description**

This function creates the writeback-connector-specific properties if they
have not been already created, initializes the connector as
type DRM_MODE_CONNECTOR_WRITEBACK, and correctly initializes the property
values. It will also create an internal encoder associated with the
drm_writeback_connector and set it to use the **enc_helper_funcs** vtable for
the encoder helper.

Drivers should always use this function instead of [`drm_connector_init()`](#c-drm_connector_init) to
set up writeback connectors.

**Return**

0 on success, or a negative error code

#### <a id="c-drm_writeback_connector_init_with_encoder"></a>`drm_writeback_connector_init_with_encoder()`

```c
int drm_writeback_connector_init_with_encoder(struct drm_device *dev, struct drm_writeback_connector *wb_connector, struct drm_encoder *enc, const struct drm_connector_funcs *con_funcs, const u32 *formats, int n_formats)
```

Initialize a writeback connector with a custom encoder

**Parameters**

- `struct drm_device *dev`: DRM device
- `struct drm_writeback_connector *wb_connector`: Writeback connector to initialize
- `struct drm_encoder *enc`: handle to the already initialized drm encoder
- `const struct drm_connector_funcs *con_funcs`: Connector funcs vtable
- `const u32 *formats`: Array of supported pixel formats for the writeback engine
- `int n_formats`: Length of the formats array

**Description**

This function creates the writeback-connector-specific properties if they
have not been already created, initializes the connector as
type DRM_MODE_CONNECTOR_WRITEBACK, and correctly initializes the property
values.

This function assumes that the drm_writeback_connector's encoder has already been
created and initialized before invoking this function.

In addition, this function also assumes that callers of this API will manage
assigning the encoder helper functions, possible_crtcs and any other encoder
specific operation.

Drivers should always use this function instead of [`drm_connector_init()`](#c-drm_connector_init) to
set up writeback connectors if they want to manage themselves the lifetime of the
associated encoder.

**Return**

0 on success, or a negative error code

#### <a id="c-drmm_writeback_connector_init"></a>`drmm_writeback_connector_init()`

```c
int drmm_writeback_connector_init(struct drm_device *dev, struct drm_writeback_connector *wb_connector, const struct drm_connector_funcs *con_funcs, struct drm_encoder *enc, const u32 *formats, int n_formats)
```

Initialize a writeback connector with a custom encoder

**Parameters**

- `struct drm_device *dev`: DRM device
- `struct drm_writeback_connector *wb_connector`: Writeback connector to initialize
- `const struct drm_connector_funcs *con_funcs`: Connector funcs vtable
- `struct drm_encoder *enc`: Encoder to connect this writeback connector
- `const u32 *formats`: Array of supported pixel formats for the writeback engine
- `int n_formats`: Length of the formats array

**Description**

This function initialize a writeback connector and register its cleanup.

This function creates the writeback-connector-specific properties if they
have not been already created, initializes the connector as
type DRM_MODE_CONNECTOR_WRITEBACK, and correctly initializes the property
values.

**Return**

0 on success, or a negative error code

#### <a id="c-drm_writeback_queue_job"></a>`drm_writeback_queue_job()`

```c
void drm_writeback_queue_job(struct drm_writeback_connector *wb_connector, struct drm_connector_state *conn_state)
```

Queue a writeback job for later signalling

**Parameters**

- `struct drm_writeback_connector *wb_connector`: The writeback connector to queue a job on
- `struct drm_connector_state *conn_state`: The connector state containing the job to queue

**Description**

This function adds the job contained in **conn_state** to the job_queue for a
writeback connector. It takes ownership of the writeback job and sets the
**conn_state->writeback_job** to NULL, and so no access to the job may be
performed by the caller after this function returns.

Drivers must ensure that for a given writeback connector, jobs are queued in
exactly the same order as they will be completed by the hardware (and
signaled via drm_writeback_signal_completion).

For every call to [`drm_writeback_queue_job()`](#c-drm_writeback_queue_job) there must be exactly one call to
[`drm_writeback_signal_completion()`](#c-drm_writeback_signal_completion)

See also: [`drm_writeback_signal_completion()`](#c-drm_writeback_signal_completion)

#### <a id="c-drm_writeback_signal_completion"></a>`drm_writeback_signal_completion()`

```c
void drm_writeback_signal_completion(struct drm_writeback_connector *wb_connector, int status)
```

Signal the completion of a writeback job

**Parameters**

- `struct drm_writeback_connector *wb_connector`: The writeback connector whose job is complete
- `int status`: Status code to set in the writeback out_fence (0 for success)

**Description**

Drivers should call this to signal the completion of a previously queued
writeback job. It should be called as soon as possible after the hardware
has finished writing, and may be called from interrupt context.
It is the driver's responsibility to ensure that for a given connector, the
hardware completes writeback jobs in the same order as they are queued.

Unless the driver is holding its own reference to the framebuffer, it must
not be accessed after calling this function.

See also: [`drm_writeback_queue_job()`](#c-drm_writeback_queue_job)


<a id="rst-encoder-abstraction"></a>

## Encoder Abstraction


Encoders represent the connecting element between the CRTC (as the overall
pixel pipeline, represented by [`struct drm_crtc`](#c-struct-drm_crtc)) and the connectors (as the
generic sink entity, represented by [`struct drm_connector`](#c-struct-drm_connector)). An encoder takes
pixel data from a CRTC and converts it to a format suitable for any attached
connector. Encoders are objects exposed to userspace, originally to allow
userspace to infer cloning and connector/CRTC restrictions. Unfortunately
almost all drivers get this wrong, making the uabi pretty much useless. On
top of that the exposed restrictions are too simple for today's hardware, and
the recommended way to infer restrictions is by using the
DRM_MODE_ATOMIC_TEST_ONLY flag for the atomic IOCTL.

Otherwise encoders aren't used in the uapi at all (any modeset request from
userspace directly connects a connector with a CRTC), drivers are therefore
free to use them however they wish. Modeset helper libraries make strong use
of encoders to facilitate code sharing. But for more complex settings it is
usually better to move shared code into a separate [`drm_bridge`](/kernel/hardware/gpu/drm-kms-helpers.md#c-struct-drm_bridge). Compared to
encoders, bridges also have the benefit of being purely an internal
abstraction since they are not exposed to userspace at all.

Encoders are initialized with [`drm_encoder_init()`](#c-drm_encoder_init) and cleaned up using
[`drm_encoder_cleanup()`](#c-drm_encoder_cleanup).


<a id="rst-encoder-functions-reference"></a>

### Encoder Functions Reference


#### <a id="c-struct-drm_encoder_funcs"></a>`struct drm_encoder_funcs`

encoder controls

**Definition**

```c
struct drm_encoder_funcs {
    void (*reset)(struct drm_encoder *encoder);
    void (*destroy)(struct drm_encoder *encoder);
    int (*late_register)(struct drm_encoder *encoder);
    void (*early_unregister)(struct drm_encoder *encoder);
    void (*debugfs_init)(struct drm_encoder *encoder, struct dentry *root);
};
```

**Members**

- `reset`: Reset encoder hardware and software state to off. This function isn't
  called by the core directly, only through [`drm_mode_config_reset()`](#c-drm_mode_config_reset).
  It's not a helper hook only for historical reasons.
- `destroy`: Clean up encoder resources. This is only called at driver unload time
  through [`drm_mode_config_cleanup()`](#c-drm_mode_config_cleanup) since an encoder cannot be
  hotplugged in DRM.
- `late_register`: This optional hook can be used to register additional userspace
  interfaces attached to the encoder.
  It is called late in the driver load sequence from [`drm_dev_register()`](/kernel/hardware/gpu/drm-internals.md#c-drm_dev_register).
  Everything added from this callback should be unregistered in
  the early_unregister callback.

  Returns:

  0 on success, or a negative error code on failure.
- `early_unregister`: This optional hook should be used to unregister the additional
  userspace interfaces attached to the encoder from
  **late_register**. It is called from [`drm_dev_unregister()`](/kernel/hardware/gpu/drm-internals.md#c-drm_dev_unregister),
  early in the driver unload sequence to disable userspace access
  before data structures are torndown.
- `debugfs_init`: Allows encoders to create encoder-specific debugfs files.

**Description**

Encoders sit between CRTCs and connectors.

#### <a id="c-struct-drm_encoder"></a>`struct drm_encoder`

central DRM encoder structure

**Definition**

```c
struct drm_encoder {
    struct drm_device *dev;
    struct list_head head;
    struct drm_mode_object base;
    char *name;
    int encoder_type;
    unsigned index;
    uint32_t possible_crtcs;
    uint32_t possible_clones;
    struct drm_crtc *crtc;
    struct list_head bridge_chain;
    const struct drm_encoder_funcs *funcs;
    const struct drm_encoder_helper_funcs *helper_private;
    struct dentry *debugfs_entry;
};
```

**Members**

- `dev`: parent DRM device
- `head`: list management
- `base`: base KMS object
- `name`: human readable name, can be overwritten by the driver
- `encoder_type`: One of the DRM_MODE_ENCODER_\<foo> types in drm_mode.h. The following
  encoder types are defined thus far:

  - DRM_MODE_ENCODER_DAC for VGA and analog on DVI-I/DVI-A.

  - DRM_MODE_ENCODER_TMDS for DVI, HDMI and (embedded) DisplayPort.

  - DRM_MODE_ENCODER_LVDS for display panels, or in general any panel
    with a proprietary parallel connector.

  - DRM_MODE_ENCODER_TVDAC for TV output (Composite, S-Video,
    Component, SCART).

  - DRM_MODE_ENCODER_VIRTUAL for virtual machine displays

  - DRM_MODE_ENCODER_DSI for panels connected using the DSI serial bus.

  - DRM_MODE_ENCODER_DPI for panels connected using the DPI parallel
    bus.

  - DRM_MODE_ENCODER_DPMST for special fake encoders used to allow
    mutliple DP MST streams to share one physical encoder.
- `index`: Position inside the mode_config.list, can be used as an array
  index. It is invariant over the lifetime of the encoder.
- `possible_crtcs`: Bitmask of potential CRTC bindings, using
  [`drm_crtc_index()`](#c-drm_crtc_index) as the index into the bitfield. The driver must set
  the bits for all [`drm_crtc`](#c-struct-drm_crtc) objects this encoder can be connected to
  before calling [`drm_dev_register()`](/kernel/hardware/gpu/drm-internals.md#c-drm_dev_register).

  You will get a WARN if you get this wrong in the driver.

  Note that since CRTC objects can't be hotplugged the assigned indices
  are stable and hence known before registering all objects.
- `possible_clones`: Bitmask of potential sibling encoders for cloning,
  using [`drm_encoder_index()`](#c-drm_encoder_index) as the index into the bitfield. The driver
  must set the bits for all [`drm_encoder`](#c-struct-drm_encoder) objects which can clone a
  [`drm_crtc`](#c-struct-drm_crtc) together with this encoder before calling
  [`drm_dev_register()`](/kernel/hardware/gpu/drm-internals.md#c-drm_dev_register). Drivers should set the bit representing the
  encoder itself, too. Cloning bits should be set such that when two
  encoders can be used in a cloned configuration, they both should have
  each another bits set.

  As an exception to the above rule if the driver doesn't implement
  any cloning it can leave **possible_clones** set to 0. The core will
  automagically fix this up by setting the bit for the encoder itself.

  You will get a WARN if you get this wrong in the driver.

  Note that since encoder objects can't be hotplugged the assigned indices
  are stable and hence known before registering all objects.
- `crtc`: Currently bound CRTC, only really meaningful for non-atomic
  drivers.  Atomic drivers should instead check
  [`drm_connector_state.crtc`](#c-struct-drm_connector_state).
- `bridge_chain`: Bridges attached to this encoder. Drivers shall not
  access this field directly.
- `funcs`: control functions, can be NULL for simple managed encoders
- `helper_private`: mid-layer private data
- `debugfs_entry`: Debugfs directory for this CRTC.

**Description**

CRTCs drive pixels to encoders, which convert them into signals
appropriate for a given connector or set of connectors.

#### <a id="c-drmm_encoder_alloc"></a>`drmm_encoder_alloc()`

```c
drmm_encoder_alloc(dev, type, member, funcs, encoder_type, name, ...)
```

Allocate and initialize an encoder

**Parameters**

- `dev`: drm device
- `type`: the type of the struct which contains struct [`drm_encoder`](#c-struct-drm_encoder)
- `member`: the name of the [`drm_encoder`](#c-struct-drm_encoder) within **type**
- `funcs`: callbacks for this encoder (optional)
- `encoder_type`: user visible type of the encoder
- `name`: printf style format string for the encoder name, or NULL for default name
- `...`: variable arguments

**Description**

Allocates and initializes an encoder. Encoder should be subclassed as part of
driver encoder objects. Cleanup is automatically handled through registering
[`drm_encoder_cleanup()`](#c-drm_encoder_cleanup) with [`drmm_add_action()`](/kernel/hardware/gpu/drm-internals.md#c-drmm_add_action).

The **drm_encoder_funcs.destroy** hook must be NULL.

**Return**

Pointer to new encoder, or ERR_PTR on failure.

#### <a id="c-drmm_plain_encoder_alloc"></a>`drmm_plain_encoder_alloc()`

```c
drmm_plain_encoder_alloc(dev, funcs, encoder_type, name, ...)
```

Allocate and initialize an encoder

**Parameters**

- `dev`: drm device
- `funcs`: callbacks for this encoder (optional)
- `encoder_type`: user visible type of the encoder
- `name`: printf style format string for the encoder name, or NULL for default name
- `...`: variable arguments

**Description**

This is a simplified version of [`drmm_encoder_alloc()`](#c-drmm_encoder_alloc), which only allocates
and returns a struct drm_encoder instance, with no subclassing.

**Return**

Pointer to the new drm_encoder struct, or ERR_PTR on failure.

#### <a id="c-drm_encoder_index"></a>`drm_encoder_index()`

```c
unsigned int drm_encoder_index(const struct drm_encoder *encoder)
```

find the index of a registered encoder

**Parameters**

- `const struct drm_encoder *encoder`: encoder to find index for

**Description**

Given a registered encoder, return the index of that encoder within a DRM
device's list of encoders.

#### <a id="c-drm_encoder_mask"></a>`drm_encoder_mask()`

```c
u32 drm_encoder_mask(const struct drm_encoder *encoder)
```

find the mask of a registered encoder

**Parameters**

- `const struct drm_encoder *encoder`: encoder to find mask for

**Description**

Given a registered encoder, return the mask bit of that encoder for an
encoder's possible_clones field.

#### <a id="c-drm_encoder_crtc_ok"></a>`drm_encoder_crtc_ok()`

```c
bool drm_encoder_crtc_ok(struct drm_encoder *encoder, struct drm_crtc *crtc)
```

can a given crtc drive a given encoder?

**Parameters**

- `struct drm_encoder *encoder`: encoder to test
- `struct drm_crtc *crtc`: crtc to test

**Description**

Returns false if **encoder** can't be driven by **crtc**, true otherwise.

#### <a id="c-drm_encoder_find"></a>`drm_encoder_find()`

```c
struct drm_encoder * drm_encoder_find(struct drm_device *dev, struct drm_file *file_priv, uint32_t id)
```

find a [`drm_encoder`](#c-struct-drm_encoder)

**Parameters**

- `struct drm_device *dev`: DRM device
- `struct drm_file *file_priv`: drm file to check for lease against.
- `uint32_t id`: encoder id

**Description**

Returns the encoder with **id**, NULL if it doesn't exist. Simple wrapper around
[`drm_mode_object_find()`](#c-drm_mode_object_find).

#### <a id="c-drm_for_each_encoder_mask"></a>`drm_for_each_encoder_mask()`

```c
drm_for_each_encoder_mask(encoder, dev, encoder_mask)
```

iterate over encoders specified by bitmask

**Parameters**

- `encoder`: the loop cursor
- `dev`: the DRM device
- `encoder_mask`: bitmask of encoder indices

**Description**

Iterate over all encoders specified by bitmask.

#### <a id="c-drm_for_each_encoder"></a>`drm_for_each_encoder()`

```c
drm_for_each_encoder(encoder, dev)
```

iterate over all encoders

**Parameters**

- `encoder`: the loop cursor
- `dev`: the DRM device

**Description**

Iterate over all encoders of **dev**.



#### <a id="c-drm_encoder_init"></a>`drm_encoder_init()`

```c
int drm_encoder_init(struct drm_device *dev, struct drm_encoder *encoder, const struct drm_encoder_funcs *funcs, int encoder_type, const char *name, ...)
```

Init a preallocated encoder

**Parameters**

- `struct drm_device *dev`: drm device
- `struct drm_encoder *encoder`: the encoder to init
- `const struct drm_encoder_funcs *funcs`: callbacks for this encoder
- `int encoder_type`: user visible type of the encoder
- `const char *name`: printf style format string for the encoder name, or NULL for default name
- `...`: variable arguments

**Description**

Initializes a preallocated encoder. Encoder should be subclassed as part of
driver encoder objects. At driver unload time the driver's
[`drm_encoder_funcs.destroy`](#c-struct-drm_encoder_funcs) hook should call [`drm_encoder_cleanup()`](#c-drm_encoder_cleanup) and [`kfree()`](/kernel/internals/core-api/mm-api.md#c-kfree)
the encoder structure. The encoder structure should not be allocated with
`devm_kzalloc()`.

**Note**

consider using [`drmm_encoder_alloc()`](#c-drmm_encoder_alloc) or [`drmm_encoder_init()`](#c-drmm_encoder_init)
instead of [`drm_encoder_init()`](#c-drm_encoder_init) to let the DRM managed resource
infrastructure take care of cleanup and deallocation.

**Return**

Zero on success, error code on failure.

#### <a id="c-drm_encoder_cleanup"></a>`drm_encoder_cleanup()`

```c
void drm_encoder_cleanup(struct drm_encoder *encoder)
```

cleans up an initialised encoder

**Parameters**

- `struct drm_encoder *encoder`: encoder to cleanup

**Description**

Cleans up the encoder but doesn't free the object.

#### <a id="c-drmm_encoder_init"></a>`drmm_encoder_init()`

```c
int drmm_encoder_init(struct drm_device *dev, struct drm_encoder *encoder, const struct drm_encoder_funcs *funcs, int encoder_type, const char *name, ...)
```

Initialize a preallocated encoder

**Parameters**

- `struct drm_device *dev`: drm device
- `struct drm_encoder *encoder`: the encoder to init
- `const struct drm_encoder_funcs *funcs`: callbacks for this encoder (optional)
- `int encoder_type`: user visible type of the encoder
- `const char *name`: printf style format string for the encoder name, or NULL for default name
- `...`: variable arguments

**Description**

Initializes a preallocated encoder. Encoder should be subclassed as
part of driver encoder objects. Cleanup is automatically handled
through registering [`drm_encoder_cleanup()`](#c-drm_encoder_cleanup) with [`drmm_add_action()`](/kernel/hardware/gpu/drm-internals.md#c-drmm_add_action). The
encoder structure should be allocated with [`drmm_kzalloc()`](/kernel/hardware/gpu/drm-internals.md#c-drmm_kzalloc).

The **drm_encoder_funcs.destroy** hook must be NULL.

**Return**

Zero on success, error code on failure.


<a id="rst-kms-locking"></a>

## KMS Locking


As KMS moves toward more fine grained locking, and atomic ioctl where
userspace can indirectly control locking order, it becomes necessary
to use `ww_mutex` and acquire-contexts to avoid deadlocks.  But because
the locking is more distributed around the driver code, we want a bit
of extra utility/tracking out of our acquire-ctx.  This is provided
by [`struct drm_modeset_lock`](#c-struct-drm_modeset_lock) and [`struct drm_modeset_acquire_ctx`](#c-struct-drm_modeset_acquire_ctx).

For basic principles of `ww_mutex`, see: Documentation/locking/ww-mutex-design.rst

The basic usage pattern is to:

```text
drm_modeset_acquire_init(ctx, DRM_MODESET_ACQUIRE_INTERRUPTIBLE)
retry:
foreach (lock in random_ordered_set_of_locks) {
    ret = drm_modeset_lock(lock, ctx)
    if (ret == -EDEADLK) {
        ret = drm_modeset_backoff(ctx);
        if (!ret)
            goto retry;
    }
    if (ret)
        goto out;
}
... do stuff ...
out:
drm_modeset_drop_locks(ctx);
drm_modeset_acquire_fini(ctx);
```

For convenience this control flow is implemented in
[`DRM_MODESET_LOCK_ALL_BEGIN()`](#c-DRM_MODESET_LOCK_ALL_BEGIN) and [`DRM_MODESET_LOCK_ALL_END()`](#c-DRM_MODESET_LOCK_ALL_END) for the case
where all modeset locks need to be taken through [`drm_modeset_lock_all_ctx()`](#c-drm_modeset_lock_all_ctx).

If all that is needed is a single modeset lock, then the [`struct drm_modeset_acquire_ctx`](#c-struct-drm_modeset_acquire_ctx) is not needed and the locking can be simplified
by passing a NULL instead of ctx in the [`drm_modeset_lock()`](#c-drm_modeset_lock) call or
calling  [`drm_modeset_lock_single_interruptible()`](#c-drm_modeset_lock_single_interruptible). To unlock afterwards
call [`drm_modeset_unlock()`](#c-drm_modeset_unlock).

On top of these per-object locks using `ww_mutex` there's also an overall
[`drm_mode_config.mutex`](#c-struct-drm_mode_config), for protecting everything else. Mostly this means
probe state of connectors, and preventing hotplug add/removal of connectors.

Finally there's a bunch of dedicated locks to protect drm core internal
lists and lookup data structures.



#### <a id="c-struct-drm_modeset_acquire_ctx"></a>`struct drm_modeset_acquire_ctx`

locking context (see ww_acquire_ctx)

**Definition**

```c
struct drm_modeset_acquire_ctx {
    struct ww_acquire_ctx ww_ctx;
    struct drm_modeset_lock *contended;
    depot_stack_handle_t stack_depot;
    struct list_head locked;
    bool trylock_only;
    bool interruptible;
};
```

**Members**

- `ww_ctx`: base acquire ctx
- `contended`: used internally for -EDEADLK handling
- `stack_depot`: used internally for contention debugging
- `locked`: list of held locks
- `trylock_only`: trylock mode used in atomic contexts/panic notifiers
- `interruptible`: whether interruptible locking should be used.

**Description**

Each thread competing for a set of locks must use one acquire
ctx.  And if any lock fxn returns -EDEADLK, it must backoff and
retry.

#### <a id="c-struct-drm_modeset_lock"></a>`struct drm_modeset_lock`

used for locking modeset resources.

**Definition**

```c
struct drm_modeset_lock {
    struct ww_mutex mutex;
    struct list_head head;
};
```

**Members**

- `mutex`: resource locking
- `head`: used to hold its place on `drm_atomi_state.locked` list when
  part of an atomic update

**Description**

Used for locking CRTCs and other modeset resources.

#### <a id="c-drm_modeset_lock_fini"></a>`drm_modeset_lock_fini()`

```c
void drm_modeset_lock_fini(struct drm_modeset_lock *lock)
```

cleanup lock

**Parameters**

- `struct drm_modeset_lock *lock`: lock to cleanup

#### <a id="c-drm_modeset_is_locked"></a>`drm_modeset_is_locked()`

```c
bool drm_modeset_is_locked(struct drm_modeset_lock *lock)
```

equivalent to [`mutex_is_locked()`](/kernel/development/kernel-hacking/locking.md#c-mutex_is_locked)

**Parameters**

- `struct drm_modeset_lock *lock`: lock to check

#### <a id="c-drm_modeset_lock_assert_held"></a>`drm_modeset_lock_assert_held()`

```c
void drm_modeset_lock_assert_held(struct drm_modeset_lock *lock)
```

equivalent to `lockdep_assert_held()`

**Parameters**

- `struct drm_modeset_lock *lock`: lock to check

#### <a id="c-DRM_MODESET_LOCK_ALL_BEGIN"></a>`DRM_MODESET_LOCK_ALL_BEGIN()`

```c
DRM_MODESET_LOCK_ALL_BEGIN(dev, ctx, flags, ret)
```

Helper to acquire modeset locks

**Parameters**

- `dev`: drm device
- `ctx`: local modeset acquire context, will be dereferenced
- `flags`: DRM_MODESET_ACQUIRE_* flags to pass to [`drm_modeset_acquire_init()`](#c-drm_modeset_acquire_init)
- `ret`: local ret/err/etc variable to track error status

**Description**

Use these macros to simplify grabbing all modeset locks using a local
context. This has the advantage of reducing boilerplate, but also properly
checking return values where appropriate.

Any code run between BEGIN and END will be holding the modeset locks.

This must be paired with [`DRM_MODESET_LOCK_ALL_END()`](#c-DRM_MODESET_LOCK_ALL_END). We will jump back and
forth between the labels on deadlock and error conditions.

Drivers can acquire additional modeset locks. If any lock acquisition
fails, the control flow needs to jump to [`DRM_MODESET_LOCK_ALL_END()`](#c-DRM_MODESET_LOCK_ALL_END) with
the **ret** parameter containing the return value of [`drm_modeset_lock()`](#c-drm_modeset_lock).

**Return**

The only possible value of ret immediately after [`DRM_MODESET_LOCK_ALL_BEGIN()`](#c-DRM_MODESET_LOCK_ALL_BEGIN)
is 0, so no error checking is necessary

#### <a id="c-DRM_MODESET_LOCK_ALL_END"></a>`DRM_MODESET_LOCK_ALL_END()`

```c
DRM_MODESET_LOCK_ALL_END(dev, ctx, ret)
```

Helper to release and cleanup modeset locks

**Parameters**

- `dev`: drm device
- `ctx`: local modeset acquire context, will be dereferenced
- `ret`: local ret/err/etc variable to track error status

**Description**

The other side of [`DRM_MODESET_LOCK_ALL_BEGIN()`](#c-DRM_MODESET_LOCK_ALL_BEGIN). It will bounce back to BEGIN
if ret is -EDEADLK.

It's important that you use the same ret variable for begin and end so
deadlock conditions are properly handled.

**Return**

ret will be untouched unless it is -EDEADLK on entry. That means that if you
successfully acquire the locks, ret will be whatever your code sets it to. If
there is a deadlock or other failure with acquire or backoff, ret will be set
to that failure. In both of these cases the code between BEGIN/END will not
be run, so the failure will reflect the inability to grab the locks.



#### <a id="c-drm_modeset_lock_all"></a>`drm_modeset_lock_all()`

```c
void drm_modeset_lock_all(struct drm_device *dev)
```

take all modeset locks

**Parameters**

- `struct drm_device *dev`: DRM device

**Description**

This function takes all modeset locks, suitable where a more fine-grained
scheme isn't (yet) implemented. Locks must be dropped by calling the
[`drm_modeset_unlock_all()`](#c-drm_modeset_unlock_all) function.

This function is deprecated. It allocates a lock acquisition context and
stores it in [`drm_device.mode_config`](/kernel/hardware/gpu/drm-internals.md#c-struct-drm_device). This facilitate conversion of
existing code because it removes the need to manually deal with the
acquisition context, but it is also brittle because the context is global
and care must be taken not to nest calls. New code should use the
[`drm_modeset_lock_all_ctx()`](#c-drm_modeset_lock_all_ctx) function and pass in the context explicitly.

#### <a id="c-drm_modeset_unlock_all"></a>`drm_modeset_unlock_all()`

```c
void drm_modeset_unlock_all(struct drm_device *dev)
```

drop all modeset locks

**Parameters**

- `struct drm_device *dev`: DRM device

**Description**

This function drops all modeset locks taken by a previous call to the
[`drm_modeset_lock_all()`](#c-drm_modeset_lock_all) function.

This function is deprecated. It uses the lock acquisition context stored
in [`drm_device.mode_config`](/kernel/hardware/gpu/drm-internals.md#c-struct-drm_device). This facilitates conversion of existing
code because it removes the need to manually deal with the acquisition
context, but it is also brittle because the context is global and care must
be taken not to nest calls. New code should pass the acquisition context
directly to the [`drm_modeset_drop_locks()`](#c-drm_modeset_drop_locks) function.

#### <a id="c-drm_warn_on_modeset_not_all_locked"></a>`drm_warn_on_modeset_not_all_locked()`

```c
void drm_warn_on_modeset_not_all_locked(struct drm_device *dev)
```

check that all modeset locks are locked

**Parameters**

- `struct drm_device *dev`: device

**Description**

Useful as a debug assert.

#### <a id="c-drm_modeset_acquire_init"></a>`drm_modeset_acquire_init()`

```c
void drm_modeset_acquire_init(struct drm_modeset_acquire_ctx *ctx, uint32_t flags)
```

initialize acquire context

**Parameters**

- `struct drm_modeset_acquire_ctx *ctx`: the acquire context
- `uint32_t flags`: 0 or `DRM_MODESET_ACQUIRE_INTERRUPTIBLE`

**Description**

When passing `DRM_MODESET_ACQUIRE_INTERRUPTIBLE` to **flags**,
all calls to [`drm_modeset_lock()`](#c-drm_modeset_lock) will perform an interruptible
wait.

#### <a id="c-drm_modeset_acquire_fini"></a>`drm_modeset_acquire_fini()`

```c
void drm_modeset_acquire_fini(struct drm_modeset_acquire_ctx *ctx)
```

cleanup acquire context

**Parameters**

- `struct drm_modeset_acquire_ctx *ctx`: the acquire context

#### <a id="c-drm_modeset_drop_locks"></a>`drm_modeset_drop_locks()`

```c
void drm_modeset_drop_locks(struct drm_modeset_acquire_ctx *ctx)
```

drop all locks

**Parameters**

- `struct drm_modeset_acquire_ctx *ctx`: the acquire context

**Description**

Drop all locks currently held against this acquire context.

#### <a id="c-drm_modeset_backoff"></a>`drm_modeset_backoff()`

```c
int drm_modeset_backoff(struct drm_modeset_acquire_ctx *ctx)
```

deadlock avoidance backoff

**Parameters**

- `struct drm_modeset_acquire_ctx *ctx`: the acquire context

**Description**

If deadlock is detected (ie. [`drm_modeset_lock()`](#c-drm_modeset_lock) returns -EDEADLK),
you must call this function to drop all currently held locks and
block until the contended lock becomes available.

This function returns 0 on success, or -ERESTARTSYS if this context
is initialized with `DRM_MODESET_ACQUIRE_INTERRUPTIBLE` and the
wait has been interrupted.

#### <a id="c-drm_modeset_lock_init"></a>`drm_modeset_lock_init()`

```c
void drm_modeset_lock_init(struct drm_modeset_lock *lock)
```

initialize lock

**Parameters**

- `struct drm_modeset_lock *lock`: lock to init

#### <a id="c-drm_modeset_lock"></a>`drm_modeset_lock()`

```c
int drm_modeset_lock(struct drm_modeset_lock *lock, struct drm_modeset_acquire_ctx *ctx)
```

take modeset lock

**Parameters**

- `struct drm_modeset_lock *lock`: lock to take
- `struct drm_modeset_acquire_ctx *ctx`: acquire ctx

**Description**

If **ctx** is not NULL, then its ww acquire context is used and the
lock will be tracked by the context and can be released by calling
[`drm_modeset_drop_locks()`](#c-drm_modeset_drop_locks).  If -EDEADLK is returned, this means a
deadlock scenario has been detected and it is an error to attempt
to take any more locks without first calling [`drm_modeset_backoff()`](#c-drm_modeset_backoff).

If the **ctx** is not NULL and initialized with
`DRM_MODESET_ACQUIRE_INTERRUPTIBLE`, this function will fail with
-ERESTARTSYS when interrupted.

If **ctx** is NULL then the function call behaves like a normal,
uninterruptible non-nesting [`mutex_lock()`](/kernel/development/kernel-hacking/locking.md#c-mutex_lock) call.

#### <a id="c-drm_modeset_lock_single_interruptible"></a>`drm_modeset_lock_single_interruptible()`

```c
int drm_modeset_lock_single_interruptible(struct drm_modeset_lock *lock)
```

take a single modeset lock

**Parameters**

- `struct drm_modeset_lock *lock`: lock to take

**Description**

This function behaves as [`drm_modeset_lock()`](#c-drm_modeset_lock) with a NULL context,
but performs interruptible waits.

This function returns 0 on success, or -ERESTARTSYS when interrupted.

#### <a id="c-drm_modeset_unlock"></a>`drm_modeset_unlock()`

```c
void drm_modeset_unlock(struct drm_modeset_lock *lock)
```

drop modeset lock

**Parameters**

- `struct drm_modeset_lock *lock`: lock to release

#### <a id="c-drm_modeset_lock_all_ctx"></a>`drm_modeset_lock_all_ctx()`

```c
int drm_modeset_lock_all_ctx(struct drm_device *dev, struct drm_modeset_acquire_ctx *ctx)
```

take all modeset locks

**Parameters**

- `struct drm_device *dev`: DRM device
- `struct drm_modeset_acquire_ctx *ctx`: lock acquisition context

**Description**

This function takes all modeset locks, suitable where a more fine-grained
scheme isn't (yet) implemented.

Unlike [`drm_modeset_lock_all()`](#c-drm_modeset_lock_all), it doesn't take the [`drm_mode_config.mutex`](#c-struct-drm_mode_config)
since that lock isn't required for modeset state changes. Callers which
need to grab that lock too need to do so outside of the acquire context
**ctx**.

Locks acquired with this function should be released by calling the
[`drm_modeset_drop_locks()`](#c-drm_modeset_drop_locks) function on **ctx**.

See also: [`DRM_MODESET_LOCK_ALL_BEGIN()`](#c-DRM_MODESET_LOCK_ALL_BEGIN) and [`DRM_MODESET_LOCK_ALL_END()`](#c-DRM_MODESET_LOCK_ALL_END)

**Return**

0 on success or a negative error-code on failure.


<a id="rst-kms-properties"></a>

## KMS Properties

This section of the documentation is primarily aimed at user-space developers. For the driver APIs, see the other sections.

<a id="rst-requirements"></a>

### Requirements

KMS drivers might need to add extra properties to support new features. Each new property introduced in a driver needs to meet a few requirements, in addition to the one mentioned above:

- It must be standardized, documenting:

  - The full, exact, name string;

  - If the property is an enum, all the valid value name strings;

  - What values are accepted, and what these values mean;

  - What the property does and how it can be used;

  - How the property might interact with other, existing properties.

- It must provide a generic helper in the core code to register that property on the object it attaches to.

- Its content must be decoded by the core and provided in the object's associated state structure. That includes anything drivers might want to precompute, like struct drm\_clip\_rect for planes.

- Its initial state must match the behavior prior to the property introduction. This might be a fixed value matching what the hardware does, or it may be inherited from the state the firmware left the system in during boot.

- An IGT test must be submitted where reasonable.

For historical reasons, non-standard, driver-specific properties exist. If a KMS driver wants to add support for one of those properties, the requirements for new properties apply where possible. Additionally, the documented behavior must match the de facto semantics of the existing property to ensure compatibility. Developers of the driver that first added the property should help with those tasks and must ACK the documented behavior if possible.

<a id="rst-property-types-and-blob-property-support"></a>

### Property Types and Blob Property Support


Properties as represented by [`drm_property`](#c-struct-drm_property) are used to extend the modeset
interface exposed to userspace. For the atomic modeset IOCTL properties are
even the only way to transport metadata about the desired new modeset
configuration from userspace to the kernel. Properties have a well-defined
value range, which is enforced by the drm core. See the documentation of the
flags member of [`struct drm_property`](#c-struct-drm_property) for an overview of the different
property types and ranges.

Properties don't store the current value directly, but need to be
instantiated by attaching them to a [`drm_mode_object`](#c-struct-drm_mode_object) with
[`drm_object_attach_property()`](#c-drm_object_attach_property).

Property values are only 64bit. To support bigger piles of data (like gamma
tables, color correction matrices or large structures) a property can instead
point at a [`drm_property_blob`](#c-struct-drm_property_blob) with that additional data.

Properties are defined by their symbolic name, userspace must keep a
per-object mapping from those names to the property ID used in the atomic
IOCTL and in the get/set property IOCTL.



#### <a id="c-struct-drm_property_enum"></a>`struct drm_property_enum`

symbolic values for enumerations

**Definition**

```c
struct drm_property_enum {
    uint64_t value;
    struct list_head head;
    char name[DRM_PROP_NAME_LEN];
};
```

**Members**

- `value`: numeric property value for this enum entry

  If the property has the type `DRM_MODE_PROP_BITMASK`, **value** stores a
  bitshift, not a bitmask. In other words, the enum entry is enabled
  if the bit number **value** is set in the property's value. This enum
  entry has the bitmask `1 << value`.
- `head`: list of enum values, linked to [`drm_property.enum_list`](#c-struct-drm_property)
- `name`: symbolic name for the enum

**Description**

For enumeration and bitmask properties this structure stores the symbolic
decoding for each value. This is used for example for the rotation property.

#### <a id="c-struct-drm_property"></a>`struct drm_property`

modeset object property

**Definition**

```c
struct drm_property {
    struct list_head head;
    struct drm_mode_object base;
    uint32_t flags;
    char name[DRM_PROP_NAME_LEN];
    uint32_t num_values;
    uint64_t *values;
    struct drm_device *dev;
    struct list_head enum_list;
};
```

**Members**

- `head`: per-device list of properties, for cleanup.
- `base`: base KMS object
- `flags`: Property flags and type. A property needs to be one of the following
  types:

  - DRM_MODE_PROP_RANGE:
    Range properties report their minimum and maximum admissible unsigned values.
    The KMS core verifies that values set by application fit in that
    range. The range is unsigned. Range properties are created using
    [`drm_property_create_range()`](#c-drm_property_create_range).

  - DRM_MODE_PROP_SIGNED_RANGE:
    Range properties report their minimum and maximum admissible unsigned values.
    The KMS core verifies that values set by application fit in that
    range. The range is signed. Range properties are created using
    [`drm_property_create_signed_range()`](#c-drm_property_create_signed_range).

  - DRM_MODE_PROP_ENUM:
    Enumerated properties take a numerical value that ranges from 0 to
    the number of enumerated values defined by the property minus one,
    and associate a free-formed string name to each value. Applications
    can retrieve the list of defined value-name pairs and use the
    numerical value to get and set property instance values. Enum
    properties are created using [`drm_property_create_enum()`](#c-drm_property_create_enum).

  - DRM_MODE_PROP_BITMASK:
    Bitmask properties are enumeration properties that additionally
    restrict all enumerated values to the 0..63 range. Bitmask property
    instance values combine one or more of the enumerated bits defined
    by the property. Bitmask properties are created using
    [`drm_property_create_bitmask()`](#c-drm_property_create_bitmask).

  - DRM_MODE_PROP_OBJECT:
    Object properties are used to link modeset objects. This is used
    extensively in the atomic support to create the display pipeline,
    by linking [`drm_framebuffer`](#c-struct-drm_framebuffer) to [`drm_plane`](#c-struct-drm_plane), [`drm_plane`](#c-struct-drm_plane) to
    [`drm_crtc`](#c-struct-drm_crtc) and [`drm_connector`](#c-struct-drm_connector) to [`drm_crtc`](#c-struct-drm_crtc). An object property can
    only link to a specific type of [`drm_mode_object`](#c-struct-drm_mode_object), this limit is
    enforced by the core. Object properties are created using
    [`drm_property_create_object()`](#c-drm_property_create_object).

    Object properties work like blob properties, but in a more
    general fashion. They are limited to atomic drivers and must have
    the DRM_MODE_PROP_ATOMIC flag set.

  - DRM_MODE_PROP_BLOB:
    Blob properties store a binary blob without any format restriction.
    The binary blobs are created as KMS standalone objects, and blob
    property instance values store the ID of their associated blob
    object. Blob properties are created by calling
    [`drm_property_create()`](#c-drm_property_create) with DRM_MODE_PROP_BLOB as the type.

    Actual blob objects to contain blob data are created using
    [`drm_property_create_blob()`](#c-drm_property_create_blob), or through the corresponding IOCTL.

    Besides the built-in limit to only accept blob objects blob
    properties work exactly like object properties. The only reasons
    blob properties exist is backwards compatibility with existing
    userspace.

  In addition a property can have any combination of the below flags:

  - DRM_MODE_PROP_ATOMIC:
    Set for properties which encode atomic modeset state. Such
    properties are not exposed to legacy userspace.

  - DRM_MODE_PROP_IMMUTABLE:
    Set for properties whose values cannot be changed by
    userspace. The kernel is allowed to update the value of these
    properties. This is generally used to expose probe state to
    userspace, e.g. the EDID, or the connector path property on DP
    MST sinks. Kernel can update the value of an immutable property
    by calling [`drm_object_property_set_value()`](#c-drm_object_property_set_value).
- `name`: symbolic name of the properties
- `num_values`: size of the **values** array.
- `values`: Array with limits and values for the property. The
  interpretation of these limits is dependent upon the type per **flags**.
- `dev`: DRM device
- `enum_list`: List of `drm_prop_enum_list` structures with the symbolic names for
  enum and bitmask values.

**Description**

This structure represent a modeset object property. It combines both the name
of the property with the set of permissible values. This means that when a
driver wants to use a property with the same name on different objects, but
with different value ranges, then it must create property for each one. An
example would be rotation of [`drm_plane`](#c-struct-drm_plane), when e.g. the primary plane cannot
be rotated. But if both the name and the value range match, then the same
property structure can be instantiated multiple times for the same object.
Userspace must be able to cope with this and cannot assume that the same
symbolic property will have the same modeset object ID on all modeset
objects.

Properties are created by one of the special functions, as explained in
detail in the **flags** structure member.

To actually expose a property it must be attached to each object using
[`drm_object_attach_property()`](#c-drm_object_attach_property). Currently properties can only be attached to
[`drm_connector`](#c-struct-drm_connector), [`drm_crtc`](#c-struct-drm_crtc) and [`drm_plane`](#c-struct-drm_plane).

Properties are also used as the generic metadatatransport for the atomic
IOCTL. Everything that was set directly in structures in the legacy modeset
IOCTLs (like the plane source or destination windows, or e.g. the links to
the CRTC) is exposed as a property with the DRM_MODE_PROP_ATOMIC flag set.

#### <a id="c-struct-drm_property_blob"></a>`struct drm_property_blob`

Blob data for [`drm_property`](#c-struct-drm_property)

**Definition**

```c
struct drm_property_blob {
    struct drm_mode_object base;
    struct drm_device *dev;
    struct list_head head_global;
    struct list_head head_file;
    size_t length;
    void *data;
};
```

**Members**

- `base`: base KMS object
- `dev`: DRM device
- `head_global`: entry on the global blob list in
  [`drm_mode_config.property_blob_list`](#c-struct-drm_mode_config).
- `head_file`: entry on the per-file blob list in [`drm_file.blobs`](/kernel/hardware/gpu/drm-internals.md#c-struct-drm_file) list.
- `length`: size of the blob in bytes, invariant over the lifetime of the object
- `data`: actual data, embedded at the end of this structure

**Description**

Blobs are used to store bigger values than what fits directly into the 64
bits available for a [`drm_property`](#c-struct-drm_property).

Blobs are reference counted using [`drm_property_blob_get()`](#c-drm_property_blob_get) and
[`drm_property_blob_put()`](#c-drm_property_blob_put). They are created using [`drm_property_create_blob()`](#c-drm_property_create_blob).

#### <a id="c-drm_property_type_is"></a>`drm_property_type_is()`

```c
bool drm_property_type_is(struct drm_property *property, uint32_t type)
```

check the type of a property

**Parameters**

- `struct drm_property *property`: property to check
- `uint32_t type`: property type to compare with

**Description**

This is a helper function becauase the uapi encoding of property types is
a bit special for historical reasons.

#### <a id="c-drm_property_find"></a>`drm_property_find()`

```c
struct drm_property * drm_property_find(struct drm_device *dev, struct drm_file *file_priv, uint32_t id)
```

find property object

**Parameters**

- `struct drm_device *dev`: DRM device
- `struct drm_file *file_priv`: drm file to check for lease against.
- `uint32_t id`: property object id

**Description**

This function looks up the property object specified by id and returns it.



#### <a id="c-drm_property_create"></a>`drm_property_create()`

```c
struct drm_property * drm_property_create(struct drm_device *dev, u32 flags, const char *name, int num_values)
```

create a new property type

**Parameters**

- `struct drm_device *dev`: drm device
- `u32 flags`: flags specifying the property type
- `const char *name`: name of the property
- `int num_values`: number of pre-defined values

**Description**

This creates a new generic drm property which can then be attached to a drm
object with [`drm_object_attach_property()`](#c-drm_object_attach_property). The returned property object must
be freed with [`drm_property_destroy()`](#c-drm_property_destroy), which is done automatically when
calling [`drm_mode_config_cleanup()`](#c-drm_mode_config_cleanup).

**Return**

A pointer to the newly created property on success, NULL on failure.

#### <a id="c-drm_property_create_enum"></a>`drm_property_create_enum()`

```c
struct drm_property * drm_property_create_enum(struct drm_device *dev, u32 flags, const char *name, const struct drm_prop_enum_list *props, int num_values)
```

create a new enumeration property type

**Parameters**

- `struct drm_device *dev`: drm device
- `u32 flags`: flags specifying the property type
- `const char *name`: name of the property
- `const struct drm_prop_enum_list *props`: enumeration lists with property values
- `int num_values`: number of pre-defined values

**Description**

This creates a new generic drm property which can then be attached to a drm
object with [`drm_object_attach_property()`](#c-drm_object_attach_property). The returned property object must
be freed with [`drm_property_destroy()`](#c-drm_property_destroy), which is done automatically when
calling [`drm_mode_config_cleanup()`](#c-drm_mode_config_cleanup).

Userspace is only allowed to set one of the predefined values for enumeration
properties.

**Return**

A pointer to the newly created property on success, NULL on failure.

#### <a id="c-drm_property_create_bitmask"></a>`drm_property_create_bitmask()`

```c
struct drm_property * drm_property_create_bitmask(struct drm_device *dev, u32 flags, const char *name, const struct drm_prop_enum_list *props, int num_props, uint64_t supported_bits)
```

create a new bitmask property type

**Parameters**

- `struct drm_device *dev`: drm device
- `u32 flags`: flags specifying the property type
- `const char *name`: name of the property
- `const struct drm_prop_enum_list *props`: enumeration lists with property bitflags
- `int num_props`: size of the **props** array
- `uint64_t supported_bits`: bitmask of all supported enumeration values

**Description**

This creates a new bitmask drm property which can then be attached to a drm
object with [`drm_object_attach_property()`](#c-drm_object_attach_property). The returned property object must
be freed with [`drm_property_destroy()`](#c-drm_property_destroy), which is done automatically when
calling [`drm_mode_config_cleanup()`](#c-drm_mode_config_cleanup).

Compared to plain enumeration properties userspace is allowed to set any
or'ed together combination of the predefined property bitflag values

**Return**

A pointer to the newly created property on success, NULL on failure.

#### <a id="c-drm_property_create_range"></a>`drm_property_create_range()`

```c
struct drm_property * drm_property_create_range(struct drm_device *dev, u32 flags, const char *name, uint64_t min, uint64_t max)
```

create a new unsigned ranged property type

**Parameters**

- `struct drm_device *dev`: drm device
- `u32 flags`: flags specifying the property type
- `const char *name`: name of the property
- `uint64_t min`: minimum value of the property
- `uint64_t max`: maximum value of the property

**Description**

This creates a new generic drm property which can then be attached to a drm
object with [`drm_object_attach_property()`](#c-drm_object_attach_property). The returned property object must
be freed with [`drm_property_destroy()`](#c-drm_property_destroy), which is done automatically when
calling [`drm_mode_config_cleanup()`](#c-drm_mode_config_cleanup).

Userspace is allowed to set any unsigned integer value in the (min, max)
range inclusive.

**Return**

A pointer to the newly created property on success, NULL on failure.

#### <a id="c-drm_property_create_signed_range"></a>`drm_property_create_signed_range()`

```c
struct drm_property * drm_property_create_signed_range(struct drm_device *dev, u32 flags, const char *name, int64_t min, int64_t max)
```

create a new signed ranged property type

**Parameters**

- `struct drm_device *dev`: drm device
- `u32 flags`: flags specifying the property type
- `const char *name`: name of the property
- `int64_t min`: minimum value of the property
- `int64_t max`: maximum value of the property

**Description**

This creates a new generic drm property which can then be attached to a drm
object with [`drm_object_attach_property()`](#c-drm_object_attach_property). The returned property object must
be freed with [`drm_property_destroy()`](#c-drm_property_destroy), which is done automatically when
calling [`drm_mode_config_cleanup()`](#c-drm_mode_config_cleanup).

Userspace is allowed to set any signed integer value in the (min, max)
range inclusive.

**Return**

A pointer to the newly created property on success, NULL on failure.

#### <a id="c-drm_property_create_object"></a>`drm_property_create_object()`

```c
struct drm_property * drm_property_create_object(struct drm_device *dev, u32 flags, const char *name, uint32_t type)
```

create a new object property type

**Parameters**

- `struct drm_device *dev`: drm device
- `u32 flags`: flags specifying the property type
- `const char *name`: name of the property
- `uint32_t type`: object type from DRM_MODE_OBJECT_* defines

**Description**

This creates a new generic drm property which can then be attached to a drm
object with [`drm_object_attach_property()`](#c-drm_object_attach_property). The returned property object must
be freed with [`drm_property_destroy()`](#c-drm_property_destroy), which is done automatically when
calling [`drm_mode_config_cleanup()`](#c-drm_mode_config_cleanup).

Userspace is only allowed to set this to any property value of the given
**type**. Only useful for atomic properties, which is enforced.

**Return**

A pointer to the newly created property on success, NULL on failure.

#### <a id="c-drm_property_create_bool"></a>`drm_property_create_bool()`

```c
struct drm_property * drm_property_create_bool(struct drm_device *dev, u32 flags, const char *name)
```

create a new boolean property type

**Parameters**

- `struct drm_device *dev`: drm device
- `u32 flags`: flags specifying the property type
- `const char *name`: name of the property

**Description**

This creates a new generic drm property which can then be attached to a drm
object with [`drm_object_attach_property()`](#c-drm_object_attach_property). The returned property object must
be freed with [`drm_property_destroy()`](#c-drm_property_destroy), which is done automatically when
calling [`drm_mode_config_cleanup()`](#c-drm_mode_config_cleanup).

This is implemented as a ranged property with only {0, 1} as valid values.

**Return**

A pointer to the newly created property on success, NULL on failure.

#### <a id="c-drm_property_add_enum"></a>`drm_property_add_enum()`

```c
int drm_property_add_enum(struct drm_property *property, uint64_t value, const char *name)
```

add a possible value to an enumeration property

**Parameters**

- `struct drm_property *property`: enumeration property to change
- `uint64_t value`: value of the new enumeration
- `const char *name`: symbolic name of the new enumeration

**Description**

This functions adds enumerations to a property.

It's use is deprecated, drivers should use one of the more specific helpers
to directly create the property with all enumerations already attached.

**Return**

Zero on success, error code on failure.

#### <a id="c-drm_property_destroy"></a>`drm_property_destroy()`

```c
void drm_property_destroy(struct drm_device *dev, struct drm_property *property)
```

destroy a drm property

**Parameters**

- `struct drm_device *dev`: drm device
- `struct drm_property *property`: property to destroy

**Description**

This function frees a property including any attached resources like
enumeration values.

#### <a id="c-drm_property_create_blob"></a>`drm_property_create_blob()`

```c
struct drm_property_blob * drm_property_create_blob(struct drm_device *dev, size_t length, const void *data)
```

Create new blob property

**Parameters**

- `struct drm_device *dev`: DRM device to create property for
- `size_t length`: Length to allocate for blob data
- `const void *data`: If specified, copies data into blob

**Description**

Creates a new blob property for a specified DRM device, optionally
copying data. Note that blob properties are meant to be invariant, hence the
data must be filled out before the blob is used as the value of any property.

**Return**

New blob property with a single reference on success, or an ERR_PTR
value on failure.

#### <a id="c-drm_property_blob_put"></a>`drm_property_blob_put()`

```c
void drm_property_blob_put(struct drm_property_blob *blob)
```

release a blob property reference

**Parameters**

- `struct drm_property_blob *blob`: DRM blob property

**Description**

Releases a reference to a blob property. May free the object.

#### <a id="c-drm_property_blob_get"></a>`drm_property_blob_get()`

```c
struct drm_property_blob * drm_property_blob_get(struct drm_property_blob *blob)
```

acquire blob property reference

**Parameters**

- `struct drm_property_blob *blob`: DRM blob property

**Description**

Acquires a reference to an existing blob property. Returns **blob**, which
allows this to be used as a shorthand in assignments.

#### <a id="c-drm_property_lookup_blob"></a>`drm_property_lookup_blob()`

```c
struct drm_property_blob * drm_property_lookup_blob(struct drm_device *dev, uint32_t id)
```

look up a blob property and take a reference

**Parameters**

- `struct drm_device *dev`: drm device
- `uint32_t id`: id of the blob property

**Description**

If successful, this takes an additional reference to the blob property.
callers need to make sure to eventually unreferenced the returned property
again, using [`drm_property_blob_put()`](#c-drm_property_blob_put).

**Return**

NULL on failure, pointer to the blob on success.

#### <a id="c-drm_property_replace_global_blob"></a>`drm_property_replace_global_blob()`

```c
int drm_property_replace_global_blob(struct drm_device *dev, struct drm_property_blob **replace, size_t length, const void *data, struct drm_mode_object *obj_holds_id, struct drm_property *prop_holds_id)
```

replace existing blob property

**Parameters**

- `struct drm_device *dev`: drm device
- `struct drm_property_blob **replace`: location of blob property pointer to be replaced
- `size_t length`: length of data for new blob, or 0 for no data
- `const void *data`: content for new blob, or NULL for no data
- `struct drm_mode_object *obj_holds_id`: optional object for property holding blob ID
- `struct drm_property *prop_holds_id`: optional property holding blob ID
  **return** 0 on success or error on failure

**Description**

This function will replace a global property in the blob list, optionally
updating a property which holds the ID of that property.

If length is 0 or data is NULL, no new blob will be created, and the holding
property, if specified, will be set to 0.

Access to the replace pointer is assumed to be protected by the caller, e.g.
by holding the relevant modesetting object lock for its parent.

For example, a drm_connector has a 'PATH' property, which contains the ID
of a blob property with the value of the MST path information. Calling this
function with replace pointing to the connector's path_blob_ptr, length and
data set for the new path information, obj_holds_id set to the connector's
base object, and prop_holds_id set to the path property name, will perform
a completely atomic update. The access to path_blob_ptr is protected by the
caller holding a lock on the connector.

#### <a id="c-drm_property_replace_blob"></a>`drm_property_replace_blob()`

```c
bool drm_property_replace_blob(struct drm_property_blob **blob, struct drm_property_blob *new_blob)
```

replace a blob property

**Parameters**

- `struct drm_property_blob **blob`: a pointer to the member blob to be replaced
- `struct drm_property_blob *new_blob`: the new blob to replace with

**Return**

true if the blob was in fact replaced.

#### <a id="c-drm_property_replace_blob_from_id"></a>`drm_property_replace_blob_from_id()`

```c
int drm_property_replace_blob_from_id(struct drm_device *dev, struct drm_property_blob **blob, uint64_t blob_id, ssize_t max_size, ssize_t expected_size, ssize_t expected_elem_size, bool *replaced)
```

replace a blob property taking a reference

**Parameters**

- `struct drm_device *dev`: DRM device
- `struct drm_property_blob **blob`: a pointer to the member blob to be replaced
- `uint64_t blob_id`: the id of the new blob to replace with
- `ssize_t max_size`: the maximum size of the blob property for variable-size blobs
- `ssize_t expected_size`: expected size of the blob property
- `ssize_t expected_elem_size`: expected size of an element in the blob property
- `bool *replaced`: if the blob was in fact replaced

**Description**

Look up the new blob from id, take its reference, check expected sizes of
the blob and its element and replace the old blob by the new one. Advertise
if the replacement operation was successful.

**Return**

true if the blob was in fact replaced. -EINVAL if the new blob was
not found or sizes don't match.


<a id="rst-standard-connector-properties-1"></a>
<a id="rst-standard-connector-properties"></a>

### Standard Connector Properties


DRM connectors have a few standardized properties:

- EDID:
  Blob property which contains the current EDID read from the sink. This
  is useful to parse sink identification information like vendor, model
  and serial. Drivers should update this property by calling
  [`drm_connector_update_edid_property()`](/kernel/hardware/gpu/drm-kms-helpers.md#c-drm_connector_update_edid_property), usually after having parsed
  the EDID using [`drm_add_edid_modes()`](/kernel/hardware/gpu/drm-kms-helpers.md#c-drm_add_edid_modes). Userspace cannot change this
  property.

  User-space should not parse the EDID to obtain information exposed via
  other KMS properties (because the kernel might apply limits, quirks or
  fixups to the EDID). For instance, user-space should not try to parse
  mode lists from the EDID.
- DPMS:
  Legacy property for setting the power state of the connector. For atomic
  drivers this is only provided for backwards compatibility with existing
  drivers, it remaps to controlling the "ACTIVE" property on the CRTC the
  connector is linked to. Drivers should never set this property directly,
  it is handled by the DRM core by calling the [`drm_connector_funcs.dpms`](#c-struct-drm_connector_funcs)
  callback. For atomic drivers the remapping to the "ACTIVE" property is
  implemented in the DRM core.

  On atomic drivers any DPMS setproperty ioctl where the value does not
  change is completely skipped, otherwise a full atomic commit will occur.
  On legacy drivers the exact behavior is driver specific.

  Note that this property cannot be set through the MODE_ATOMIC ioctl,
  userspace must use "ACTIVE" on the CRTC instead.

  WARNING:

  For userspace also running on legacy drivers the "DPMS" semantics are a
  lot more complicated. First, userspace cannot rely on the "DPMS" value
  returned by the GETCONNECTOR actually reflecting reality, because many
  drivers fail to update it. For atomic drivers this is taken care of in
  [`drm_atomic_helper_update_legacy_modeset_state()`](/kernel/hardware/gpu/drm-kms-helpers.md#c-drm_atomic_helper_update_legacy_modeset_state).

  The second issue is that the DPMS state is only well-defined when the
  connector is connected to a CRTC. In atomic the DRM core enforces that
  "ACTIVE" is off in such a case, no such checks exists for "DPMS".

  Finally, when enabling an output using the legacy SETCONFIG ioctl then
  "DPMS" is forced to ON. But see above, that might not be reflected in
  the software value on legacy drivers.

  Summarizing: Only set "DPMS" when the connector is known to be enabled,
  assume that a successful SETCONFIG call also sets "DPMS" to on, and
  never read back the value of "DPMS" because it can be incorrect.
- PATH:
  Connector path property to identify how this sink is physically
  connected. Used by DP MST. This should be set by calling
  [`drm_connector_set_path_property()`](#c-drm_connector_set_path_property), in the case of DP MST with the
  path property the MST manager created. Userspace cannot change this
  property.

  In the case of DP MST, the property has the format
  `mst:<parent>-<ports>` where `<parent>` is the KMS object ID of the
  parent connector and `<ports>` is a hyphen-separated list of DP MST
  port numbers. Note, KMS object IDs are not guaranteed to be stable
  across reboots.
- TILE:
  Connector tile group property to indicate how a set of DRM connector
  compose together into one logical screen. This is used by both high-res
  external screens (often only using a single cable, but exposing multiple
  DP MST sinks), or high-res integrated panels (like dual-link DSI) which
  are not gen-locked. Note that for tiled panels which are genlocked, like
  dual-link LVDS or dual-link DSI, the driver should try to not expose the
  tiling and virtualise both [`drm_crtc`](#c-struct-drm_crtc) and [`drm_plane`](#c-struct-drm_plane) if needed. Drivers
  should update this value using [`drm_connector_set_tile_property()`](#c-drm_connector_set_tile_property).
  Userspace cannot change this property.
- link-status:
  Connector link-status property to indicate the status of link. The
  default value of link-status is "GOOD". If something fails during or
  after modeset, the kernel driver may set this to "BAD" and issue a
  hotplug uevent. Drivers should update this value using
  [`drm_connector_set_link_status_property()`](#c-drm_connector_set_link_status_property).

  When user-space receives the hotplug uevent and detects a "BAD"
  link-status, the sink doesn't receive pixels anymore (e.g. the screen
  becomes completely black). The list of available modes may have
  changed. User-space is expected to pick a new mode if the current one
  has disappeared and perform a new modeset with link-status set to
  "GOOD" to re-enable the connector.

  If multiple connectors share the same CRTC and one of them gets a "BAD"
  link-status, the other are unaffected (ie. the sinks still continue to
  receive pixels).

  When user-space performs an atomic commit on a connector with a "BAD"
  link-status without resetting the property to "GOOD", the sink may
  still not receive pixels. When user-space performs an atomic commit
  which resets the link-status property to "GOOD" without the
  ALLOW_MODESET flag set, it might fail because a modeset is required.

  User-space can only change link-status to "GOOD", changing it to "BAD"
  is a no-op.

  For backwards compatibility with non-atomic userspace the kernel
  tries to automatically set the link-status back to "GOOD" in the
  SETCRTC IOCTL. This might fail if the mode is no longer valid, similar
  to how it might fail if a different screen has been connected in the
  interim.
- non_desktop:
  Indicates the output should be ignored for purposes of displaying a
  standard desktop environment or console. This is most likely because
  the output device is not rectilinear.
- Content Protection:
  This property is used by userspace to request the kernel protect future
  content communicated over the link. When requested, kernel will apply
  the appropriate means of protection (most often HDCP), and use the
  property to tell userspace the protection is active.

  Drivers can set this up by calling
  [`drm_connector_attach_content_protection_property()`](/kernel/hardware/gpu/drm-kms-helpers.md#c-drm_connector_attach_content_protection_property) on initialization.

  The value of this property can be one of the following:

  DRM_MODE_CONTENT_PROTECTION_UNDESIRED = 0
  The link is not protected, content is transmitted in the clear.
  DRM_MODE_CONTENT_PROTECTION_DESIRED = 1
  Userspace has requested content protection, but the link is not
  currently protected. When in this state, kernel should enable
  Content Protection as soon as possible.
  DRM_MODE_CONTENT_PROTECTION_ENABLED = 2
  Userspace has requested content protection, and the link is
  protected. Only the driver can set the property to this value.
  If userspace attempts to set to ENABLED, kernel will return
  -EINVAL.

  A few guidelines:

  - DESIRED state should be preserved until userspace de-asserts it by
    setting the property to UNDESIRED. This means ENABLED should only
    transition to UNDESIRED when the user explicitly requests it.
  - If the state is DESIRED, kernel should attempt to re-authenticate the
    link whenever possible. This includes across disable/enable, dpms,
    hotplug, downstream device changes, link status failures, etc..
  - Kernel sends uevent with the connector id and property id through
    **drm_hdcp_update_content_protection**, upon below kernel triggered
    scenarios:

    - DESIRED -> ENABLED (authentication success)
    - ENABLED -> DESIRED (termination of authentication)
  - Please note no uevents for userspace triggered property state changes,
    which can't fail such as

    - DESIRED/ENABLED -> UNDESIRED
    - UNDESIRED -> DESIRED
  - Userspace is responsible for polling the property or listen to uevents
    to determine when the value transitions from ENABLED to DESIRED.
    This signifies the link is no longer protected and userspace should
    take appropriate action (whatever that might be).

- HDCP Content Type:
  This Enum property is used by the userspace to declare the content type
  of the display stream, to kernel. Here display stream stands for any
  display content that userspace intended to display through HDCP
  encryption.

  Content Type of a stream is decided by the owner of the stream, as
  "HDCP Type0" or "HDCP Type1".

  The value of the property can be one of the below:
  - "HDCP Type0": DRM_MODE_HDCP_CONTENT_TYPE0 = 0
  - "HDCP Type1": DRM_MODE_HDCP_CONTENT_TYPE1 = 1

  When kernel starts the HDCP authentication (see "Content Protection"
  for details), it uses the content type in "HDCP Content Type"
  for performing the HDCP authentication with the display sink.

  Please note in HDCP spec versions, a link can be authenticated with
  HDCP 2.2 for Content Type 0/Content Type 1. Where as a link can be
  authenticated with HDCP1.4 only for Content Type 0(though it is implicit
  in nature. As there is no reference for Content Type in HDCP1.4).

  HDCP2.2 authentication protocol itself takes the "Content Type" as a
  parameter, which is a input for the DP HDCP2.2 encryption algo.

  In case of Type 0 content protection request, kernel driver can choose
  either of HDCP spec versions 1.4 and 2.2. When HDCP2.2 is used for
  "HDCP Type 0", a HDCP 2.2 capable repeater in the downstream can send
  that content to a HDCP 1.4 authenticated HDCP sink (Type0 link).
  But if the content is classified as "HDCP Type 1", above mentioned
  HDCP 2.2 repeater wont send the content to the HDCP sink as it can't
  authenticate the HDCP1.4 capable sink for "HDCP Type 1".

  Please note userspace can be ignorant of the HDCP versions used by the
  kernel driver to achieve the "HDCP Content Type".

  At current scenario, classifying a content as Type 1 ensures that the
  content will be displayed only through the HDCP2.2 encrypted link.

  Note that the HDCP Content Type property is introduced at HDCP 2.2, and
  defaults to type 0. It is only exposed by drivers supporting HDCP 2.2
  (hence supporting Type 0 and Type 1). Based on how next versions of
  HDCP specs are defined content Type could be used for higher versions
  too.

  If content type is changed when "Content Protection" is not UNDESIRED,
  then kernel will disable the HDCP and re-enable with new type in the
  same atomic commit. And when "Content Protection" is ENABLED, it means
  that link is HDCP authenticated and encrypted, for the transmission of
  the Type of stream mentioned at "HDCP Content Type".

- HDR_OUTPUT_METADATA:
  Connector property to enable userspace to send HDR Metadata to
  driver. This metadata is based on the composition and blending
  policies decided by user, taking into account the hardware and
  sink capabilities. The driver gets this metadata and creates a
  Dynamic Range and Mastering Infoframe (DRM) in case of HDMI,
  SDP packet (Non-audio INFOFRAME SDP v1.3) for DP. This is then
  sent to sink. This notifies the sink of the upcoming frame's Color
  Encoding and Luminance parameters.

  Userspace first need to detect the HDR capabilities of sink by
  reading and parsing the EDID. Details of HDR metadata for HDMI
  are added in CTA 861.G spec. For DP , its defined in VESA DP
  Standard v1.4. It needs to then get the metadata information
  of the video/game/app content which are encoded in HDR (basically
  using HDR transfer functions). With this information it needs to
  decide on a blending policy and compose the relevant
  layers/overlays into a common format. Once this blending is done,
  userspace will be aware of the metadata of the composed frame to
  be send to sink. It then uses this property to communicate this
  metadata to driver which then make a Infoframe packet and sends
  to sink based on the type of encoder connected.

  Userspace will be responsible to do Tone mapping operation in case:
  - Some layers are HDR and others are SDR
  - HDR layers luminance is not same as sink

  It will even need to do colorspace conversion and get all layers
  to one common colorspace for blending. It can use either GL, Media
  or display engine to get this done based on the capabilities of the
  associated hardware.

  Driver expects metadata to be put in [`struct hdr_output_metadata`](/kernel/hardware/gpu/drm-uapi.md#c-struct-hdr_output_metadata)
  structure from userspace. This is received as blob and stored in
  [`drm_connector_state.hdr_output_metadata`](#c-struct-drm_connector_state). It parses EDID and saves the
  sink metadata in [`struct hdr_sink_metadata`](/kernel/hardware/gpu/drm-kms-helpers.md#c-struct-hdr_sink_metadata), as
  [`drm_connector.display_info`](#c-struct-drm_connector).hdr_sink_metadata.  Driver uses
  `drm_hdmi_infoframe_set_hdr_metadata()` helper to set the HDR metadata,
  [`hdmi_drm_infoframe_pack()`](/kernel/hardware/gpu/drm-kms-helpers.md#c-hdmi_drm_infoframe_pack) to pack the infoframe as per spec, in case of
  HDMI encoder.

- max bpc:
  This range property is used by userspace to limit the bit depth. When
  used the driver would limit the bpc in accordance with the valid range
  supported by the hardware and sink. Drivers to use the function
  [`drm_connector_attach_max_bpc_property()`](#c-drm_connector_attach_max_bpc_property) to create and attach the
  property to the connector during initialization.

Connectors also have one standardized atomic property:

- CRTC_ID:
  Mode object ID of the [`drm_crtc`](#c-struct-drm_crtc) this connector should be connected to.

Connectors for LCD panels may also have one standardized property:

- panel orientation:
  On some devices the LCD panel is mounted in the casing in such a way
  that the up/top side of the panel does not match with the top side of
  the device. Userspace can use this property to check for this.
  Note that input coordinates from touchscreens (input devices with
  INPUT_PROP_DIRECT) will still map 1:1 to the actual LCD panel
  coordinates, so if userspace rotates the picture to adjust for
  the orientation it must also apply the same transformation to the
  touchscreen input coordinates. This property is initialized by calling
  [`drm_connector_set_panel_orientation()`](#c-drm_connector_set_panel_orientation) or
  [`drm_connector_set_panel_orientation_with_quirk()`](#c-drm_connector_set_panel_orientation_with_quirk)

- scaling mode:
  This property defines how a non-native mode is upscaled to the native
  mode of an LCD panel:

  None:
  No upscaling happens, scaling is left to the panel. Not all
  drivers expose this mode.
  Full:
  The output is upscaled to the full resolution of the panel,
  ignoring the aspect ratio.
  Center:
  No upscaling happens, the output is centered within the native
  resolution the panel.
  Full aspect:
  The output is upscaled to maximize either the width or height
  while retaining the aspect ratio.

  This property should be set up by calling
  [`drm_connector_attach_scaling_mode_property()`](#c-drm_connector_attach_scaling_mode_property). Note that drivers
  can also expose this property to external outputs, in which case they
  must support "None", which should be the default (since external screens
  have a built-in scaler).

- subconnector:
  This property is used by DVI-I, TVout and DisplayPort to indicate different
  connector subtypes. Enum values more or less match with those from main
  connector types.
  For DVI-I and TVout there is also a matching property "select subconnector"
  allowing to switch between signal types.
  DP subconnector corresponds to a downstream port.

- privacy-screen sw-state, privacy-screen hw-state:
  These 2 optional properties can be used to query the state of the
  electronic privacy screen that is available on some displays; and in
  some cases also control the state. If a driver implements these
  properties then both properties must be present.

  "privacy-screen hw-state" is read-only and reflects the actual state
  of the privacy-screen, possible values: "Enabled", "Disabled,
  "Enabled-locked", "Disabled-locked". The locked states indicate
  that the state cannot be changed through the DRM API. E.g. there
  might be devices where the firmware-setup options, or a hardware
  slider-switch, offer always on / off modes.

  "privacy-screen sw-state" can be set to change the privacy-screen state
  when not locked. In this case the driver must update the hw-state
  property to reflect the new state on completion of the commit of the
  sw-state property. Setting the sw-state property when the hw-state is
  locked must be interpreted by the driver as a request to change the
  state to the set state when the hw-state becomes unlocked. E.g. if
  "privacy-screen hw-state" is "Enabled-locked" and the sw-state
  gets set to "Disabled" followed by the user unlocking the state by
  changing the slider-switch position, then the driver must set the
  state to "Disabled" upon receiving the unlock event.

  In some cases the privacy-screen's actual state might change outside of
  control of the DRM code. E.g. there might be a firmware handled hotkey
  which toggles the actual state, or the actual state might be changed
  through another userspace API such as writing /proc/acpi/ibm/lcdshadow.
  In this case the driver must update both the hw-state and the sw-state
  to reflect the new value, overwriting any pending state requests in the
  sw-state. Any pending sw-state requests are thus discarded.

  Note that the ability for the state to change outside of control of
  the DRM master process means that userspace must not cache the value
  of the sw-state. Caching the sw-state value and including it in later
  atomic commits may lead to overriding a state change done through e.g.
  a firmware handled hotkey. Therefor userspace must not include the
  privacy-screen sw-state in an atomic commit unless it wants to change
  its value.

- left margin, right margin, top margin, bottom margin:
  Add margins to the connector's viewport. This is typically used to
  mitigate overscan on TVs.

  The value is the size in pixels of the black border which will be
  added. The attached CRTC's content will be scaled to fill the whole
  area inside the margin.

  The margins configuration might be sent to the sink, e.g. via HDMI AVI
  InfoFrames.

  Drivers can set up these properties by calling
  [`drm_mode_create_tv_margin_properties()`](#c-drm_mode_create_tv_margin_properties).

- Colorspace:
  This property is used to inform the driver about the color encoding
  user space configured the pixel operation properties to produce.
  The variants set the colorimetry, transfer characteristics, and which
  YCbCr conversion should be used when necessary.
  The transfer characteristics from HDR_OUTPUT_METADATA takes precedence
  over this property.
  User space always configures the pixel operation properties to produce
  full quantization range data (see the Broadcast RGB property).

  Drivers inform the sink about what colorimetry, transfer
  characteristics, YCbCr conversion, and quantization range to expect
  (this can depend on the output mode, output format and other
  properties). Drivers also convert the user space provided data to what
  the sink expects.

  User space has to check if the sink supports all of the possible
  colorimetries that the driver is allowed to pick by parsing the EDID.

  For historical reasons this property exposes a number of variants which
  result in undefined behavior.

  Default:
  The behavior is driver-specific.

  BT2020_RGB:

  BT2020_YCC:
  User space configures the pixel operation properties to produce
  RGB content with Rec. ITU-R BT.2020 colorimetry, Rec.
  ITU-R BT.2020 (Table 4, RGB) transfer characteristics and full
  quantization range.
  User space can use the HDR_OUTPUT_METADATA property to set the
  transfer characteristics to PQ (Rec. ITU-R BT.2100 Table 4) or
  HLG (Rec. ITU-R BT.2100 Table 5) in which case, user space
  configures pixel operation properties to produce content with
  the respective transfer characteristics.
  User space has to make sure the sink supports Rec.
  ITU-R BT.2020 R'G'B' and Rec. ITU-R BT.2020 Y'C'BC'R
  colorimetry.
  Drivers can configure the sink to use an RGB format, tell the
  sink to expect Rec. ITU-R BT.2020 R'G'B' colorimetry and convert
  to the appropriate quantization range.
  Drivers can configure the sink to use a YCbCr format, tell the
  sink to expect Rec. ITU-R BT.2020 Y'C'BC'R colorimetry, convert
  to YCbCr using the Rec. ITU-R BT.2020 non-constant luminance
  conversion matrix and convert to the appropriate quantization
  range.
  The variants BT2020_RGB and BT2020_YCC are equivalent and the
  driver chooses between RGB and YCbCr on its own.

  SMPTE_170M_YCC:
  BT709_YCC:
  XVYCC_601:
  XVYCC_709:
  SYCC_601:
  opYCC_601:
  opRGB:
  BT2020_CYCC:
  DCI-P3_RGB_D65:
  DCI-P3_RGB_Theater:
  RGB_WIDE_FIXED:
  RGB_WIDE_FLOAT:

  BT601_YCC:
  The behavior is undefined.

Because between HDMI and DP have different colorspaces,
[`drm_mode_create_hdmi_colorspace_property()`](#c-drm_mode_create_hdmi_colorspace_property) is used for HDMI connector and
[`drm_mode_create_dp_colorspace_property()`](#c-drm_mode_create_dp_colorspace_property) is used for DP connector.


<a id="rst-hdmi-specific-connector-properties"></a>

### HDMI Specific Connector Properties


- Broadcast RGB (HDMI specific)

  Indicates the Quantization Range (Full vs Limited) used. The color
  processing pipeline will be adjusted to match the value of the
  property, and the Infoframes will be generated and sent accordingly.

  This property is only relevant if the HDMI output format is RGB. If
  it's one of the YCbCr variant, it will be ignored.

  The CRTC attached to the connector must be configured by user-space to
  always produce full-range pixels.

  The value of this property can be one of the following:

  Automatic:
  The quantization range is selected automatically based on the
  mode according to the HDMI specifications (HDMI 1.4b - Section
  6.6 - Video Quantization Ranges).

  Full:
  Full quantization range is forced.

  Limited 16:235:
  Limited quantization range is forced. Unlike the name suggests,
  this works for any number of bits-per-component.

  Property values other than Automatic can result in colors being off (if
  limited is selected but the display expects full), or a black screen
  (if full is selected but the display expects limited).

  Drivers can set up this property by calling
  [`drm_connector_attach_broadcast_rgb_property()`](#c-drm_connector_attach_broadcast_rgb_property).

- content type (HDMI specific):
  Indicates content type setting to be used in HDMI infoframes to indicate
  content type for the external device, so that it adjusts its display
  settings accordingly.

  The value of this property can be one of the following:

  No Data:
  Content type is unknown
  Graphics:
  Content type is graphics
  Photo:
  Content type is photo
  Cinema:
  Content type is cinema
  Game:
  Content type is game

  The meaning of each content type is defined in CTA-861-G table 15.

  Drivers can set up this property by calling
  [`drm_connector_attach_content_type_property()`](#c-drm_connector_attach_content_type_property). Decoding to
  infoframe values is done through `drm_hdmi_avi_infoframe_content_type()`.


<a id="rst-analog-tv-specific-connector-properties"></a>

### Analog TV Specific Connector Properties


- TV Mode:
  Indicates the TV Mode used on an analog TV connector. The value
  of this property can be one of the following:

  NTSC:
  TV Mode is CCIR System M (aka 525-lines) together with
  the NTSC Color Encoding.

  NTSC-443:

  TV Mode is CCIR System M (aka 525-lines) together with
  the NTSC Color Encoding, but with a color subcarrier
  frequency of 4.43MHz

  NTSC-J:

  TV Mode is CCIR System M (aka 525-lines) together with
  the NTSC Color Encoding, but with a black level equal to
  the blanking level.

  PAL:

  TV Mode is CCIR System B (aka 625-lines) together with
  the PAL Color Encoding.

  PAL-M:

  TV Mode is CCIR System M (aka 525-lines) together with
  the PAL Color Encoding.

  PAL-N:

  TV Mode is CCIR System N together with the PAL Color
  Encoding, a color subcarrier frequency of 3.58MHz, the
  SECAM color space, and narrower channels than other PAL
  variants.

  SECAM:

  TV Mode is CCIR System B (aka 625-lines) together with
  the SECAM Color Encoding.

  Mono:

  Use timings appropriate to the DRM mode, including
  equalizing pulses for a 525-line or 625-line mode,
  with no pedestal or color encoding.

  Drivers can set up this property by calling
  [`drm_mode_create_tv_properties()`](#c-drm_mode_create_tv_properties).


<a id="rst-standard-crtc-properties"></a>

### Standard CRTC Properties


DRM CRTCs have a few standardized properties:

- ACTIVE:
  Atomic property for setting the power state of the CRTC. When set to 1
  the CRTC will actively display content. When set to 0 the CRTC will be
  powered off. There is no expectation that user-space will reset CRTC
  resources like the mode and planes when setting ACTIVE to 0.

  User-space can rely on an ACTIVE change to 1 to never fail an atomic
  test as long as no other property has changed. If a change to ACTIVE
  fails an atomic test, this is a driver bug. For this reason setting
  ACTIVE to 0 must not release internal resources (like reserved memory
  bandwidth or clock generators).

  Note that the legacy DPMS property on connectors is internally routed
  to control this property for atomic drivers.
- MODE_ID:
  Atomic property for setting the CRTC display timings. The value is the
  ID of a blob containing the DRM mode info. To disable the CRTC,
  user-space must set this property to 0.

  Setting MODE_ID to 0 will release reserved resources for the CRTC.
- SCALING_FILTER:
  Atomic property for setting the scaling filter for CRTC scaler

  The value of this property can be one of the following:

  Default:
  Driver's default scaling filter
  Nearest Neighbor:
  Nearest Neighbor scaling filter
- SHARPNESS_STRENGTH:
  Atomic property for setting the sharpness strength/intensity by userspace.

  The value of this property is set as an integer value ranging
  from 0 - 255 where:

  0: Sharpness feature is disabled(default value).

  1: Minimum sharpness.

  255: Maximum sharpness.

  User can gradually increase or decrease the sharpness level and can
  set the optimum value depending on content.
  This value will be passed to kernel through the UAPI.
  The setting of this property does not require modeset.
  The sharpness effect takes place post blending on the final composed output.
  If the feature is disabled, the content remains same without any sharpening effect
  and when this feature is applied, it enhances the clarity of the content.


<a id="rst-standard-plane-properties"></a>

### Standard Plane Properties


DRM planes have a few standardized properties:

- type:
  Immutable property describing the type of the plane.

  For user-space which has enabled the [`DRM_CLIENT_CAP_ATOMIC`](/kernel/hardware/gpu/drm-uapi.md#c-DRM_CLIENT_CAP_ATOMIC) capability,
  the plane type is just a hint and is mostly superseded by atomic
  test-only commits. The type hint can still be used to come up more
  easily with a plane configuration accepted by the driver.

  The value of this property can be one of the following:

  "Primary":
  To light up a CRTC, attaching a primary plane is the most likely to
  work if it covers the whole CRTC and doesn't have scaling or
  cropping set up.

  Drivers may support more features for the primary plane, user-space
  can find out with test-only atomic commits.

  Some primary planes are implicitly used by the kernel in the legacy
  IOCTLs `DRM_IOCTL_MODE_SETCRTC` and `DRM_IOCTL_MODE_PAGE_FLIP`.
  Therefore user-space must not mix explicit usage of any primary
  plane (e.g. through an atomic commit) with these legacy IOCTLs.

  "Cursor":
  To enable this plane, using a framebuffer configured without scaling
  or cropping and with the following properties is the most likely to
  work:

  - If the driver provides the capabilities [`DRM_CAP_CURSOR_WIDTH`](/kernel/hardware/gpu/drm-uapi.md#c-DRM_CAP_CURSOR_WIDTH) and
    [`DRM_CAP_CURSOR_HEIGHT`](/kernel/hardware/gpu/drm-uapi.md#c-DRM_CAP_CURSOR_HEIGHT), create the framebuffer with this size.
    Otherwise, create a framebuffer with the size 64x64.
  - If the driver doesn't support modifiers, create a framebuffer with
    a linear layout. Otherwise, use the IN_FORMATS plane property.

  Drivers may support more features for the cursor plane, user-space
  can find out with test-only atomic commits.

  Some cursor planes are implicitly used by the kernel in the legacy
  IOCTLs `DRM_IOCTL_MODE_CURSOR` and `DRM_IOCTL_MODE_CURSOR2`.
  Therefore user-space must not mix explicit usage of any cursor
  plane (e.g. through an atomic commit) with these legacy IOCTLs.

  Some drivers may support cursors even if no cursor plane is exposed.
  In this case, the legacy cursor IOCTLs can be used to configure the
  cursor.

  "Overlay":
  Neither primary nor cursor.

  Overlay planes are the only planes exposed when the
  [`DRM_CLIENT_CAP_UNIVERSAL_PLANES`](/kernel/hardware/gpu/drm-uapi.md#c-DRM_CLIENT_CAP_UNIVERSAL_PLANES) capability is disabled.

- IN_FORMATS:
  Blob property which contains the set of buffer format and modifier
  pairs supported by this plane. The blob is a struct
  drm_format_modifier_blob. Without this property the plane doesn't
  support buffers with modifiers. Userspace cannot change this property.

  Note that userspace can check the [`DRM_CAP_ADDFB2_MODIFIERS`](/kernel/hardware/gpu/drm-uapi.md#c-DRM_CAP_ADDFB2_MODIFIERS) driver
  capability for general modifier support. If this flag is set then every
  plane will have the IN_FORMATS property, even when it only supports
  DRM_FORMAT_MOD_LINEAR. Before linux kernel release v5.1 there have been
  various bugs in this area with inconsistencies between the capability
  flag and per-plane properties.

- IN_FORMATS_ASYNC:
  Blob property which contains the set of buffer format and modifier
  pairs supported by this plane for asynchronous flips. The blob is a struct
  drm_format_modifier_blob. Userspace cannot change this property. This is an
  optional property and if not present then user should expect a failure in
  atomic ioctl when the modifier/format is not supported by that plane under
  asynchronous flip.

- SIZE_HINTS:
  Blob property which contains the set of recommended plane size
  which can used for simple "cursor like" use cases (eg. no scaling).
  Using these hints frees userspace from extensive probing of
  supported plane sizes through atomic/setcursor ioctls.

  The blob contains an array of struct drm_plane_size_hint, in
  order of preference. For optimal usage userspace should pick
  the first size that satisfies its own requirements.

  Drivers should only attach this property to planes that
  support a very limited set of sizes.

  Note that property value 0 (ie. no blob) is reserved for potential
  future use. Current userspace is expected to ignore the property
  if the value is 0, and fall back to some other means (eg.
  [`DRM_CAP_CURSOR_WIDTH`](/kernel/hardware/gpu/drm-uapi.md#c-DRM_CAP_CURSOR_WIDTH) and [`DRM_CAP_CURSOR_HEIGHT`](/kernel/hardware/gpu/drm-uapi.md#c-DRM_CAP_CURSOR_HEIGHT)) to determine
  the appropriate plane size to use.


<a id="rst-plane-composition-properties-1"></a>
<a id="rst-plane-composition-properties"></a>

### Plane Composition Properties


The basic plane composition model supported by standard plane properties only
has a source rectangle (in logical pixels within the [`drm_framebuffer`](#c-struct-drm_framebuffer)), with
sub-pixel accuracy, which is scaled up to a pixel-aligned destination
rectangle in the visible area of a [`drm_crtc`](#c-struct-drm_crtc). The visible area of a CRTC is
defined by the horizontal and vertical visible pixels (stored in **hdisplay**
and **vdisplay**) of the requested mode (stored in [`drm_crtc_state.mode`](#c-struct-drm_crtc_state)). These
two rectangles are both stored in the [`drm_plane_state`](#c-struct-drm_plane_state).

For the atomic ioctl the following standard (atomic) properties on the plane object
encode the basic plane composition model:

- SRC_X:
  X coordinate offset for the source rectangle within the
  [`drm_framebuffer`](#c-struct-drm_framebuffer), in 16.16 fixed point. Must be positive.
- SRC_Y:
  Y coordinate offset for the source rectangle within the
  [`drm_framebuffer`](#c-struct-drm_framebuffer), in 16.16 fixed point. Must be positive.
- SRC_W:
  Width for the source rectangle within the [`drm_framebuffer`](#c-struct-drm_framebuffer), in 16.16
  fixed point. SRC_X plus SRC_W must be within the width of the source
  framebuffer. Must be positive.
- SRC_H:
  Height for the source rectangle within the [`drm_framebuffer`](#c-struct-drm_framebuffer), in 16.16
  fixed point. SRC_Y plus SRC_H must be within the height of the source
  framebuffer. Must be positive.
- CRTC_X:
  X coordinate offset for the destination rectangle. Can be negative.
- CRTC_Y:
  Y coordinate offset for the destination rectangle. Can be negative.
- CRTC_W:
  Width for the destination rectangle. CRTC_X plus CRTC_W can extend past
  the currently visible horizontal area of the [`drm_crtc`](#c-struct-drm_crtc).
- CRTC_H:
  Height for the destination rectangle. CRTC_Y plus CRTC_H can extend past
  the currently visible vertical area of the [`drm_crtc`](#c-struct-drm_crtc).
- FB_ID:
  Mode object ID of the [`drm_framebuffer`](#c-struct-drm_framebuffer) this plane should scan out.

  When a KMS client is performing front-buffer rendering, it should set
  FB_ID to the same front-buffer FB on each atomic commit. This implies
  to the driver that it needs to re-read the same FB again. Otherwise
  drivers which do not employ continuously repeated scanout cycles might
  not update the screen.
- CRTC_ID:
  Mode object ID of the [`drm_crtc`](#c-struct-drm_crtc) this plane should be connected to.

Note that the source rectangle must fully lie within the bounds of the
[`drm_framebuffer`](#c-struct-drm_framebuffer). The destination rectangle can lie outside of the visible
area of the current mode of the CRTC. It must be appropriately clipped by the
driver, which can be done by calling `drm_plane_helper_check_update()`. Drivers
are also allowed to round the subpixel sampling positions appropriately, but
only to the next full pixel. No pixel outside of the source rectangle may
ever be sampled, which is important when applying more sophisticated
filtering than just a bilinear one when scaling. The filtering mode when
scaling is unspecified.

On top of this basic transformation additional properties can be exposed by
the driver:

- alpha:
  Alpha is setup with [`drm_plane_create_alpha_property()`](#c-drm_plane_create_alpha_property). It controls the
  plane-wide opacity, from transparent (0) to opaque (0xffff). It can be
  combined with pixel alpha.
  The pixel values in the framebuffers are expected to not be
  pre-multiplied by the global alpha associated to the plane.

- rotation:
  Rotation is set up with [`drm_plane_create_rotation_property()`](#c-drm_plane_create_rotation_property). It adds a
  rotation and reflection step between the source and destination rectangles.
  Without this property the rectangle is only scaled, but not rotated or
  reflected.

  Possbile values:

  "rotate-\<degrees>":
  Signals that a drm plane is rotated \<degrees> degrees in counter
  clockwise direction.

  "reflect-\<axis>":
  Signals that the contents of a drm plane is reflected along the
  \<axis> axis, in the same way as mirroring.

  reflect-x:

```text
|o |    | o|
|  | -> |  |
| v|    |v |
```

reflect-y:

```text
|o |    | ^|
|  | -> |  |
| v|    |o |
```

- zpos:
  Z position is set up with [`drm_plane_create_zpos_immutable_property()`](#c-drm_plane_create_zpos_immutable_property) and
  [`drm_plane_create_zpos_property()`](#c-drm_plane_create_zpos_property). It controls the visibility of overlapping
  planes. Without this property the primary plane is always below the cursor
  plane, and ordering between all other planes is undefined. The positive
  Z axis points towards the user, i.e. planes with lower Z position values
  are underneath planes with higher Z position values. Two planes with the
  same Z position value have undefined ordering. Note that the Z position
  value can also be immutable, to inform userspace about the hard-coded
  stacking of planes, see [`drm_plane_create_zpos_immutable_property()`](#c-drm_plane_create_zpos_immutable_property). If
  any plane has a zpos property (either mutable or immutable), then all
  planes shall have a zpos property.

- pixel blend mode:
  Pixel blend mode is set up with [`drm_plane_create_blend_mode_property()`](#c-drm_plane_create_blend_mode_property).
  It adds a blend mode for alpha blending equation selection, describing
  how the pixels from the current plane are composited with the
  background.

  Three alpha blending equations are defined:

  "None":
  Blend formula that ignores the pixel alpha:

```text
out.rgb = plane_alpha * fg.rgb +
        (1 - plane_alpha) * bg.rgb
```

- "Pre-multiplied":
  Blend formula that assumes the pixel color values
  have been already pre-multiplied with the alpha
  channel values:

```text
out.rgb = plane_alpha * fg.rgb +
        (1 - (plane_alpha * fg.alpha)) * bg.rgb
```

- "Coverage":
  Blend formula that assumes the pixel color values have not
  been pre-multiplied and will do so when blending them to the
  background color values:

```text
out.rgb = plane_alpha * fg.alpha * fg.rgb +
        (1 - (plane_alpha * fg.alpha)) * bg.rgb
```

Using the following symbols:

- "fg.rgb":
  Each of the RGB component values from the plane's pixel
      - "fg.alpha":
        Alpha component value from the plane's pixel. If the plane's
        pixel format has no alpha component, then this is assumed to be
        1.0. In these cases, this property has no effect, as all three
        equations become equivalent.
      - "bg.rgb":
        Each of the RGB component values from the background
      - "plane_alpha":
        Plane alpha value set by the plane "alpha" property. If the
        plane does not expose the "alpha" property, then this is
        assumed to be 1.0

Note that all the property extensions described here apply either to the
plane or the CRTC (e.g. for the background color, which currently is not
exposed and assumed to be black).

- SCALING_FILTER:
  Indicates scaling filter to be used for plane scaler

  The value of this property can be one of the following:

  Default:
  Driver's default scaling filter
  Nearest Neighbor:
  Nearest Neighbor scaling filter

Drivers can set up this property for a plane by calling
drm_plane_create_scaling_filter_property


<a id="rst-damage-tracking-properties-1"></a>
<a id="rst-damage-tracking-properties"></a>

### Damage Tracking Properties


FB_DAMAGE_CLIPS is an optional plane property which provides a means to
specify a list of damage rectangles on a plane in framebuffer coordinates of
the framebuffer attached to the plane. In current context damage is the area
of plane framebuffer that has changed since last plane update (also called
page-flip), irrespective of whether currently attached framebuffer is same as
framebuffer attached during last plane update or not.

FB_DAMAGE_CLIPS is a hint to kernel which could be helpful for some drivers
to optimize internally especially for virtual devices where each framebuffer
change needs to be transmitted over network, usb, etc.

Since FB_DAMAGE_CLIPS is a hint so it is an optional property. User-space can
ignore damage clips property and in that case driver will do a full plane
update. In case damage clips are provided then it is guaranteed that the area
inside damage clips will be updated to plane. For efficiency driver can do
full update or can update more than specified in damage clips. Since driver
is free to read more, user-space must always render the entire visible
framebuffer. Otherwise there can be corruptions. Also, if a user-space
provides damage clips which doesn't encompass the actual damage to
framebuffer (since last plane update) can result in incorrect rendering.

FB_DAMAGE_CLIPS is a blob property with the layout of blob data is simply an
array of [`drm_mode_rect`](/kernel/hardware/gpu/drm-uapi.md#c-struct-drm_mode_rect). Unlike plane [`drm_plane_state.src`](#c-struct-drm_plane_state) coordinates,
damage clips are not in 16.16 fixed point. Similar to plane src in
framebuffer, damage clips cannot be negative. In damage clip, x1/y1 are
inclusive and x2/y2 are exclusive. While kernel does not error for overlapped
damage clips, it is strongly discouraged.

Drivers that are interested in damage interface for plane should enable
FB_DAMAGE_CLIPS property by calling [`drm_plane_enable_fb_damage_clips()`](#c-drm_plane_enable_fb_damage_clips).
Drivers implementing damage can use [`drm_atomic_helper_damage_iter_init()`](#c-drm_atomic_helper_damage_iter_init) and
[`drm_atomic_helper_damage_iter_next()`](#c-drm_atomic_helper_damage_iter_next) helper iterator function to get damage
rectangles clipped to [`drm_plane_state.src`](#c-struct-drm_plane_state).

Note that there are two types of damage handling: frame damage and buffer
damage, the type of damage handling implemented depends on a driver's upload
target. Drivers implementing a per-plane or per-CRTC upload target need to
handle frame damage, while drivers implementing a per-buffer upload target
need to handle buffer damage.

The existing damage helpers only support the frame damage type, there is no
buffer age support or similar damage accumulation algorithm implemented yet.

Only drivers handling frame damage can use the mentioned damage helpers to
iterate over the damaged regions. Drivers that handle buffer damage, must set
[`drm_plane_state.ignore_damage_clips`](#c-struct-drm_plane_state) for [`drm_atomic_helper_damage_iter_init()`](#c-drm_atomic_helper_damage_iter_init)
to know that damage clips should be ignored and return [`drm_plane_state.src`](#c-struct-drm_plane_state)
as the damage rectangle, to force a full plane update.

Drivers with a per-buffer upload target could compare the [`drm_plane_state.fb`](#c-struct-drm_plane_state)
of the old and new plane states to determine if the framebuffer attached to a
plane has changed or not since the last plane update. If [`drm_plane_state.fb`](#c-struct-drm_plane_state)
has changed, then [`drm_plane_state.ignore_damage_clips`](#c-struct-drm_plane_state) must be set to true.

That is because drivers with a per-plane upload target, expect the backing
storage buffer to not change for a given plane. If the upload buffer changes
between page flips, the new upload buffer has to be updated as a whole. This
can be improved in the future if support for frame damage is added to the DRM
damage helpers, similarly to how user-space already handle this case as it is
explained in the following documents:

https://registry.khronos.org/EGL/extensions/KHR/EGL_KHR_swap_buffers_with_damage.txt
https://emersion.fr/blog/2019/intro-to-damage-tracking/


<a id="rst-color-management-properties"></a>

### Color Management Properties


Color management or color space adjustments is supported through a set of 5
properties on the [`drm_crtc`](#c-struct-drm_crtc) object. They are set up by calling
[`drm_crtc_enable_color_mgmt()`](#c-drm_crtc_enable_color_mgmt).

- "DEGAMMA_LUT”:
  Blob property to set the degamma lookup table (LUT) mapping pixel data
  from the framebuffer before it is given to the transformation matrix.
  The data is interpreted as an array of `struct drm_color_lut` elements.
  Hardware might choose not to use the full precision of the LUT elements
  nor use all the elements of the LUT (for example the hardware might
  choose to interpolate between LUT\[0\] and LUT\[4\]).

  Setting this to NULL (blob property value set to 0) means a
  linear/pass-thru gamma table should be used. This is generally the
  driver boot-up state too. Drivers can access this blob through
  [`drm_crtc_state.degamma_lut`](#c-struct-drm_crtc_state).

- “DEGAMMA_LUT_SIZE”:
  Unsinged range property to give the size of the lookup table to be set
  on the DEGAMMA_LUT property (the size depends on the underlying
  hardware). If drivers support multiple LUT sizes then they should
  publish the largest size, and sub-sample smaller sized LUTs (e.g. for
  split-gamma modes) appropriately.

- “CTM”:
  Blob property to set the current transformation matrix (CTM) apply to
  pixel data after the lookup through the degamma LUT and before the
  lookup through the gamma LUT. The data is interpreted as a struct
  `drm_color_ctm`.

  Setting this to NULL (blob property value set to 0) means a
  unit/pass-thru matrix should be used. This is generally the driver
  boot-up state too. Drivers can access the blob for the color conversion
  matrix through [`drm_crtc_state.ctm`](#c-struct-drm_crtc_state).

- “GAMMA_LUT”:
  Blob property to set the gamma lookup table (LUT) mapping pixel data
  after the transformation matrix to data sent to the connector. The
  data is interpreted as an array of `struct drm_color_lut` elements.
  Hardware might choose not to use the full precision of the LUT elements
  nor use all the elements of the LUT (for example the hardware might
  choose to interpolate between LUT\[0\] and LUT\[4\]).

  Setting this to NULL (blob property value set to 0) means a
  linear/pass-thru gamma table should be used. This is generally the
  driver boot-up state too. Drivers can access this blob through
  [`drm_crtc_state.gamma_lut`](#c-struct-drm_crtc_state).

  Note that for mostly historical reasons stemming from Xorg heritage,
  this is also used to store the color map (also sometimes color lut, CLUT
  or color palette) for indexed formats like DRM_FORMAT_C8.

- “GAMMA_LUT_SIZE”:
  Unsigned range property to give the size of the lookup table to be set
  on the GAMMA_LUT property (the size depends on the underlying hardware).
  If drivers support multiple LUT sizes then they should publish the
  largest size, and sub-sample smaller sized LUTs (e.g. for split-gamma
  modes) appropriately.

There is also support for a legacy gamma table, which is set up by calling
[`drm_mode_crtc_set_gamma_size()`](#c-drm_mode_crtc_set_gamma_size). The DRM core will then alias the legacy gamma
ramp with "GAMMA_LUT" or, if that is unavailable, "DEGAMMA_LUT".

Support for different non RGB color encodings is controlled through
[`drm_plane`](#c-struct-drm_plane) specific COLOR_ENCODING and COLOR_RANGE properties. They
are set up by calling [`drm_plane_create_color_properties()`](#c-drm_plane_create_color_properties).

- "COLOR_ENCODING":
  Optional plane enum property to support different non RGB
  color encodings. The driver can provide a subset of standard
  enum values supported by the DRM plane.

- "COLOR_RANGE":
  Optional plane enum property to support different non RGB
  color parameter ranges. The driver can provide a subset of
  standard enum values supported by the DRM plane.


<a id="rst-tile-group-property"></a>

### Tile Group Property


Tile groups are used to represent tiled monitors with a unique integer
identifier. Tiled monitors using DisplayID v1.3 have a unique 8-byte handle,
we store this in a tile group, so we have a common identifier for all tiles
in a monitor group. The property is called "TILE". Drivers can manage tile
groups using [`drm_mode_create_tile_group()`](#c-drm_mode_create_tile_group), [`drm_mode_put_tile_group()`](#c-drm_mode_put_tile_group) and
[`drm_mode_get_tile_group()`](#c-drm_mode_get_tile_group). But this is only needed for internal panels where
the tile group information is exposed through a non-standard way.


<a id="rst-explicit-fencing-properties"></a>

### Explicit Fencing Properties


Explicit fencing allows userspace to control the buffer synchronization
between devices. A Fence or a group of fences are transferred to/from
userspace using Sync File fds and there are two DRM properties for that.
IN_FENCE_FD on each DRM Plane to send fences to the kernel and
OUT_FENCE_PTR on each DRM CRTC to receive fences from the kernel.

As a contrast, with implicit fencing the kernel keeps track of any
ongoing rendering, and automatically ensures that the atomic update waits
for any pending rendering to complete. This is usually tracked in [`struct dma_resv`](/kernel/hardware/driver-api/io-and-dma/dma-buf.md#c-struct-dma_resv) which can also contain mandatory kernel fences. Implicit syncing
is how Linux traditionally worked (e.g. DRI2/3 on X.org), whereas explicit
fencing is what Android wants.

- "IN_FENCE_FD”:
  Use this property to pass a fence that DRM should wait on before
  proceeding with the Atomic Commit request and show the framebuffer for
  the plane on the screen. The fence can be either a normal fence or a
  merged one, the sync_file framework will handle both cases and use a
  fence_array if a merged fence is received. Passing -1 here means no
  fences to wait on.

  If the Atomic Commit request has the DRM_MODE_ATOMIC_TEST_ONLY flag
  it will only check if the Sync File is a valid one.

  On the driver side the fence is stored on the **fence** parameter of
  [`struct drm_plane_state`](#c-struct-drm_plane_state). Drivers which also support implicit fencing
  should extract the implicit fence using [`drm_gem_plane_helper_prepare_fb()`](/kernel/hardware/gpu/drm-kms-helpers.md#c-drm_gem_plane_helper_prepare_fb),
  to make sure there's consistent behaviour between drivers in precedence
  of implicit vs. explicit fencing.

- "OUT_FENCE_PTR”:
  Use this property to pass a file descriptor pointer to DRM. Once the
  Atomic Commit request call returns OUT_FENCE_PTR will be filled with
  the file descriptor number of a Sync File. This Sync File contains the
  CRTC fence that will be signaled when all framebuffers present on the
  Atomic Commit * request for that given CRTC are scanned out on the
  screen.

  The Atomic Commit request fails if a invalid pointer is passed. If the
  Atomic Commit request fails for any other reason the out fence fd
  returned will be -1. On a Atomic Commit with the
  DRM_MODE_ATOMIC_TEST_ONLY flag the out fence will also be set to -1.

  Note that out-fences don't have a special interface to drivers and are
  internally represented by a [`struct drm_pending_vblank_event`](#c-struct-drm_pending_vblank_event) in struct
  [`drm_crtc_state`](#c-struct-drm_crtc_state), which is also used by the nonblocking atomic commit
  helpers and for the DRM event handling for existing userspace.


<a id="rst-variable-refresh-properties"></a>

### Variable Refresh Properties


Variable refresh rate capable displays can dynamically adjust their
refresh rate by extending the duration of their vertical front porch
until page flip or timeout occurs. This can reduce or remove stuttering
and latency in scenarios where the page flip does not align with the
vblank interval.

An example scenario would be an application flipping at a constant rate
of 48Hz on a 60Hz display. The page flip will frequently miss the vblank
interval and the same contents will be displayed twice. This can be
observed as stuttering for content with motion.

If variable refresh rate was active on a display that supported a
variable refresh range from 35Hz to 60Hz no stuttering would be observable
for the example scenario. The minimum supported variable refresh rate of
35Hz is below the page flip frequency and the vertical front porch can
be extended until the page flip occurs. The vblank interval will be
directly aligned to the page flip rate.

Not all userspace content is suitable for use with variable refresh rate.
Large and frequent changes in vertical front porch duration may worsen
perceived stuttering for input sensitive applications.

Panel brightness will also vary with vertical front porch duration. Some
panels may have noticeable differences in brightness between the minimum
vertical front porch duration and the maximum vertical front porch duration.
Large and frequent changes in vertical front porch duration may produce
observable flickering for such panels.

Userspace control for variable refresh rate is supported via properties
on the [`drm_connector`](#c-struct-drm_connector) and [`drm_crtc`](#c-struct-drm_crtc) objects.

- "vrr_capable":
  Optional [`drm_connector`](#c-struct-drm_connector) boolean property that drivers should attach
  with [`drm_connector_attach_vrr_capable_property()`](#c-drm_connector_attach_vrr_capable_property) on connectors that
  could support variable refresh rates. Drivers should update the
  property value by calling [`drm_connector_set_vrr_capable_property()`](#c-drm_connector_set_vrr_capable_property).

  Absence of the property should indicate absence of support.

- "VRR_ENABLED":
  Default [`drm_crtc`](#c-struct-drm_crtc) boolean property that notifies the driver that the
  content on the CRTC is suitable for variable refresh rate presentation.
  The driver will take this property as a hint to enable variable
  refresh rate support if the receiver supports it, ie. if the
  "vrr_capable" property is true on the [`drm_connector`](#c-struct-drm_connector) object. The
  vertical front porch duration will be extended until page-flip or
  timeout when enabled.

  The minimum vertical front porch duration is defined as the vertical
  front porch duration for the current mode.

  The maximum vertical front porch duration is greater than or equal to
  the minimum vertical front porch duration. The duration is derived
  from the minimum supported variable refresh rate for the connector.

  The driver may place further restrictions within these minimum
  and maximum bounds.


<a id="rst-cursor-hotspot-properties"></a>

### Cursor Hotspot Properties


HOTSPOT_X: property to set mouse hotspot x offset.
HOTSPOT_Y: property to set mouse hotspot y offset.

When the plane is being used as a cursor image to display a mouse pointer,
the "hotspot" is the offset within the cursor image where mouse events
are expected to go.

Positive values move the hotspot from the top-left corner of the cursor
plane towards the right and bottom.

Most display drivers do not need this information because the
hotspot is not actually connected to anything visible on screen.
However, this is necessary for display drivers like the para-virtualized
drivers (eg qxl, vbox, virtio, vmwgfx), that are attached to a user console
with a mouse pointer.  Since these consoles are often being remoted over a
network, they would otherwise have to wait to display the pointer movement to
the user until a full network round-trip has occurred.  New mouse events have
to be sent from the user's console, over the network to the virtual input
devices, forwarded to the desktop for processing, and then the cursor plane's
position can be updated and sent back to the user's console over the network.
Instead, with the hotspot information, the console can anticipate the new
location, and draw the mouse cursor there before the confirmation comes in.
To do that correctly, the user's console must be able predict how the
desktop will process mouse events, which normally requires the desktop's
mouse topology information, ie where each CRTC sits in the mouse coordinate
space.  This is typically sent to the para-virtualized drivers using some
driver-specific method, and the driver then forwards it to the console by
way of the virtual display device or hypervisor.

The assumption is generally made that there is only one cursor plane being
used this way at a time, and that the desktop is feeding all mouse devices
into the same global pointer.  Para-virtualized drivers that require this
should only be exposing a single cursor plane, or find some other way
to coordinate with a userspace desktop that supports multiple pointers.
If the hotspot properties are set, the cursor plane is therefore assumed to be
used only for displaying a mouse cursor image, and the position of the combined
cursor plane + offset can therefore be used for coordinating with input from a
mouse device.

The cursor will then be drawn either at the location of the plane in the CRTC
console, or as a free-floating cursor plane on the user's console
corresponding to their desktop mouse position.

DRM clients which would like to work correctly on drivers which expose
hotspot properties should advertise DRM_CLIENT_CAP_CURSOR_PLANE_HOTSPOT.
Setting this property on drivers which do not special case
cursor planes will return EOPNOTSUPP, which can be used by userspace to
gauge requirements of the hardware/drivers they're running on. Advertising
DRM_CLIENT_CAP_CURSOR_PLANE_HOTSPOT implies that the userspace client will be
correctly setting the hotspot properties.


<a id="rst-existing-kms-properties"></a>

### Existing KMS Properties

The following table gives description of drm properties exposed by various modules/drivers. Because this table is very unwieldy, do not add any new properties here. Instead document them in a section above.



| Owner Module/Drivers | Group | Property Name | Type | Property Values | Object attached | Description/Restrictions |
|---|---|---|---|---|---|---|
|  | DVI-I | “subconnector” | ENUM | { “Unknown”, “DVI-D”, “DVI-A” } | Connector | TBD |
|  |  | “select subconnector” | ENUM | { “Automatic”, “DVI-D”, “DVI-A” } | Connector | TBD |
|  | TV | “subconnector” | ENUM | { "Unknown", "Composite", "SVIDEO", "Component", "SCART" } | Connector | TBD |
|  |  | “select subconnector” | ENUM | { "Automatic", "Composite", "SVIDEO", "Component", "SCART" } | Connector | TBD |
|  |  | “mode” | ENUM | { "NTSC\_M", "NTSC\_J", "NTSC\_443", "PAL\_B" } etc. | Connector | TBD |
|  |  | “left margin” | RANGE | Min=0, Max=100 | Connector | TBD |
|  |  | “right margin” | RANGE | Min=0, Max=100 | Connector | TBD |
|  |  | “top margin” | RANGE | Min=0, Max=100 | Connector | TBD |
|  |  | “bottom margin” | RANGE | Min=0, Max=100 | Connector | TBD |
|  |  | “brightness” | RANGE | Min=0, Max=100 | Connector | TBD |
|  |  | “contrast” | RANGE | Min=0, Max=100 | Connector | TBD |
|  |  | “flicker reduction” | RANGE | Min=0, Max=100 | Connector | TBD |
|  |  | “overscan” | RANGE | Min=0, Max=100 | Connector | TBD |
|  |  | “saturation” | RANGE | Min=0, Max=100 | Connector | TBD |
|  |  | “hue” | RANGE | Min=0, Max=100 | Connector | TBD |
|  | Virtual GPU | “suggested X” | RANGE | Min=0, Max=0xffffffff | Connector | property to suggest an X offset for a connector |
|  |  | “suggested Y” | RANGE | Min=0, Max=0xffffffff | Connector | property to suggest an Y offset for a connector |
|  | Optional | "aspect ratio" | ENUM | { "None", "4:3", "16:9" } | Connector | TDB |
|  |  | “audio” | ENUM | { "force-dvi", "off", "auto", "on" } | Connector | TBD |
|  | SDVO-TV | “mode” | ENUM | { "NTSC\_M", "NTSC\_J", "NTSC\_443", "PAL\_B" } etc. | Connector | TBD |
|  |  | "left\_margin" | RANGE | Min=0, Max= SDVO dependent | Connector | TBD |
|  |  | "right\_margin" | RANGE | Min=0, Max= SDVO dependent | Connector | TBD |
|  |  | "top\_margin" | RANGE | Min=0, Max= SDVO dependent | Connector | TBD |
|  |  | "bottom\_margin" | RANGE | Min=0, Max= SDVO dependent | Connector | TBD |
|  |  | “hpos” | RANGE | Min=0, Max= SDVO dependent | Connector | TBD |
|  |  | “vpos” | RANGE | Min=0, Max= SDVO dependent | Connector | TBD |
|  |  | “contrast” | RANGE | Min=0, Max= SDVO dependent | Connector | TBD |
|  |  | “saturation” | RANGE | Min=0, Max= SDVO dependent | Connector | TBD |
|  |  | “hue” | RANGE | Min=0, Max= SDVO dependent | Connector | TBD |
|  |  | “sharpness” | RANGE | Min=0, Max= SDVO dependent | Connector | TBD |
|  |  | “flicker\_filter” | RANGE | Min=0, Max= SDVO dependent | Connector | TBD |
|  |  | “flicker\_filter\_adaptive” | RANGE | Min=0, Max= SDVO dependent | Connector | TBD |
|  |  | “flicker\_filter\_2d” | RANGE | Min=0, Max= SDVO dependent | Connector | TBD |
|  |  | “tv\_chroma\_filter” | RANGE | Min=0, Max= SDVO dependent | Connector | TBD |
|  |  | “tv\_luma\_filter” | RANGE | Min=0, Max= SDVO dependent | Connector | TBD |
|  |  | “dot\_crawl” | RANGE | Min=0, Max=1 | Connector | TBD |
|  | SDVO-TV/LVDS | “brightness” | RANGE | Min=0, Max= SDVO dependent | Connector | TBD |
| CDV gma-500 | Generic | "Broadcast RGB" | ENUM | { “Full”, “Limited 16:235” } | Connector | TBD |
| Poulsbo | Generic | “backlight” | RANGE | Min=0, Max=100 | Connector | TBD |
|  | SDVO-TV | “mode” | ENUM | { "NTSC\_M", "NTSC\_J", "NTSC\_443", "PAL\_B" } etc. | Connector | TBD |
|  |  | "left\_margin" | RANGE | Min=0, Max= SDVO dependent | Connector | TBD |
|  |  | "right\_margin" | RANGE | Min=0, Max= SDVO dependent | Connector | TBD |
|  |  | "top\_margin" | RANGE | Min=0, Max= SDVO dependent | Connector | TBD |
|  |  | "bottom\_margin" | RANGE | Min=0, Max= SDVO dependent | Connector | TBD |
|  |  | “hpos” | RANGE | Min=0, Max= SDVO dependent | Connector | TBD |
|  |  | “vpos” | RANGE | Min=0, Max= SDVO dependent | Connector | TBD |
|  |  | “contrast” | RANGE | Min=0, Max= SDVO dependent | Connector | TBD |
|  |  | “saturation” | RANGE | Min=0, Max= SDVO dependent | Connector | TBD |
|  |  | “hue” | RANGE | Min=0, Max= SDVO dependent | Connector | TBD |
|  |  | “sharpness” | RANGE | Min=0, Max= SDVO dependent | Connector | TBD |
|  |  | “flicker\_filter” | RANGE | Min=0, Max= SDVO dependent | Connector | TBD |
|  |  | “flicker\_filter\_adaptive” | RANGE | Min=0, Max= SDVO dependent | Connector | TBD |
|  |  | “flicker\_filter\_2d” | RANGE | Min=0, Max= SDVO dependent | Connector | TBD |
|  |  | “tv\_chroma\_filter” | RANGE | Min=0, Max= SDVO dependent | Connector | TBD |
|  |  | “tv\_luma\_filter” | RANGE | Min=0, Max= SDVO dependent | Connector | TBD |
|  |  | “dot\_crawl” | RANGE | Min=0, Max=1 | Connector | TBD |
|  | SDVO-TV/LVDS | “brightness” | RANGE | Min=0, Max= SDVO dependent | Connector | TBD |
| armada | CRTC | "CSC\_YUV" | ENUM | { "Auto" , "CCIR601", "CCIR709" } | CRTC | TBD |
|  |  | "CSC\_RGB" | ENUM | { "Auto", "Computer system", "Studio" } | CRTC | TBD |
|  | Overlay | "colorkey" | RANGE | Min=0, Max=0xffffff | Plane | TBD |
|  |  | "colorkey\_min" | RANGE | Min=0, Max=0xffffff | Plane | TBD |
|  |  | "colorkey\_max" | RANGE | Min=0, Max=0xffffff | Plane | TBD |
|  |  | "colorkey\_val" | RANGE | Min=0, Max=0xffffff | Plane | TBD |
|  |  | "colorkey\_alpha" | RANGE | Min=0, Max=0xffffff | Plane | TBD |
|  |  | "colorkey\_mode" | ENUM | { "disabled", "Y component", "U component" , "V component", "RGB", “R component", "G component", "B component" } | Plane | TBD |
|  |  | "brightness" | RANGE | Min=0, Max=256 + 255 | Plane | TBD |
|  |  | "contrast" | RANGE | Min=0, Max=0x7fff | Plane | TBD |
|  |  | "saturation" | RANGE | Min=0, Max=0x7fff | Plane | TBD |
| exynos | CRTC | “mode” | ENUM | { "normal", "blank" } | CRTC | TBD |
| i2c/ch7006\_drv | Generic | “scale” | RANGE | Min=0, Max=2 | Connector | TBD |
|  | TV | “mode” | ENUM | { "PAL", "PAL-M","PAL-N"}, ”PAL-Nc" , "PAL-60", "NTSC-M", "NTSC-J" } | Connector | TBD |
| nouveau | NV10 Overlay | "colorkey" | RANGE | Min=0, Max=0x01ffffff | Plane | TBD |
|  |  | “contrast” | RANGE | Min=0, Max=8192-1 | Plane | TBD |
|  |  | “brightness” | RANGE | Min=0, Max=1024 | Plane | TBD |
|  |  | “hue” | RANGE | Min=0, Max=359 | Plane | TBD |
|  |  | “saturation” | RANGE | Min=0, Max=8192-1 | Plane | TBD |
|  |  | “iturbt\_709” | RANGE | Min=0, Max=1 | Plane | TBD |
|  | Nv04 Overlay | “colorkey” | RANGE | Min=0, Max=0x01ffffff | Plane | TBD |
|  |  | “brightness” | RANGE | Min=0, Max=1024 | Plane | TBD |
|  | Display | “dithering mode” | ENUM | { "auto", "off", "on" } | Connector | TBD |
|  |  | “dithering depth” | ENUM | { "auto", "off", "on", "static 2x2", "dynamic 2x2", "temporal" } | Connector | TBD |
|  |  | “underscan” | ENUM | { "auto", "6 bpc", "8 bpc" } | Connector | TBD |
|  |  | “underscan hborder” | RANGE | Min=0, Max=128 | Connector | TBD |
|  |  | “underscan vborder” | RANGE | Min=0, Max=128 | Connector | TBD |
|  |  | “vibrant hue” | RANGE | Min=0, Max=180 | Connector | TBD |
|  |  | “color vibrance” | RANGE | Min=0, Max=200 | Connector | TBD |
| omap | Generic | “zorder” | RANGE | Min=0, Max=3 | CRTC, Plane | TBD |
| qxl | Generic | “hotplug\_mode\_update" | RANGE | Min=0, Max=1 | Connector | TBD |
| radeon | DVI-I | “coherent” | RANGE | Min=0, Max=1 | Connector | TBD |
|  | DAC enable load detect | “load detection” | RANGE | Min=0, Max=1 | Connector | TBD |
|  | TV Standard | "tv standard" | ENUM | { "ntsc", "pal", "pal-m", "pal-60", "ntsc-j" , "scart-pal", "pal-cn", "secam" } | Connector | TBD |
|  | legacy TMDS PLL detect | "tmds\_pll" | ENUM | { "driver", "bios" } | - | TBD |
|  | Underscan | "underscan" | ENUM | { "off", "on", "auto" } | Connector | TBD |
|  |  | "underscan hborder" | RANGE | Min=0, Max=128 | Connector | TBD |
|  |  | "underscan vborder" | RANGE | Min=0, Max=128 | Connector | TBD |
|  | Audio | “audio” | ENUM | { "off", "on", "auto" } | Connector | TBD |
|  | FMT Dithering | “dither” | ENUM | { "off", "on" } | Connector | TBD |
|  |  | "colorkey" | RANGE | Min=0, Max=0x01ffffff | Plane | TBD |


<a id="rst-vertical-blanking"></a>

## Vertical Blanking


From the computer's perspective, every time the monitor displays
a new frame the scanout engine has "scanned out" the display image
from top to bottom, one row of pixels at a time. The current row
of pixels is referred to as the current scanline.

In addition to the display's visible area, there's usually a couple of
extra scanlines which aren't actually displayed on the screen.
These extra scanlines don't contain image data and are occasionally used
for features like audio and infoframes. The region made up of these
scanlines is referred to as the vertical blanking region, or vblank for
short.

For historical reference, the vertical blanking period was designed to
give the electron gun (on CRTs) enough time to move back to the top of
the screen to start scanning out the next frame. Similar for horizontal
blanking periods. They were designed to give the electron gun enough
time to move back to the other side of the screen to start scanning the
next scanline.

```text
physical →   ⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽
top of      |                                        |
display     |                                        |
            |               New frame                |
            |                                        |
            |↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓|
            |~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~| ← Scanline,
            |↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓|   updates the
            |                                        |   frame as it
            |                                        |   travels down
            |                                        |   ("scan out")
            |               Old frame                |
            |                                        |
            |                                        |
            |                                        |
            |                                        |   physical
            |                                        |   bottom of
vertical    |⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽| ← display
blanking    ┆xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx┆
region   →  ┆xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx┆
            ┆xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx┆
start of →   ⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽
new frame
```

"Physical top of display" is the reference point for the high-precision/
corrected timestamp.

On a lot of display hardware, programming needs to take effect during the
vertical blanking period so that settings like gamma, the image buffer
buffer to be scanned out, etc. can safely be changed without showing
any visual artifacts on the screen. In some unforgiving hardware, some of
this programming has to both start and end in the same vblank. To help
with the timing of the hardware programming, an interrupt is usually
available to notify the driver when it can start the updating of registers.
The interrupt is in this context named the vblank interrupt.

The vblank interrupt may be fired at different points depending on the
hardware. Some hardware implementations will fire the interrupt when the
new frame start, other implementations will fire the interrupt at different
points in time.

Vertical blanking plays a major role in graphics rendering. To achieve
tear-free display, users must synchronize page flips and/or rendering to
vertical blanking. The DRM API offers ioctls to perform page flips
synchronized to vertical blanking and wait for vertical blanking.

The DRM core handles most of the vertical blanking management logic, which
involves filtering out spurious interrupts, keeping race-free blanking
counters, coping with counter wrap-around and resets and keeping use counts.
It relies on the driver to generate vertical blanking interrupts and
optionally provide a hardware vertical blanking counter.

Drivers must initialize the vertical blanking handling core with a call to
[`drm_vblank_init()`](#c-drm_vblank_init). Minimally, a driver needs to implement
[`drm_crtc_funcs.enable_vblank`](#c-struct-drm_crtc_funcs) and [`drm_crtc_funcs.disable_vblank`](#c-struct-drm_crtc_funcs) plus call
[`drm_crtc_handle_vblank()`](#c-drm_crtc_handle_vblank) in its vblank interrupt handler for working vblank
support.

Vertical blanking interrupts can be enabled by the DRM core or by drivers
themselves (for instance to handle page flipping operations).  The DRM core
maintains a vertical blanking use count to ensure that the interrupts are not
disabled while a user still needs them. To increment the use count, drivers
call [`drm_crtc_vblank_get()`](#c-drm_crtc_vblank_get) and release the vblank reference again with
[`drm_crtc_vblank_put()`](#c-drm_crtc_vblank_put). In between these two calls vblank interrupts are
guaranteed to be enabled.

On many hardware disabling the vblank interrupt cannot be done in a race-free
manner, see [`drm_vblank_crtc_config.disable_immediate`](#c-struct-drm_vblank_crtc_config) and
[`drm_driver.max_vblank_count`](/kernel/hardware/gpu/drm-internals.md#c-struct-drm_driver). In that case the vblank core only disables the
vblanks after a timer has expired, which can be configured through the
`vblankoffdelay` module parameter.

Drivers for hardware without support for vertical-blanking interrupts can
use DRM vblank timers to send vblank events at the rate of the current
display mode's refresh. While not synchronized to the hardware's
vertical-blanking regions, the timer helps DRM clients and compositors to
adapt their update cycle to the display output. Drivers should set up
vblanking as usual, but call [`drm_crtc_vblank_start_timer()`](#c-drm_crtc_vblank_start_timer) and
[`drm_crtc_vblank_cancel_timer()`](#c-drm_crtc_vblank_cancel_timer) as part of their atomic mode setting.
See also DRM vblank helpers for more information.

Drivers without support for vertical-blanking interrupts nor timers must
not call [`drm_vblank_init()`](#c-drm_vblank_init). For these drivers, atomic helpers will
automatically generate fake vblank events as part of the display update.
This functionality also can be controlled by the driver by enabling and
disabling struct drm_crtc_state.no_vblank.


<a id="rst-vertical-blanking-and-interrupt-handling-functions-reference"></a>

### Vertical Blanking and Interrupt Handling Functions Reference


#### <a id="c-struct-drm_pending_vblank_event"></a>`struct drm_pending_vblank_event`

pending vblank event tracking

**Definition**

```c
struct drm_pending_vblank_event {
    struct drm_pending_event base;
    unsigned int pipe;
    u64 sequence;
    union {
        struct drm_event base;
        struct drm_event_vblank vbl;
        struct drm_event_crtc_sequence seq;
    } event;
};
```

**Members**

- `base`: Base structure for tracking pending DRM events.
- `pipe`: [`drm_crtc_index()`](#c-drm_crtc_index) of the [`drm_crtc`](#c-struct-drm_crtc) this event is for.
- `sequence`: frame event should be triggered at
- `event`: Actual event which will be sent to userspace.
- `event.base`: DRM event base class.
- `event.vbl`: Event payload for vblank events, requested through
  either the MODE_PAGE_FLIP or MODE_ATOMIC IOCTL. Also
  generated by the legacy WAIT_VBLANK IOCTL, but new userspace
  should use MODE_QUEUE_SEQUENCE and `event.seq` instead.
- `event.seq`: Event payload for the MODE_QUEUEU_SEQUENCE IOCTL.

#### <a id="c-struct-drm_vblank_crtc_config"></a>`struct drm_vblank_crtc_config`

vblank configuration for a CRTC

**Definition**

```c
struct drm_vblank_crtc_config {
    int offdelay_ms;
    bool disable_immediate;
};
```

**Members**

- `offdelay_ms`: Vblank off delay in ms, used to determine how long
  [`drm_vblank_crtc.disable_timer`](#c-struct-drm_vblank_crtc) waits before disabling.

  Defaults to the value of drm_vblank_offdelay in [`drm_crtc_vblank_on()`](#c-drm_crtc_vblank_on).
- `disable_immediate`: See [`drm_device.vblank_disable_immediate`](/kernel/hardware/gpu/drm-internals.md#c-struct-drm_device)
  for the exact semantics of immediate vblank disabling.

  Additionally, this tracks the disable immediate value per crtc, just
  in case it needs to differ from the default value for a given device.

  Defaults to the value of [`drm_device.vblank_disable_immediate`](/kernel/hardware/gpu/drm-internals.md#c-struct-drm_device) in
  [`drm_crtc_vblank_on()`](#c-drm_crtc_vblank_on).

#### <a id="c-struct-drm_vblank_crtc_timer"></a>`struct drm_vblank_crtc_timer`

vblank timer for a CRTC

**Definition**

```c
struct drm_vblank_crtc_timer {
    struct hrtimer timer;
    spinlock_t interval_lock;
    ktime_t interval;
    struct drm_crtc *crtc;
};
```

**Members**

- `timer`: The vblank's high-resolution timer
- `interval_lock`: Protects **interval**
- `interval`: Duration between two vblanks
- `crtc`: The timer's CRTC

#### <a id="c-struct-drm_vblank_crtc"></a>`struct drm_vblank_crtc`

vblank tracking for a CRTC

**Definition**

```c
struct drm_vblank_crtc {
    struct drm_device *dev;
    wait_queue_head_t queue;
    struct timer_list disable_timer;
    seqlock_t seqlock;
    atomic64_t count;
    ktime_t time;
    atomic_t refcount;
    u32 last;
    u32 max_vblank_count;
    unsigned int inmodeset;
    unsigned int pipe;
    int framedur_ns;
    int linedur_ns;
    struct drm_display_mode hwmode;
    struct drm_vblank_crtc_config config;
    bool enabled;
    struct kthread_worker *worker;
    struct list_head pending_work;
    wait_queue_head_t work_wait_queue;
    struct drm_vblank_crtc_timer vblank_timer;
};
```

**Members**

- `dev`: Pointer to the [`drm_device`](/kernel/hardware/gpu/drm-internals.md#c-struct-drm_device).
- `queue`: Wait queue for vblank waiters.
- `disable_timer`: Disable timer for the delayed vblank disabling
  hysteresis logic. Vblank disabling is controlled through
  [`drm_vblank_crtc_config.offdelay_ms`](#c-struct-drm_vblank_crtc_config) and the setting of the
  [`drm_device.max_vblank_count`](/kernel/hardware/gpu/drm-internals.md#c-struct-drm_device) value.
- `seqlock`: Protect vblank count and time.
- `count`: Current software vblank counter.

  Note that for a given vblank counter value [`drm_crtc_handle_vblank()`](#c-drm_crtc_handle_vblank)
  and [`drm_crtc_vblank_count()`](#c-drm_crtc_vblank_count) or [`drm_crtc_vblank_count_and_time()`](#c-drm_crtc_vblank_count_and_time)
  provide a barrier: Any writes done before calling
  [`drm_crtc_handle_vblank()`](#c-drm_crtc_handle_vblank) will be visible to callers of the later
  functions, iff the vblank count is the same or a later one.

  IMPORTANT: This guarantee requires barriers, therefor never access
  this field directly. Use [`drm_crtc_vblank_count()`](#c-drm_crtc_vblank_count) instead.
- `time`: Vblank timestamp corresponding to **count**.
- `refcount`: Number of users/waiters of the vblank interrupt. Only when
  this refcount reaches 0 can the hardware interrupt be disabled using
  **disable_timer**.
- `last`: Protected by [`drm_device.vbl_lock`](/kernel/hardware/gpu/drm-internals.md#c-struct-drm_device), used for wraparound handling.
- `max_vblank_count`: Maximum value of the vblank registers for this crtc. This value +1
  will result in a wrap-around of the vblank register. It is used
  by the vblank core to handle wrap-arounds.

  If set to zero the vblank core will try to guess the elapsed vblanks
  between times when the vblank interrupt is disabled through
  high-precision timestamps. That approach is suffering from small
  races and imprecision over longer time periods, hence exposing a
  hardware vblank counter is always recommended.

  This is the runtime configurable per-crtc maximum set through
  [`drm_crtc_set_max_vblank_count()`](#c-drm_crtc_set_max_vblank_count). If this is used the driver
  must leave the device wide [`drm_device.max_vblank_count`](/kernel/hardware/gpu/drm-internals.md#c-struct-drm_device) at zero.

  If non-zero, [`drm_crtc_funcs.get_vblank_counter`](#c-struct-drm_crtc_funcs) must be set.
- `inmodeset`: Tracks whether the vblank is disabled due to a modeset.
  For legacy driver bit 2 additionally tracks whether an additional
  temporary vblank reference has been acquired to paper over the
  hardware counter resetting/jumping. KMS drivers should instead just
  call [`drm_crtc_vblank_off()`](#c-drm_crtc_vblank_off) and [`drm_crtc_vblank_on()`](#c-drm_crtc_vblank_on), which explicitly
  save and restore the vblank count.
- `pipe`: [`drm_crtc_index()`](#c-drm_crtc_index) of the [`drm_crtc`](#c-struct-drm_crtc) corresponding to this
  structure.
- `framedur_ns`: Frame/Field duration in ns, used by
  [`drm_crtc_vblank_helper_get_vblank_timestamp()`](#c-drm_crtc_vblank_helper_get_vblank_timestamp) and computed by
  [`drm_calc_timestamping_constants()`](#c-drm_calc_timestamping_constants).
- `linedur_ns`: Line duration in ns, used by
  [`drm_crtc_vblank_helper_get_vblank_timestamp()`](#c-drm_crtc_vblank_helper_get_vblank_timestamp) and computed by
  [`drm_calc_timestamping_constants()`](#c-drm_calc_timestamping_constants).
- `hwmode`: Cache of the current hardware display mode. Only valid when **enabled**
  is set. This is used by helpers like
  [`drm_crtc_vblank_helper_get_vblank_timestamp()`](#c-drm_crtc_vblank_helper_get_vblank_timestamp). We can't just access
  the hardware mode by e.g. looking at [`drm_crtc_state.adjusted_mode`](#c-struct-drm_crtc_state),
  because that one is really hard to get from interrupt context.
- `config`: Stores vblank configuration values for a given CRTC.
  Also, see [`drm_crtc_vblank_on_config()`](#c-drm_crtc_vblank_on_config).
- `enabled`: Tracks the enabling state of the corresponding [`drm_crtc`](#c-struct-drm_crtc) to
  avoid double-disabling and hence corrupting saved state. Needed by
  drivers not using atomic KMS, since those might go through their CRTC
  disabling functions multiple times.
- `worker`: The `kthread_worker` used for executing vblank works.
- `pending_work`: A list of scheduled [`drm_vblank_work`](#c-struct-drm_vblank_work) items that are
  waiting for a future vblank.
- `work_wait_queue`: The wait queue used for signaling that a
  [`drm_vblank_work`](#c-struct-drm_vblank_work) item has either finished executing, or was
  cancelled.
- `vblank_timer`: Holds the state of the vblank timer

**Description**

This structure tracks the vblank state for one CRTC.

Note that for historical reasons - the vblank handling code is still shared
with legacy/non-kms drivers - this is a free-standing structure not directly
connected to [`struct drm_crtc`](#c-struct-drm_crtc). But all public interface functions are taking
a [`struct drm_crtc`](#c-struct-drm_crtc) to hide this implementation detail.



#### <a id="c-drm_crtc_accurate_vblank_count"></a>`drm_crtc_accurate_vblank_count()`

```c
u64 drm_crtc_accurate_vblank_count(struct drm_crtc *crtc)
```

retrieve the master vblank counter

**Parameters**

- `struct drm_crtc *crtc`: which counter to retrieve

**Description**

This function is similar to [`drm_crtc_vblank_count()`](#c-drm_crtc_vblank_count) but this function
interpolates to handle a race with vblank interrupts using the high precision
timestamping support.

This is mostly useful for hardware that can obtain the scanout position, but
doesn't have a hardware frame counter.

#### <a id="c-drm_vblank_init"></a>`drm_vblank_init()`

```c
int drm_vblank_init(struct drm_device *dev, unsigned int num_crtcs)
```

initialize vblank support

**Parameters**

- `struct drm_device *dev`: DRM device
- `unsigned int num_crtcs`: number of CRTCs supported by **dev**

**Description**

This function initializes vblank support for **num_crtcs** display pipelines.
Cleanup is handled automatically through a cleanup function added with
[`drmm_add_action_or_reset()`](/kernel/hardware/gpu/drm-internals.md#c-drmm_add_action_or_reset).

**Return**

Zero on success or a negative error code on failure.

#### <a id="c-drm_dev_has_vblank"></a>`drm_dev_has_vblank()`

```c
bool drm_dev_has_vblank(const struct drm_device *dev)
```

test if vblanking has been initialized for a device

**Parameters**

- `const struct drm_device *dev`: the device

**Description**

Drivers may call this function to test if vblank support is
initialized for a device. For most hardware this means that vblanking
can also be enabled.

Atomic helpers use this function to initialize
[`drm_crtc_state.no_vblank`](#c-struct-drm_crtc_state). See also [`drm_atomic_helper_check_modeset()`](/kernel/hardware/gpu/drm-kms-helpers.md#c-drm_atomic_helper_check_modeset).

**Return**

True if vblanking has been initialized for the given device, false
otherwise.

#### <a id="c-drm_crtc_vblank_waitqueue"></a>`drm_crtc_vblank_waitqueue()`

```c
wait_queue_head_t * drm_crtc_vblank_waitqueue(struct drm_crtc *crtc)
```

get vblank waitqueue for the CRTC

**Parameters**

- `struct drm_crtc *crtc`: which CRTC's vblank waitqueue to retrieve

**Description**

This function returns a pointer to the vblank waitqueue for the CRTC.
Drivers can use this to implement vblank waits using [`wait_event()`](/kernel/hardware/driver-api/fundamentals/basics.md#c-wait_event) and related
functions.

#### <a id="c-drm_calc_timestamping_constants"></a>`drm_calc_timestamping_constants()`

```c
void drm_calc_timestamping_constants(struct drm_crtc *crtc, const struct drm_display_mode *mode)
```

calculate vblank timestamp constants

**Parameters**

- `struct drm_crtc *crtc`: drm_crtc whose timestamp constants should be updated.
- `const struct drm_display_mode *mode`: display mode containing the scanout timings

**Description**

Calculate and store various constants which are later needed by vblank and
swap-completion timestamping, e.g, by
[`drm_crtc_vblank_helper_get_vblank_timestamp()`](#c-drm_crtc_vblank_helper_get_vblank_timestamp). They are derived from
CRTC's true scanout timing, so they take things like panel scaling or
other adjustments into account.

#### <a id="c-drm_crtc_vblank_helper_get_vblank_timestamp_internal"></a>`drm_crtc_vblank_helper_get_vblank_timestamp_internal()`

```c
bool drm_crtc_vblank_helper_get_vblank_timestamp_internal(struct drm_crtc *crtc, int *max_error, ktime_t *vblank_time, bool in_vblank_irq, drm_vblank_get_scanout_position_func get_scanout_position)
```

precise vblank timestamp helper

**Parameters**

- `struct drm_crtc *crtc`: CRTC whose vblank timestamp to retrieve
- `int *max_error`: Desired maximum allowable error in timestamps (nanosecs)
  On return contains true maximum error of timestamp
- `ktime_t *vblank_time`: Pointer to time which should receive the timestamp
- `bool in_vblank_irq`: True when called from [`drm_crtc_handle_vblank()`](#c-drm_crtc_handle_vblank).  Some drivers
  need to apply some workarounds for gpu-specific vblank irq quirks
  if flag is set.
- `drm_vblank_get_scanout_position_func get_scanout_position`: Callback function to retrieve the scanout position. See
  **struct** drm_crtc_helper_funcs.get_scanout_position.

**Description**

Implements calculation of exact vblank timestamps from given drm_display_mode
timings and current video scanout position of a CRTC.

The current implementation only handles standard video modes. For double scan
and interlaced modes the driver is supposed to adjust the hardware mode
(taken from [`drm_crtc_state.adjusted`](#c-struct-drm_crtc_state) mode for atomic modeset drivers) to
match the scanout position reported.

Note that atomic drivers must call [`drm_calc_timestamping_constants()`](#c-drm_calc_timestamping_constants) before
enabling a CRTC. The atomic helpers already take care of that in
[`drm_atomic_helper_calc_timestamping_constants()`](/kernel/hardware/gpu/drm-kms-helpers.md#c-drm_atomic_helper_calc_timestamping_constants).

**Return**

Returns true on success, and false on failure, i.e. when no accurate
timestamp could be acquired.

#### <a id="c-drm_crtc_vblank_helper_get_vblank_timestamp"></a>`drm_crtc_vblank_helper_get_vblank_timestamp()`

```c
bool drm_crtc_vblank_helper_get_vblank_timestamp(struct drm_crtc *crtc, int *max_error, ktime_t *vblank_time, bool in_vblank_irq)
```

precise vblank timestamp helper

**Parameters**

- `struct drm_crtc *crtc`: CRTC whose vblank timestamp to retrieve
- `int *max_error`: Desired maximum allowable error in timestamps (nanosecs)
  On return contains true maximum error of timestamp
- `ktime_t *vblank_time`: Pointer to time which should receive the timestamp
- `bool in_vblank_irq`: True when called from [`drm_crtc_handle_vblank()`](#c-drm_crtc_handle_vblank).  Some drivers
  need to apply some workarounds for gpu-specific vblank irq quirks
  if flag is set.

**Description**

Implements calculation of exact vblank timestamps from given drm_display_mode
timings and current video scanout position of a CRTC. This can be directly
used as the [`drm_crtc_funcs.get_vblank_timestamp`](#c-struct-drm_crtc_funcs) implementation of a kms
driver if [`drm_crtc_helper_funcs.get_scanout_position`](/kernel/hardware/gpu/drm-kms-helpers.md#c-struct-drm_crtc_helper_funcs) is implemented.

The current implementation only handles standard video modes. For double scan
and interlaced modes the driver is supposed to adjust the hardware mode
(taken from [`drm_crtc_state.adjusted`](#c-struct-drm_crtc_state) mode for atomic modeset drivers) to
match the scanout position reported.

Note that atomic drivers must call [`drm_calc_timestamping_constants()`](#c-drm_calc_timestamping_constants) before
enabling a CRTC. The atomic helpers already take care of that in
[`drm_atomic_helper_calc_timestamping_constants()`](/kernel/hardware/gpu/drm-kms-helpers.md#c-drm_atomic_helper_calc_timestamping_constants).

**Return**

Returns true on success, and false on failure, i.e. when no accurate
timestamp could be acquired.

#### <a id="c-drm_crtc_vblank_count"></a>`drm_crtc_vblank_count()`

```c
u64 drm_crtc_vblank_count(struct drm_crtc *crtc)
```

retrieve "cooked" vblank counter value

**Parameters**

- `struct drm_crtc *crtc`: which counter to retrieve

**Description**

Fetches the "cooked" vblank count value that represents the number of
vblank events since the system was booted, including lost events due to
modesetting activity. Note that this timer isn't correct against a racing
vblank interrupt (since it only reports the software vblank counter), see
[`drm_crtc_accurate_vblank_count()`](#c-drm_crtc_accurate_vblank_count) for such use-cases.

Note that for a given vblank counter value [`drm_crtc_handle_vblank()`](#c-drm_crtc_handle_vblank)
and [`drm_crtc_vblank_count()`](#c-drm_crtc_vblank_count) or [`drm_crtc_vblank_count_and_time()`](#c-drm_crtc_vblank_count_and_time)
provide a barrier: Any writes done before calling
[`drm_crtc_handle_vblank()`](#c-drm_crtc_handle_vblank) will be visible to callers of the later
functions, if the vblank count is the same or a later one.

See also [`drm_vblank_crtc.count`](#c-struct-drm_vblank_crtc).

**Return**

The software vblank counter.

#### <a id="c-drm_crtc_vblank_count_and_time"></a>`drm_crtc_vblank_count_and_time()`

```c
u64 drm_crtc_vblank_count_and_time(struct drm_crtc *crtc, ktime_t *vblanktime)
```

retrieve "cooked" vblank counter value and the system timestamp corresponding to that vblank counter value

**Parameters**

- `struct drm_crtc *crtc`: which counter to retrieve
- `ktime_t *vblanktime`: Pointer to time to receive the vblank timestamp.

**Description**

Fetches the "cooked" vblank count value that represents the number of
vblank events since the system was booted, including lost events due to
modesetting activity. Returns corresponding system timestamp of the time
of the vblank interval that corresponds to the current vblank counter value.

Note that for a given vblank counter value [`drm_crtc_handle_vblank()`](#c-drm_crtc_handle_vblank)
and [`drm_crtc_vblank_count()`](#c-drm_crtc_vblank_count) or [`drm_crtc_vblank_count_and_time()`](#c-drm_crtc_vblank_count_and_time)
provide a barrier: Any writes done before calling
[`drm_crtc_handle_vblank()`](#c-drm_crtc_handle_vblank) will be visible to callers of the later
functions, if the vblank count is the same or a later one.

See also [`drm_vblank_crtc.count`](#c-struct-drm_vblank_crtc).

#### <a id="c-drm_crtc_next_vblank_start"></a>`drm_crtc_next_vblank_start()`

```c
int drm_crtc_next_vblank_start(struct drm_crtc *crtc, ktime_t *vblanktime)
```

calculate the time of the next vblank

**Parameters**

- `struct drm_crtc *crtc`: the crtc for which to calculate next vblank time
- `ktime_t *vblanktime`: pointer to time to receive the next vblank timestamp.

**Description**

Calculate the expected time of the start of the next vblank period,
based on time of previous vblank and frame duration

#### <a id="c-drm_crtc_arm_vblank_event"></a>`drm_crtc_arm_vblank_event()`

```c
void drm_crtc_arm_vblank_event(struct drm_crtc *crtc, struct drm_pending_vblank_event *e)
```

arm vblank event after pageflip

**Parameters**

- `struct drm_crtc *crtc`: the source CRTC of the vblank event
- `struct drm_pending_vblank_event *e`: the event to send

**Description**

A lot of drivers need to generate vblank events for the very next vblank
interrupt. For example when the page flip interrupt happens when the page
flip gets armed, but not when it actually executes within the next vblank
period. This helper function implements exactly the required vblank arming
behaviour.

**NOTE**

Drivers using this to send out the [`drm_crtc_state.event`](#c-struct-drm_crtc_state) as part of an
atomic commit must ensure that the next vblank happens at exactly the same
time as the atomic commit is committed to the hardware. This function itself
does **not** protect against the next vblank interrupt racing with either this
function call or the atomic commit operation. A possible sequence could be:

1. Driver commits new hardware state into vblank-synchronized registers.
2. A vblank happens, committing the hardware state. Also the corresponding
   vblank interrupt is fired off and fully processed by the interrupt
   handler.
3. The atomic commit operation proceeds to call [`drm_crtc_arm_vblank_event()`](#c-drm_crtc_arm_vblank_event).
4. The event is only send out for the next vblank, which is wrong.

An equivalent race can happen when the driver calls
[`drm_crtc_arm_vblank_event()`](#c-drm_crtc_arm_vblank_event) before writing out the new hardware state.

The only way to make this work safely is to prevent the vblank from firing
(and the hardware from committing anything else) until the entire atomic
commit sequence has run to completion. If the hardware does not have such a
feature (e.g. using a "go" bit), then it is unsafe to use this functions.
Instead drivers need to manually send out the event from their interrupt
handler by calling [`drm_crtc_send_vblank_event()`](#c-drm_crtc_send_vblank_event) and make sure that there's no
possible race with the hardware committing the atomic update.

Caller must hold a vblank reference for the event **e** acquired by a
[`drm_crtc_vblank_get()`](#c-drm_crtc_vblank_get), which will be dropped when the next vblank arrives.

#### <a id="c-drm_crtc_send_vblank_event"></a>`drm_crtc_send_vblank_event()`

```c
void drm_crtc_send_vblank_event(struct drm_crtc *crtc, struct drm_pending_vblank_event *e)
```

helper to send vblank event after pageflip

**Parameters**

- `struct drm_crtc *crtc`: the source CRTC of the vblank event
- `struct drm_pending_vblank_event *e`: the event to send

**Description**

Updates sequence # and timestamp on event for the most recently processed
vblank, and sends it to userspace.  Caller must hold event lock.

See [`drm_crtc_arm_vblank_event()`](#c-drm_crtc_arm_vblank_event) for a helper which can be used in certain
situation, especially to send out events for atomic commit operations.

#### <a id="c-drm_crtc_vblank_get"></a>`drm_crtc_vblank_get()`

```c
int drm_crtc_vblank_get(struct drm_crtc *crtc)
```

get a reference count on vblank events

**Parameters**

- `struct drm_crtc *crtc`: which CRTC to own

**Description**

Acquire a reference count on vblank events to avoid having them disabled
while in use.

**Return**

Zero on success or a negative error code on failure.

#### <a id="c-drm_crtc_vblank_put"></a>`drm_crtc_vblank_put()`

```c
void drm_crtc_vblank_put(struct drm_crtc *crtc)
```

give up ownership of vblank events

**Parameters**

- `struct drm_crtc *crtc`: which counter to give up

**Description**

Release ownership of a given vblank counter, turning off interrupts
if possible. Disable interrupts after [`drm_vblank_crtc_config.offdelay_ms`](#c-struct-drm_vblank_crtc_config)
milliseconds.

#### <a id="c-drm_crtc_wait_one_vblank"></a>`drm_crtc_wait_one_vblank()`

```c
int drm_crtc_wait_one_vblank(struct drm_crtc *crtc)
```

wait for one vblank

**Parameters**

- `struct drm_crtc *crtc`: DRM crtc

**Description**

This waits for one vblank to pass on **crtc**, using the irq driver interfaces.
It is a failure to call this when the vblank irq for **crtc** is disabled, e.g.
due to lack of driver support or because the crtc is off.

**Return**

0 on success, negative error on failures.

#### <a id="c-drm_crtc_vblank_off"></a>`drm_crtc_vblank_off()`

```c
void drm_crtc_vblank_off(struct drm_crtc *crtc)
```

disable vblank events on a CRTC

**Parameters**

- `struct drm_crtc *crtc`: CRTC in question

**Description**

Drivers can use this function to shut down the vblank interrupt handling when
disabling a crtc. This function ensures that the latest vblank frame count is
stored so that drm_vblank_on can restore it again.

Drivers must use this function when the hardware vblank counter can get
reset, e.g. when suspending or disabling the **crtc** in general.

#### <a id="c-drm_crtc_vblank_reset"></a>`drm_crtc_vblank_reset()`

```c
void drm_crtc_vblank_reset(struct drm_crtc *crtc)
```

reset vblank state to off on a CRTC

**Parameters**

- `struct drm_crtc *crtc`: CRTC in question

**Description**

Drivers can use this function to reset the vblank state to off at load time.
Drivers should use this together with the [`drm_crtc_vblank_off()`](#c-drm_crtc_vblank_off) and
[`drm_crtc_vblank_on()`](#c-drm_crtc_vblank_on) functions. The difference compared to
[`drm_crtc_vblank_off()`](#c-drm_crtc_vblank_off) is that this function doesn't save the vblank counter
and hence doesn't need to call any driver hooks.

This is useful for recovering driver state e.g. on driver load, or on resume.

#### <a id="c-drm_crtc_set_max_vblank_count"></a>`drm_crtc_set_max_vblank_count()`

```c
void drm_crtc_set_max_vblank_count(struct drm_crtc *crtc, u32 max_vblank_count)
```

configure the hw max vblank counter value

**Parameters**

- `struct drm_crtc *crtc`: CRTC in question
- `u32 max_vblank_count`: max hardware vblank counter value

**Description**

Update the maximum hardware vblank counter value for **crtc**
at runtime. Useful for hardware where the operation of the
hardware vblank counter depends on the currently active
display configuration.

For example, if the hardware vblank counter does not work
when a specific connector is active the maximum can be set
to zero. And when that specific connector isn't active the
maximum can again be set to the appropriate non-zero value.

If used, must be called before `drm_vblank_on()`.

#### <a id="c-drm_crtc_vblank_on_config"></a>`drm_crtc_vblank_on_config()`

```c
void drm_crtc_vblank_on_config(struct drm_crtc *crtc, const struct drm_vblank_crtc_config *config)
```

enable vblank events on a CRTC with custom configuration options

**Parameters**

- `struct drm_crtc *crtc`: CRTC in question
- `const struct drm_vblank_crtc_config *config`: Vblank configuration value

**Description**

See [`drm_crtc_vblank_on()`](#c-drm_crtc_vblank_on). In addition, this function allows you to provide a
custom vblank configuration for a given CRTC.

Note that **config** is copied, the pointer does not need to stay valid beyond
this function call. For details of the parameters see
struct drm_vblank_crtc_config.

#### <a id="c-drm_crtc_vblank_on"></a>`drm_crtc_vblank_on()`

```c
void drm_crtc_vblank_on(struct drm_crtc *crtc)
```

enable vblank events on a CRTC

**Parameters**

- `struct drm_crtc *crtc`: CRTC in question

**Description**

This functions restores the vblank interrupt state captured with
[`drm_crtc_vblank_off()`](#c-drm_crtc_vblank_off) again and is generally called when enabling **crtc**. Note
that calls to [`drm_crtc_vblank_on()`](#c-drm_crtc_vblank_on) and [`drm_crtc_vblank_off()`](#c-drm_crtc_vblank_off) can be
unbalanced and so can also be unconditionally called in driver load code to
reflect the current hardware state of the crtc.

Note that unlike in [`drm_crtc_vblank_on_config()`](#c-drm_crtc_vblank_on_config), default values are used.

#### <a id="c-drm_crtc_vblank_restore"></a>`drm_crtc_vblank_restore()`

```c
void drm_crtc_vblank_restore(struct drm_crtc *crtc)
```

estimate missed vblanks and update vblank count.

**Parameters**

- `struct drm_crtc *crtc`: CRTC in question

**Description**

Power manamement features can cause frame counter resets between vblank
disable and enable. Drivers can use this function in their
[`drm_crtc_funcs.enable_vblank`](#c-struct-drm_crtc_funcs) implementation to estimate missed vblanks since
the last [`drm_crtc_funcs.disable_vblank`](#c-struct-drm_crtc_funcs) using timestamps and update the
vblank counter.

Note that drivers must have race-free high-precision timestamping support,
i.e.  [`drm_crtc_funcs.get_vblank_timestamp`](#c-struct-drm_crtc_funcs) must be hooked up and
[`drm_vblank_crtc_config.disable_immediate`](#c-struct-drm_vblank_crtc_config) must be set to indicate the
time-stamping functions are race-free against vblank hardware counter
increments.

#### <a id="c-drm_handle_vblank"></a>`drm_handle_vblank()`

```c
bool drm_handle_vblank(struct drm_device *dev, unsigned int pipe)
```

handle a vblank event

**Parameters**

- `struct drm_device *dev`: DRM device
- `unsigned int pipe`: index of CRTC where this event occurred

**Description**

Drivers should call this routine in their vblank interrupt handlers to
update the vblank counter and send any signals that may be pending.

This is the legacy version of [`drm_crtc_handle_vblank()`](#c-drm_crtc_handle_vblank).

#### <a id="c-drm_crtc_handle_vblank"></a>`drm_crtc_handle_vblank()`

```c
bool drm_crtc_handle_vblank(struct drm_crtc *crtc)
```

handle a vblank event

**Parameters**

- `struct drm_crtc *crtc`: where this event occurred

**Description**

Drivers should call this routine in their vblank interrupt handlers to
update the vblank counter and send any signals that may be pending.

This is the native KMS version of [`drm_handle_vblank()`](#c-drm_handle_vblank).

Note that for a given vblank counter value [`drm_crtc_handle_vblank()`](#c-drm_crtc_handle_vblank)
and [`drm_crtc_vblank_count()`](#c-drm_crtc_vblank_count) or [`drm_crtc_vblank_count_and_time()`](#c-drm_crtc_vblank_count_and_time)
provide a barrier: Any writes done before calling
[`drm_crtc_handle_vblank()`](#c-drm_crtc_handle_vblank) will be visible to callers of the later
functions, if the vblank count is the same or a later one.

See also [`drm_vblank_crtc.count`](#c-struct-drm_vblank_crtc).

**Return**

True if the event was successfully handled, false on failure.

#### <a id="c-drm_crtc_vblank_start_timer"></a>`drm_crtc_vblank_start_timer()`

```c
int drm_crtc_vblank_start_timer(struct drm_crtc *crtc)
```

Starts the vblank timer on the given CRTC

**Parameters**

- `struct drm_crtc *crtc`: the CRTC

**Description**

Drivers should call this function from their CRTC's enable_vblank
function to start a vblank timer. The timer will fire after the duration
of a full frame. [`drm_crtc_vblank_cancel_timer()`](#c-drm_crtc_vblank_cancel_timer) disables a running timer.

**Return**

0 on success, or a negative errno code otherwise.

#### <a id="c-drm_crtc_vblank_cancel_timer"></a>`drm_crtc_vblank_cancel_timer()`

```c
void drm_crtc_vblank_cancel_timer(struct drm_crtc *crtc)
```

Cancels the given CRTC's vblank timer

**Parameters**

- `struct drm_crtc *crtc`: the CRTC

**Description**

Drivers should call this function from their CRTC's disable_vblank
function to stop a vblank timer.

#### <a id="c-drm_crtc_vblank_get_vblank_timeout"></a>`drm_crtc_vblank_get_vblank_timeout()`

```c
void drm_crtc_vblank_get_vblank_timeout(struct drm_crtc *crtc, ktime_t *vblank_time)
```

Returns the vblank timeout

**Parameters**

- `struct drm_crtc *crtc`: The CRTC
- `ktime_t *vblank_time`: Returns the next vblank timestamp

**Description**

The helper [`drm_crtc_vblank_get_vblank_timeout()`](#c-drm_crtc_vblank_get_vblank_timeout) returns the next vblank
timestamp of the CRTC's vblank timer according to the timer's expiry
time.


<a id="rst-vertical-blank-work"></a>

## Vertical Blank Work


Many DRM drivers need to program hardware in a time-sensitive manner, many
times with a deadline of starting and finishing within a certain region of
the scanout. Most of the time the safest way to accomplish this is to
simply do said time-sensitive programming in the driver's IRQ handler,
which allows drivers to avoid being preempted during these critical
regions. Or even better, the hardware may even handle applying such
time-critical programming independently of the CPU.

While there's a decent amount of hardware that's designed so that the CPU
doesn't need to be concerned with extremely time-sensitive programming,
there's a few situations where it can't be helped. Some unforgiving
hardware may require that certain time-sensitive programming be handled
completely by the CPU, and said programming may even take too long to
handle in an IRQ handler. Another such situation would be where the driver
needs to perform a task that needs to complete within a specific scanout
period, but might possibly block and thus cannot be handled in an IRQ
context. Both of these situations can't be solved perfectly in Linux since
we're not a realtime kernel, and thus the scheduler may cause us to miss
our deadline if it decides to preempt us. But for some drivers, it's good
enough if we can lower our chance of being preempted to an absolute
minimum.

This is where [`drm_vblank_work`](#c-struct-drm_vblank_work) comes in. [`drm_vblank_work`](#c-struct-drm_vblank_work) provides a simple
generic delayed work implementation which delays work execution until a
particular vblank has passed, and then executes the work at realtime
priority. This provides the best possible chance at performing
time-sensitive hardware programming on time, even when the system is under
heavy load. [`drm_vblank_work`](#c-struct-drm_vblank_work) also supports rescheduling, so that self
re-arming work items can be easily implemented.


<a id="rst-vertical-blank-work-functions-reference"></a>

### Vertical Blank Work Functions Reference


#### <a id="c-struct-drm_vblank_work"></a>`struct drm_vblank_work`

A delayed work item which delays until a target vblank passes, and then executes at realtime priority outside of IRQ context.

**Definition**

```c
struct drm_vblank_work {
    struct kthread_work base;
    struct drm_vblank_crtc *vblank;
    u64 count;
    int cancelling;
    struct list_head node;
};
```

**Members**

- `base`: The base `kthread_work` item which will be executed by
  [`drm_vblank_crtc.worker`](#c-struct-drm_vblank_crtc). Drivers should not interact with this
  directly, and instead rely on [`drm_vblank_work_init()`](#c-drm_vblank_work_init) to initialize
  this.
- `vblank`: A pointer to [`drm_vblank_crtc`](#c-struct-drm_vblank_crtc) this work item belongs to.
- `count`: The target vblank this work will execute on. Drivers should
  not modify this value directly, and instead use
  [`drm_vblank_work_schedule()`](#c-drm_vblank_work_schedule)
- `cancelling`: The number of [`drm_vblank_work_cancel_sync()`](#c-drm_vblank_work_cancel_sync) calls that
  are currently running. A work item cannot be rescheduled until all
  calls have finished.
- `node`: The position of this work item in
  [`drm_vblank_crtc.pending_work`](#c-struct-drm_vblank_crtc).

**Description**

See also:
[`drm_vblank_work_schedule()`](#c-drm_vblank_work_schedule)
[`drm_vblank_work_init()`](#c-drm_vblank_work_init)
[`drm_vblank_work_cancel_sync()`](#c-drm_vblank_work_cancel_sync)
[`drm_vblank_work_flush()`](#c-drm_vblank_work_flush)
[`drm_vblank_work_flush_all()`](#c-drm_vblank_work_flush_all)

#### <a id="c-to_drm_vblank_work"></a>`to_drm_vblank_work()`

```c
to_drm_vblank_work(_work)
```

Retrieve the respective [`drm_vblank_work`](#c-struct-drm_vblank_work) item from a `kthread_work`

**Parameters**

- `_work`: The `kthread_work` embedded inside a [`drm_vblank_work`](#c-struct-drm_vblank_work)



#### <a id="c-drm_vblank_work_schedule"></a>`drm_vblank_work_schedule()`

```c
int drm_vblank_work_schedule(struct drm_vblank_work *work, u64 count, bool nextonmiss)
```

schedule a vblank work

**Parameters**

- `struct drm_vblank_work *work`: vblank work to schedule
- `u64 count`: target vblank count
- `bool nextonmiss`: defer until the next vblank if target vblank was missed

**Description**

Schedule **work** for execution once the crtc vblank count reaches **count**.

If the crtc vblank count has already reached **count** and **nextonmiss** is
`false` the work starts to execute immediately.

If the crtc vblank count has already reached **count** and **nextonmiss** is
`true` the work is deferred until the next vblank (as if **count** has been
specified as crtc vblank count + 1).

If **work** is already scheduled, this function will reschedule said work
using the new **count**. This can be used for self-rearming work items.

**Return**

`1` if **work** was successfully (re)scheduled, `0` if it was either already
scheduled or cancelled, or a negative error code on failure.

#### <a id="c-drm_vblank_work_cancel_sync"></a>`drm_vblank_work_cancel_sync()`

```c
bool drm_vblank_work_cancel_sync(struct drm_vblank_work *work)
```

cancel a vblank work and wait for it to finish executing

**Parameters**

- `struct drm_vblank_work *work`: vblank work to cancel

**Description**

Cancel an already scheduled vblank work and wait for its
execution to finish.

On return, **work** is guaranteed to no longer be scheduled or running, even
if it's self-arming.

**Return**

`True` if the work was cancelled before it started to execute, `false`
otherwise.

#### <a id="c-drm_vblank_work_flush"></a>`drm_vblank_work_flush()`

```c
void drm_vblank_work_flush(struct drm_vblank_work *work)
```

wait for a scheduled vblank work to finish executing

**Parameters**

- `struct drm_vblank_work *work`: vblank work to flush

**Description**

Wait until **work** has finished executing once.

#### <a id="c-drm_vblank_work_flush_all"></a>`drm_vblank_work_flush_all()`

```c
void drm_vblank_work_flush_all(struct drm_crtc *crtc)
```

flush all currently pending vblank work on crtc.

**Parameters**

- `struct drm_crtc *crtc`: crtc for which vblank work to flush

**Description**

Wait until all currently queued vblank work on **crtc**
has finished executing once.

#### <a id="c-drm_vblank_work_init"></a>`drm_vblank_work_init()`

```c
void drm_vblank_work_init(struct drm_vblank_work *work, struct drm_crtc *crtc, void (*func)(struct kthread_work *work))
```

initialize a vblank work item

**Parameters**

- `struct drm_vblank_work *work`: vblank work item
- `struct drm_crtc *crtc`: CRTC whose vblank will trigger the work execution
- `void (*func)(struct kthread_work *work)`: work function to be executed

**Description**

Initialize a vblank work item for a specific crtc.

---

# DRM Memory Management

_Peios Kernel / Hardware and drivers / Graphics_

> Modern Linux systems require large amount of graphics memory to store frame buffers, textures, vertices and other graphics-related data. Given the very dynamic nature of many of that data, managing graphics memory efficiently is thus…

<a id="rst-drm-memory-management"></a>

Modern Linux systems require large amount of graphics memory to store frame buffers, textures, vertices and other graphics-related data. Given the very dynamic nature of many of that data, managing graphics memory efficiently is thus crucial for the graphics stack and plays a central role in the DRM infrastructure.

The DRM core includes two memory managers, namely Translation Table Manager (TTM) and Graphics Execution Manager (GEM). TTM was the first DRM memory manager to be developed and tried to be a one-size-fits-them all solution. It provides a single userspace API to accommodate the need of all hardware, supporting both Unified Memory Architecture (UMA) devices and devices with dedicated video RAM (i.e. most discrete video cards). This resulted in a large, complex piece of code that turned out to be hard to use for driver development.

GEM started as an Intel-sponsored project in reaction to TTM's complexity. Its design philosophy is completely different: instead of providing a solution to every graphics memory-related problems, GEM identified common code between drivers and created a support library to share it. GEM has simpler initialization and execution requirements than TTM, but has no video RAM management capabilities and is thus limited to UMA devices.

<a id="rst-the-translation-table-manager-ttm"></a>

## The Translation Table Manager (TTM)


TTM is a memory manager for accelerator devices with dedicated memory.

The basic idea is that resources are grouped together in buffer objects of
certain size and TTM handles lifetime, movement and CPU mappings of those
objects.

TODO: Add more design background and information here.



#### <a id="c-enum-ttm_caching"></a>`enum ttm_caching`

CPU caching and BUS snooping behavior.

**Constants**

- `ttm_uncached`: Most defensive option for device mappings,
  don't even allow write combining.
- `ttm_write_combined`: Don't cache read accesses, but allow at least
  writes to be combined.
- `ttm_cached`: Fully cached like normal system memory, requires that
  devices snoop the CPU cache on accesses.


<a id="rst-ttm-device-object-reference"></a>

### TTM device object reference


#### <a id="c-struct-ttm_global"></a>`struct ttm_global`

Buffer object driver global data.

**Definition**

```c
struct ttm_global {
    struct page *dummy_read_page;
    struct list_head device_list;
    atomic_t bo_count;
};
```

**Members**

- `dummy_read_page`: Pointer to a dummy page used for mapping requests
  of unpopulated pages. Constant after init.
- `device_list`: List of buffer object devices. Protected by
  ttm_global_mutex.
- `bo_count`: Number of buffer objects allocated by devices.

#### <a id="c-struct-ttm_device"></a>`struct ttm_device`

Buffer object driver device-specific data.

**Definition**

```c
struct ttm_device {
    struct list_head device_list;
    unsigned int alloc_flags;
    const struct ttm_device_funcs *funcs;
    struct ttm_resource_manager sysman;
    struct ttm_resource_manager *man_drv[TTM_NUM_MEM_TYPES];
    struct drm_vma_offset_manager *vma_manager;
    struct ttm_pool pool;
    spinlock_t lru_lock;
    struct list_head unevictable;
    struct address_space *dev_mapping;
    struct workqueue_struct *wq;
};
```

**Members**

- `device_list`: Our entry in the global device list.
  Constant after bo device init
- `alloc_flags`: TTM_ALLOCATION_* flags.
- `funcs`: Function table for the device.
  Constant after bo device init
- `sysman`: Resource manager for the system domain.
  Access via ttm_manager_type.
- `man_drv`: An array of resource_managers, one per resource type.
- `vma_manager`: Address space manager for finding BOs to mmap.
- `pool`: page pool for the device.
- `lru_lock`: Protection for the per manager LRU and ddestroy lists.
- `unevictable`: Buffer objects which are pinned or swapped and as such
  not on an LRU list.
- `dev_mapping`: A pointer to the struct address_space for invalidating
  CPU mappings on buffer move. Protected by load/unload sync.
- `wq`: Work queue structure for the delayed delete workqueue.



#### <a id="c-ttm_device_prepare_hibernation"></a>`ttm_device_prepare_hibernation()`

```c
int ttm_device_prepare_hibernation(struct ttm_device *bdev)
```

move GTT BOs to shmem for hibernation.

**Parameters**

- `struct ttm_device *bdev`: A pointer to a struct ttm_device to prepare hibernation for.

**Return**

0 on success, negative number on failure.

#### <a id="c-ttm_device_init"></a>`ttm_device_init()`

```c
int ttm_device_init(struct ttm_device *bdev, const struct ttm_device_funcs *funcs, struct device *dev, struct address_space *mapping, struct drm_vma_offset_manager *vma_manager, unsigned int alloc_flags)
```

**Parameters**

- `struct ttm_device *bdev`: A pointer to a struct ttm_device to initialize.
- `const struct ttm_device_funcs *funcs`: Function table for the device.
- `struct device *dev`: The core kernel device pointer for DMA mappings and allocations.
- `struct address_space *mapping`: The address space to use for this bo.
- `struct drm_vma_offset_manager *vma_manager`: A pointer to a vma manager.
- `unsigned int alloc_flags`: TTM_ALLOCATION_* flags.

**Description**

Initializes a struct ttm_device:

**Return**

!0: Failure.


<a id="rst-ttm-resource-placement-reference"></a>

### TTM resource placement reference


#### <a id="c-struct-ttm_place"></a>`struct ttm_place`

**Definition**

```c
struct ttm_place {
    unsigned fpfn;
    unsigned lpfn;
    uint32_t mem_type;
    uint32_t flags;
};
```

**Members**

- `fpfn`: first valid page frame number to put the object
- `lpfn`: last valid page frame number to put the object
- `mem_type`: One of TTM_PL_* where the resource should be allocated from.
- `flags`: memory domain and caching flags for the object

**Description**

Structure indicating a possible place to put an object.

#### <a id="c-struct-ttm_placement"></a>`struct ttm_placement`

**Definition**

```c
struct ttm_placement {
    unsigned num_placement;
    const struct ttm_place  *placement;
};
```

**Members**

- `num_placement`: number of preferred placements
- `placement`: preferred placements

**Description**

Structure indicating the placement you request for an object.


<a id="rst-ttm-resource-object-reference"></a>

### TTM resource object reference


#### <a id="c-TTM_NUM_MOVE_FENCES"></a>`TTM_NUM_MOVE_FENCES`

```c
TTM_NUM_MOVE_FENCES
```

How many entities can be used for evictions

**Description**

Pipelined evictions can be spread on multiple entities. This
is the max number of entities that can be used by the driver
for that purpose.

#### <a id="c-enum-ttm_lru_item_type"></a>`enum ttm_lru_item_type`

enumerate ttm_lru_item subclasses

**Constants**

- `TTM_LRU_RESOURCE`: The resource subclass
- `TTM_LRU_HITCH`: The iterator hitch subclass

#### <a id="c-struct-ttm_lru_item"></a>`struct ttm_lru_item`

The TTM lru list node base class

**Definition**

```c
struct ttm_lru_item {
    struct list_head link;
    enum ttm_lru_item_type type;
};
```

**Members**

- `link`: The list link
- `type`: The subclass type

#### <a id="c-ttm_lru_item_init"></a>`ttm_lru_item_init()`

```c
void ttm_lru_item_init(struct ttm_lru_item *item, enum ttm_lru_item_type type)
```

initialize a struct ttm_lru_item

**Parameters**

- `struct ttm_lru_item *item`: The item to initialize
- `enum ttm_lru_item_type type`: The subclass type

#### <a id="c-struct-ttm_resource_manager"></a>`struct ttm_resource_manager`

**Definition**

```c
struct ttm_resource_manager {
    bool use_type;
    bool use_tt;
    struct ttm_device *bdev;
    uint64_t size;
    const struct ttm_resource_manager_func *func;
    spinlock_t eviction_lock;
    struct dma_fence *eviction_fences[TTM_NUM_MOVE_FENCES];
    struct list_head lru[TTM_MAX_BO_PRIORITY];
    uint64_t usage;
    struct dmem_cgroup_region *cg;
};
```

**Members**

- `use_type`: The memory type is enabled.
- `use_tt`: If a TT object should be used for the backing store.
- `bdev`: ttm device this manager belongs to
- `size`: Size of the managed region.
- `func`: structure pointer implementing the range manager. See above
- `eviction_lock`: lock for eviction fences
- `eviction_fences`: The fences of the last pipelined move operation.
- `lru`: The lru list for this memory type.
- `usage`: How much of the resources are used, protected by the
  bdev->lru_lock.
- `cg`: `dmem_cgroup_region` used for memory accounting, if not NULL.

**Description**

This structure is used to identify and manage memory types for a device.

#### <a id="c-struct-ttm_bus_placement"></a>`struct ttm_bus_placement`

**Definition**

```c
struct ttm_bus_placement {
    void *addr;
    phys_addr_t offset;
    bool is_iomem;
    enum ttm_caching        caching;
};
```

**Members**

- `addr`: mapped virtual address
- `offset`: physical addr
- `is_iomem`: is this io memory ?
- `caching`: See enum ttm_caching

**Description**

Structure indicating the bus placement of an object.

#### <a id="c-struct-ttm_resource"></a>`struct ttm_resource`

**Definition**

```c
struct ttm_resource {
    unsigned long start;
    size_t size;
    uint32_t mem_type;
    uint32_t placement;
    struct ttm_bus_placement bus;
    struct ttm_buffer_object *bo;
    struct dmem_cgroup_pool_state *css;
    struct ttm_lru_item lru;
};
```

**Members**

- `start`: Start of the allocation.
- `size`: Actual size of resource in bytes.
- `mem_type`: Resource type of the allocation.
- `placement`: Placement flags.
- `bus`: Placement on io bus accessible to the CPU
- `bo`: weak reference to the BO, protected by ttm_device::lru_lock
- `css`: cgroup state this resource is charged to
- `lru`: Least recently used list, see [`ttm_resource_manager.lru`](#c-struct-ttm_resource_manager)

**Description**

Structure indicating the placement and space resources used by a
buffer object.

#### <a id="c-ttm_lru_item_to_res"></a>`ttm_lru_item_to_res()`

```c
struct ttm_resource * ttm_lru_item_to_res(struct ttm_lru_item *item)
```

Downcast a struct ttm_lru_item to a struct ttm_resource

**Parameters**

- `struct ttm_lru_item *item`: The struct ttm_lru_item to downcast

**Return**

Pointer to the embedding struct ttm_resource

#### <a id="c-struct-ttm_lru_bulk_move_pos"></a>`struct ttm_lru_bulk_move_pos`

**Definition**

```c
struct ttm_lru_bulk_move_pos {
    struct ttm_resource *first;
    struct ttm_resource *last;
};
```

**Members**

- `first`: first res in the bulk move range
- `last`: last res in the bulk move range

**Description**

Range of resources for a lru bulk move.

#### <a id="c-struct-ttm_lru_bulk_move"></a>`struct ttm_lru_bulk_move`

**Definition**

```c
struct ttm_lru_bulk_move {
    struct ttm_lru_bulk_move_pos pos[TTM_NUM_MEM_TYPES][TTM_MAX_BO_PRIORITY];
    struct list_head cursor_list;
};
```

**Members**

- `pos`: first/last lru entry for resources in the each domain/priority
- `cursor_list`: The list of cursors currently traversing any of
  the sublists of **pos**. Protected by the ttm device's lru_lock.

**Description**

Container for the current bulk move state. Should be used with
[`ttm_lru_bulk_move_init()`](#c-ttm_lru_bulk_move_init) and `ttm_bo_set_bulk_move()`.
All BOs in a bulk_move structure need to share the same reservation object to
ensure that the bulk as a whole is locked for eviction even if only one BO of
the bulk is evicted.

#### <a id="c-struct-ttm_resource_cursor"></a>`struct ttm_resource_cursor`

**Definition**

```c
struct ttm_resource_cursor {
    struct ttm_resource_manager *man;
    struct ttm_lru_item hitch;
    struct list_head bulk_link;
    struct ttm_lru_bulk_move *bulk;
    unsigned int mem_type;
    unsigned int priority;
};
```

**Members**

- `man`: The resource manager currently being iterated over
- `hitch`: A hitch list node inserted before the next resource
  to iterate over.
- `bulk_link`: A list link for the list of cursors traversing the
  bulk sublist of **bulk**. Protected by the ttm device's lru_lock.
- `bulk`: Pointer to struct ttm_lru_bulk_move whose subrange **hitch** is
  inserted to. NULL if none. Never dereference this pointer since
  the struct ttm_lru_bulk_move object pointed to might have been
  freed. The pointer is only for comparison.
- `mem_type`: The memory type of the LRU list being traversed.
  This field is valid iff **bulk** != NULL.
- `priority`: the current priority

**Description**

Cursor to iterate over the resources in a manager.

#### <a id="c-struct-ttm_kmap_iter_iomap"></a>`struct ttm_kmap_iter_iomap`

Specialization for a struct io_mapping + struct sg_table backed struct ttm_resource.

**Definition**

```c
struct ttm_kmap_iter_iomap {
    struct ttm_kmap_iter base;
    struct io_mapping *iomap;
    struct sg_table *st;
    resource_size_t start;
    struct {
        struct scatterlist *sg;
        pgoff_t i;
        pgoff_t end;
        pgoff_t offs;
    } cache;
};
```

**Members**

- `base`: Embedded struct ttm_kmap_iter providing the usage interface.
- `iomap`: struct io_mapping representing the underlying linear io_memory.
- `st`: sg_table into **iomap**, representing the memory of the struct ttm_resource.
- `start`: Offset that needs to be subtracted from **st** to make
  sg_dma_address(st->sgl) - **start** == 0 for **iomap** start.
- `cache`: Scatterlist traversal cache for fast lookups.
- `cache.sg`: Pointer to the currently cached scatterlist segment.
- `cache.i`: First index of **sg**. PAGE_SIZE granularity.
- `cache.end`: Last index + 1 of **sg**. PAGE_SIZE granularity.
- `cache.offs`: First offset into **iomap** of **sg**. PAGE_SIZE granularity.

#### <a id="c-struct-ttm_kmap_iter_linear_io"></a>`struct ttm_kmap_iter_linear_io`

Iterator specialization for linear io

**Definition**

```c
struct ttm_kmap_iter_linear_io {
    struct ttm_kmap_iter base;
    struct iosys_map dmap;
    bool needs_unmap;
};
```

**Members**

- `base`: The base iterator
- `dmap`: Points to the starting address of the region
- `needs_unmap`: Whether we need to unmap on fini

#### <a id="c-ttm_resource_manager_set_used"></a>`ttm_resource_manager_set_used()`

```c
void ttm_resource_manager_set_used(struct ttm_resource_manager *man, bool used)
```

**Parameters**

- `struct ttm_resource_manager *man`: A memory manager object.
- `bool used`: usage state to set.

**Description**

Set the manager in use flag. If disabled the manager is no longer
used for object placement.

#### <a id="c-ttm_resource_manager_used"></a>`ttm_resource_manager_used()`

```c
bool ttm_resource_manager_used(struct ttm_resource_manager *man)
```

**Parameters**

- `struct ttm_resource_manager *man`: Manager to get used state for

**Description**

Get the in use flag for a manager.

**Return**

true is used, false if not.

#### <a id="c-ttm_resource_manager_cleanup"></a>`ttm_resource_manager_cleanup()`

```c
void ttm_resource_manager_cleanup(struct ttm_resource_manager *man)
```

**Parameters**

- `struct ttm_resource_manager *man`: A memory manager object.

**Description**

Cleanup the move fences from the memory manager object.

#### <a id="c-ttm_resource_manager_for_each_res"></a>`ttm_resource_manager_for_each_res()`

```c
ttm_resource_manager_for_each_res(cursor, res)
```

iterate over all resources

**Parameters**

- `cursor`: struct ttm_resource_cursor for the current position
- `res`: the current resource

**Description**

Iterate over all the evictable resources in a resource manager.



#### <a id="c-ttm_lru_bulk_move_init"></a>`ttm_lru_bulk_move_init()`

```c
void ttm_lru_bulk_move_init(struct ttm_lru_bulk_move *bulk)
```

initialize a bulk move structure

**Parameters**

- `struct ttm_lru_bulk_move *bulk`: the structure to init

**Description**

For now just memset the structure to zero.

#### <a id="c-ttm_lru_bulk_move_fini"></a>`ttm_lru_bulk_move_fini()`

```c
void ttm_lru_bulk_move_fini(struct ttm_device *bdev, struct ttm_lru_bulk_move *bulk)
```

finalize a bulk move structure

**Parameters**

- `struct ttm_device *bdev`: The struct ttm_device
- `struct ttm_lru_bulk_move *bulk`: the structure to finalize

**Description**

Sanity checks that bulk moves don't have any
resources left and hence no cursors attached.

#### <a id="c-ttm_lru_bulk_move_tail"></a>`ttm_lru_bulk_move_tail()`

```c
void ttm_lru_bulk_move_tail(struct ttm_lru_bulk_move *bulk)
```

bulk move range of resources to the LRU tail.

**Parameters**

- `struct ttm_lru_bulk_move *bulk`: bulk move structure

**Description**

Bulk move BOs to the LRU tail, only valid to use when driver makes sure that
resource order never changes. Should be called with [`ttm_device.lru_lock`](#c-struct-ttm_device) held.

#### <a id="c-ttm_resource_init"></a>`ttm_resource_init()`

```c
void ttm_resource_init(struct ttm_buffer_object *bo, const struct ttm_place *place, struct ttm_resource *res)
```

resource object constructure

**Parameters**

- `struct ttm_buffer_object *bo`: buffer object this resources is allocated for
- `const struct ttm_place *place`: placement of the resource
- `struct ttm_resource *res`: the resource object to inistilize

**Description**

Initialize a new resource object. Counterpart of [`ttm_resource_fini()`](#c-ttm_resource_fini).

#### <a id="c-ttm_resource_fini"></a>`ttm_resource_fini()`

```c
void ttm_resource_fini(struct ttm_resource_manager *man, struct ttm_resource *res)
```

resource destructor

**Parameters**

- `struct ttm_resource_manager *man`: the resource manager this resource belongs to
- `struct ttm_resource *res`: the resource to clean up

**Description**

Should be used by resource manager backends to clean up the TTM resource
objects before freeing the underlying structure. Makes sure the resource is
removed from the LRU before destruction.
Counterpart of [`ttm_resource_init()`](#c-ttm_resource_init).

#### <a id="c-ttm_resource_manager_init"></a>`ttm_resource_manager_init()`

```c
void ttm_resource_manager_init(struct ttm_resource_manager *man, struct ttm_device *bdev, uint64_t size)
```

**Parameters**

- `struct ttm_resource_manager *man`: memory manager object to init
- `struct ttm_device *bdev`: ttm device this manager belongs to
- `uint64_t size`: size of managed resources in arbitrary units

**Description**

Initialise core parts of a manager object.

#### <a id="c-ttm_resource_manager_usage"></a>`ttm_resource_manager_usage()`

```c
uint64_t ttm_resource_manager_usage(struct ttm_resource_manager *man)
```

**Parameters**

- `struct ttm_resource_manager *man`: A memory manager object.

**Description**

Return how many resources are currently used.

#### <a id="c-ttm_resource_manager_debug"></a>`ttm_resource_manager_debug()`

```c
void ttm_resource_manager_debug(struct ttm_resource_manager *man, struct drm_printer *p)
```

**Parameters**

- `struct ttm_resource_manager *man`: manager type to dump.
- `struct drm_printer *p`: printer to use for debug.

#### <a id="c-ttm_kmap_iter_iomap_init"></a>`ttm_kmap_iter_iomap_init()`

```c
struct ttm_kmap_iter * ttm_kmap_iter_iomap_init(struct ttm_kmap_iter_iomap *iter_io, struct io_mapping *iomap, struct sg_table *st, resource_size_t start)
```

Initialize a struct ttm_kmap_iter_iomap

**Parameters**

- `struct ttm_kmap_iter_iomap *iter_io`: The struct ttm_kmap_iter_iomap to initialize.
- `struct io_mapping *iomap`: The struct io_mapping representing the underlying linear io_memory.
- `struct sg_table *st`: sg_table into **iomap**, representing the memory of the struct
  ttm_resource.
- `resource_size_t start`: Offset that needs to be subtracted from **st** to make
  sg_dma_address(st->sgl) - **start** == 0 for **iomap** start.

**Return**

Pointer to the embedded struct ttm_kmap_iter.

#### <a id="c-ttm_resource_manager_create_debugfs"></a>`ttm_resource_manager_create_debugfs()`

```c
void ttm_resource_manager_create_debugfs(struct ttm_resource_manager *man, struct dentry * parent, const char *name)
```

Create debugfs entry for specified resource manager.

**Parameters**

- `struct ttm_resource_manager *man`: The TTM resource manager for which the debugfs stats file be creates
- `struct dentry * parent`: debugfs directory in which the file will reside
- `const char *name`: The filename to create.

**Description**

This function setups up a debugfs file that can be used to look
at debug statistics of the specified ttm_resource_manager.


<a id="rst-ttm-tt-object-reference"></a>

### TTM TT object reference


#### <a id="c-struct-ttm_tt"></a>`struct ttm_tt`

This is a structure holding the pages, caching- and aperture binding status for a buffer object that isn't backed by fixed (VRAM / AGP) memory.

**Definition**

```c
struct ttm_tt {
        struct page **pages;
    #define TTM_TT_FLAG_SWAPPED             BIT(0);
    #define TTM_TT_FLAG_ZERO_ALLOC          BIT(1);
    #define TTM_TT_FLAG_EXTERNAL            BIT(2);
    #define TTM_TT_FLAG_EXTERNAL_MAPPABLE   BIT(3);
    #define TTM_TT_FLAG_DECRYPTED           BIT(4);
    #define TTM_TT_FLAG_BACKED_UP           BIT(5);
    #define TTM_TT_FLAG_PRIV_POPULATED      BIT(6);
        uint32_t page_flags;
        uint32_t num_pages;
        struct sg_table *sg;
        dma_addr_t *dma_address;
        struct file *swap_storage;
        struct file *backup;
        enum ttm_caching caching;
        struct ttm_pool_tt_restore *restore;
};
```

**Members**

- `pages`: Array of pages backing the data.
- `page_flags`: The page flags.

  Supported values:

  TTM_TT_FLAG_SWAPPED: Set by TTM when the pages have been unpopulated
  and swapped out by TTM.  Calling [`ttm_tt_populate()`](#c-ttm_tt_populate) will then swap the
  pages back in, and unset the flag. Drivers should in general never
  need to touch this.

  TTM_TT_FLAG_ZERO_ALLOC: Set if the pages will be zeroed on
  allocation.

  TTM_TT_FLAG_EXTERNAL: Set if the underlying pages were allocated
  externally, like with dma-buf or userptr. This effectively disables
  TTM swapping out such pages.  Also important is to prevent TTM from
  ever directly mapping these pages.

  Note that enum ttm_bo_type.ttm_bo_type_sg objects will always enable
  this flag.

  TTM_TT_FLAG_EXTERNAL_MAPPABLE: Same behaviour as
  TTM_TT_FLAG_EXTERNAL, but with the reduced restriction that it is
  still valid to use TTM to map the pages directly. This is useful when
  implementing a ttm_tt backend which still allocates driver owned
  pages underneath(say with shmem).

  Note that since this also implies TTM_TT_FLAG_EXTERNAL, the usage
  here should always be:

  - page_flags = TTM_TT_FLAG_EXTERNAL |

    TTM_TT_FLAG_EXTERNAL_MAPPABLE;

  TTM_TT_FLAG_DECRYPTED: The mapped ttm pages should be marked as
  not encrypted. The framework will try to match what the dma layer
  is doing, but note that it is a little fragile because ttm page
  fault handling abuses the DMA api a bit and dma_map_attrs can't be
  used to assure pgprot always matches.

  TTM_TT_FLAG_BACKED_UP: TTM internal only. This is set if the
  struct ttm_tt has been (possibly partially) backed up.

  TTM_TT_FLAG_PRIV_POPULATED: TTM internal only. DO NOT USE. This is
  set by TTM after [`ttm_tt_populate()`](#c-ttm_tt_populate) has successfully returned, and is
  then unset when TTM calls [`ttm_tt_unpopulate()`](#c-ttm_tt_unpopulate).
- `num_pages`: Number of pages in the page array.
- `sg`: for SG objects via dma-buf.
- `dma_address`: The DMA (bus) addresses of the pages.
- `swap_storage`: Pointer to shmem struct file for swap storage.
- `backup`: Pointer to backup struct for backed up tts.
  Could be unified with **swap_storage**. Meanwhile, the driver's
  [`ttm_tt_create()`](#c-ttm_tt_create) callback is responsible for assigning
  this field.
- `caching`: The current caching state of the pages, see enum
  ttm_caching.
- `restore`: Partial restoration from backup state. TTM private

#### <a id="c-struct-ttm_kmap_iter_tt"></a>`struct ttm_kmap_iter_tt`

Specialization of a mappig iterator for a tt.

**Definition**

```c
struct ttm_kmap_iter_tt {
    struct ttm_kmap_iter base;
    struct ttm_tt *tt;
    pgprot_t prot;
};
```

**Members**

- `base`: Embedded struct ttm_kmap_iter providing the usage interface
- `tt`: Cached struct ttm_tt.
- `prot`: Cached page protection for mapping.

#### <a id="c-ttm_tt_is_swapped"></a>`ttm_tt_is_swapped()`

```c
bool ttm_tt_is_swapped(const struct ttm_tt *tt)
```

Whether the ttm_tt is swapped out or backed up

**Parameters**

- `const struct ttm_tt *tt`: The struct ttm_tt.

**Return**

true if swapped or backed up, false otherwise.

#### <a id="c-ttm_tt_is_backed_up"></a>`ttm_tt_is_backed_up()`

```c
bool ttm_tt_is_backed_up(const struct ttm_tt *tt)
```

Whether the ttm_tt backed up

**Parameters**

- `const struct ttm_tt *tt`: The struct ttm_tt.

**Return**

true if swapped or backed up, false otherwise.

#### <a id="c-ttm_tt_clear_backed_up"></a>`ttm_tt_clear_backed_up()`

```c
void ttm_tt_clear_backed_up(struct ttm_tt *tt)
```

Clear the ttm_tt backed-up status

**Parameters**

- `struct ttm_tt *tt`: The struct ttm_tt.

**Description**

Drivers can use this functionto clear the backed-up status,
for example before destroying or re-validating a purged tt.

#### <a id="c-ttm_tt_create"></a>`ttm_tt_create()`

```c
int ttm_tt_create(struct ttm_buffer_object *bo, bool zero_alloc)
```

**Parameters**

- `struct ttm_buffer_object *bo`: pointer to a struct ttm_buffer_object
- `bool zero_alloc`: true if allocated pages needs to be zeroed

**Description**

Make sure we have a TTM structure allocated for the given BO.
No pages are actually allocated.

#### <a id="c-ttm_tt_init"></a>`ttm_tt_init()`

```c
int ttm_tt_init(struct ttm_tt *ttm, struct ttm_buffer_object *bo, uint32_t page_flags, enum ttm_caching caching, unsigned long extra_pages)
```

**Parameters**

- `struct ttm_tt *ttm`: The struct ttm_tt.
- `struct ttm_buffer_object *bo`: The buffer object we create the ttm for.
- `uint32_t page_flags`: Page flags as identified by TTM_TT_FLAG_XX flags.
- `enum ttm_caching caching`: the desired caching state of the pages
- `unsigned long extra_pages`: Extra pages needed for the driver.

**Description**

Create a struct ttm_tt to back data with system memory pages.
No pages are actually allocated.

**Return**

NULL: Out of memory.

#### <a id="c-ttm_tt_fini"></a>`ttm_tt_fini()`

```c
void ttm_tt_fini(struct ttm_tt *ttm)
```

**Parameters**

- `struct ttm_tt *ttm`: the ttm_tt structure.

**Description**

Free memory of ttm_tt structure

#### <a id="c-ttm_tt_destroy"></a>`ttm_tt_destroy()`

```c
void ttm_tt_destroy(struct ttm_device *bdev, struct ttm_tt *ttm)
```

**Parameters**

- `struct ttm_device *bdev`: the ttm_device this object belongs to
- `struct ttm_tt *ttm`: The struct ttm_tt.

**Description**

Unbind, unpopulate and destroy common struct ttm_tt.

#### <a id="c-ttm_tt_swapin"></a>`ttm_tt_swapin()`

```c
int ttm_tt_swapin(struct ttm_tt *ttm)
```

**Parameters**

- `struct ttm_tt *ttm`: The struct ttm_tt.

**Description**

Swap in a previously swap out ttm_tt.

#### <a id="c-ttm_tt_populate"></a>`ttm_tt_populate()`

```c
int ttm_tt_populate(struct ttm_device *bdev, struct ttm_tt *ttm, struct ttm_operation_ctx *ctx)
```

allocate pages for a ttm

**Parameters**

- `struct ttm_device *bdev`: the ttm_device this object belongs to
- `struct ttm_tt *ttm`: Pointer to the ttm_tt structure
- `struct ttm_operation_ctx *ctx`: operation context for populating the tt object.

**Description**

Calls the driver method to allocate pages for a ttm

#### <a id="c-ttm_tt_unpopulate"></a>`ttm_tt_unpopulate()`

```c
void ttm_tt_unpopulate(struct ttm_device *bdev, struct ttm_tt *ttm)
```

free pages from a ttm

**Parameters**

- `struct ttm_device *bdev`: the ttm_device this object belongs to
- `struct ttm_tt *ttm`: Pointer to the ttm_tt structure

**Description**

Calls the driver method to free all pages from a ttm

#### <a id="c-ttm_tt_mark_for_clear"></a>`ttm_tt_mark_for_clear()`

```c
void ttm_tt_mark_for_clear(struct ttm_tt *ttm)
```

Mark pages for clearing on populate.

**Parameters**

- `struct ttm_tt *ttm`: Pointer to the ttm_tt structure

**Description**

Marks pages for clearing so that the next time the page vector is
populated, the pages will be cleared.

#### <a id="c-struct-ttm_backup_flags"></a>`struct ttm_backup_flags`

Flags to govern backup behaviour.

**Definition**

```c
struct ttm_backup_flags {
    u32 purge : 1;
    u32 writeback : 1;
};
```

**Members**

- `purge`: Free pages without backing up. Bypass pools.
- `writeback`: Attempt to copy contents directly to swap space, even
  if that means blocking on writes to external memory.

#### <a id="c-ttm_agp_tt_create"></a>`ttm_agp_tt_create()`

```c
struct ttm_tt * ttm_agp_tt_create(struct ttm_buffer_object *bo, struct agp_bridge_data *bridge, uint32_t page_flags)
```

**Parameters**

- `struct ttm_buffer_object *bo`: Buffer object we allocate the ttm for.
- `struct agp_bridge_data *bridge`: The agp bridge this device is sitting on.
- `uint32_t page_flags`: Page flags as identified by TTM_TT_FLAG_XX flags.

**Description**

Create a TTM backend that uses the indicated AGP bridge as an aperture
for TT memory. This function uses the linux agpgart interface to
bind and unbind memory backing a ttm_tt.



#### <a id="c-ttm_kmap_iter_tt_init"></a>`ttm_kmap_iter_tt_init()`

```c
struct ttm_kmap_iter * ttm_kmap_iter_tt_init(struct ttm_kmap_iter_tt *iter_tt, struct ttm_tt *tt)
```

Initialize a struct ttm_kmap_iter_tt

**Parameters**

- `struct ttm_kmap_iter_tt *iter_tt`: The struct ttm_kmap_iter_tt to initialize.
- `struct ttm_tt *tt`: Struct ttm_tt holding page pointers of the struct ttm_resource.

**Return**

Pointer to the embedded struct ttm_kmap_iter.

#### <a id="c-ttm_tt_setup_backup"></a>`ttm_tt_setup_backup()`

```c
int ttm_tt_setup_backup(struct ttm_tt *tt)
```

Allocate and assign a backup structure for a ttm_tt

**Parameters**

- `struct ttm_tt *tt`: The ttm_tt for wich to allocate and assign a backup structure.

**Description**

Assign a backup structure to be used for tt backup. This should
typically be done at bo creation, to avoid allocations at shrinking
time.

**Return**

0 on success, negative error code on failure.


<a id="rst-ttm-page-pool-reference"></a>

### TTM page pool reference


#### <a id="c-struct-ttm_pool_type"></a>`struct ttm_pool_type`

Pool for a certain memory type

**Definition**

```c
struct ttm_pool_type {
    struct ttm_pool *pool;
    unsigned int order;
    enum ttm_caching caching;
    struct list_head shrinker_list;
    spinlock_t lock;
    struct list_head pages;
};
```

**Members**

- `pool`: the pool we belong to, might be NULL for the global ones
- `order`: the allocation order our pages have
- `caching`: the caching type our pages have
- `shrinker_list`: our place on the global shrinker list
- `lock`: protection of the page list
- `pages`: the list of pages in the pool

#### <a id="c-struct-ttm_pool"></a>`struct ttm_pool`

Pool for all caching and orders

**Definition**

```c
struct ttm_pool {
    struct device *dev;
    int nid;
    unsigned int alloc_flags;
    struct {
        struct ttm_pool_type orders[NR_PAGE_ORDERS];
    } caching[TTM_NUM_CACHING_TYPES];
};
```

**Members**

- `dev`: the device we allocate pages for
- `nid`: which numa node to use
- `alloc_flags`: TTM_ALLOCATION_POOL_* flags
- `caching`: pools for each caching/order



#### <a id="c-ttm_pool_alloc"></a>`ttm_pool_alloc()`

```c
int ttm_pool_alloc(struct ttm_pool *pool, struct ttm_tt *tt, struct ttm_operation_ctx *ctx)
```

Fill a ttm_tt object

**Parameters**

- `struct ttm_pool *pool`: ttm_pool to use
- `struct ttm_tt *tt`: ttm_tt object to fill
- `struct ttm_operation_ctx *ctx`: operation context

**Description**

Fill the ttm_tt object with pages and also make sure to DMA map them when
necessary.

**Return**

0 on successe, negative error code otherwise.

#### <a id="c-ttm_pool_free"></a>`ttm_pool_free()`

```c
void ttm_pool_free(struct ttm_pool *pool, struct ttm_tt *tt)
```

Free the backing pages from a ttm_tt object

**Parameters**

- `struct ttm_pool *pool`: Pool to give pages back to.
- `struct ttm_tt *tt`: ttm_tt object to unpopulate

**Description**

Give the packing pages back to a pool or free them

#### <a id="c-ttm_pool_init"></a>`ttm_pool_init()`

```c
void ttm_pool_init(struct ttm_pool *pool, struct device *dev, int nid, unsigned int alloc_flags)
```

Initialize a pool

**Parameters**

- `struct ttm_pool *pool`: the pool to initialize
- `struct device *dev`: device for DMA allocations and mappings
- `int nid`: NUMA node to use for allocations
- `unsigned int alloc_flags`: TTM_ALLOCATION_POOL_* flags

**Description**

Initialize the pool and its pool types.

#### <a id="c-ttm_pool_fini"></a>`ttm_pool_fini()`

```c
void ttm_pool_fini(struct ttm_pool *pool)
```

Cleanup a pool

**Parameters**

- `struct ttm_pool *pool`: the pool to clean up

**Description**

Free all pages in the pool and unregister the types from the global
shrinker.

#### <a id="c-ttm_pool_debugfs"></a>`ttm_pool_debugfs()`

```c
int ttm_pool_debugfs(struct ttm_pool *pool, struct seq_file *m)
```

Debugfs dump function for a pool

**Parameters**

- `struct ttm_pool *pool`: the pool to dump the information for
- `struct seq_file *m`: seq_file to dump to

**Description**

Make a debugfs dump with the per pool and global information.


<a id="rst-the-graphics-execution-manager-gem"></a>

## The Graphics Execution Manager (GEM)

The GEM design approach has resulted in a memory manager that doesn't provide full coverage of all (or even all common) use cases in its userspace or kernel API. GEM exposes a set of standard memory-related operations to userspace and a set of helper functions to drivers, and let drivers implement hardware-specific operations with their own private API.

The GEM userspace API is described in the [GEM - the Graphics Execution Manager](<http://lwn.net/Articles/283798/>) article on LWN. While slightly outdated, the document provides a good overview of the GEM API principles. Buffer allocation and read and write operations, described as part of the common GEM API, are currently implemented using driver-specific ioctls.

GEM is data-agnostic. It manages abstract buffer objects without knowing what individual buffers contain. APIs that require knowledge of buffer contents or purpose, such as buffer allocation or synchronization primitives, are thus outside of the scope of GEM and must be implemented using driver-specific ioctls.

On a fundamental level, GEM involves several operations:

- Memory allocation and freeing

- Command execution

- Aperture management at command execution time

Buffer object allocation is relatively straightforward and largely provided by Linux's shmem layer, which provides memory to back each object.

Device-specific operations, such as command execution, pinning, buffer read &amp; write, mapping, and domain ownership transfers are left to driver-specific ioctls.

<a id="rst-gem-initialization"></a>

### GEM Initialization

Drivers that use GEM must set the DRIVER_GEM bit in the struct `struct drm_driver <drm_driver>` driver_features field. The DRM core will then automatically initialize the GEM core before calling the load operation. Behind the scene, this will create a DRM Memory Manager object which provides an address space pool for object allocation.

In a KMS configuration, drivers need to allocate and initialize a command ring buffer following core GEM initialization if required by the hardware. UMA devices usually have what is called a "stolen" memory region, which provides space for the initial framebuffer and large, contiguous memory regions required by the device. This space is typically not managed by GEM, and must be initialized separately into its own DRM MM object.

<a id="rst-gem-objects-creation"></a>

### GEM Objects Creation

GEM splits creation of GEM objects and allocation of the memory that backs them in two distinct operations.

GEM objects are represented by an instance of struct `struct drm_gem_object <drm_gem_object>`. Drivers usually need to extend GEM objects with private information and thus create a driver-specific GEM object structure type that embeds an instance of struct `struct drm_gem_object <drm_gem_object>`.

To create a GEM object, a driver allocates memory for an instance of its specific GEM object type and initializes the embedded struct `struct drm_gem_object <drm_gem_object>` with a call to drm_gem_object_init(). The function takes a pointer to the DRM device, a pointer to the GEM object and the buffer object size in bytes.

GEM uses shmem to allocate anonymous pageable memory. drm_gem_object_init() will create an shmfs file of the requested size and store it into the struct `struct drm_gem_object <drm_gem_object>` filp field. The memory is used as either main storage for the object when the graphics hardware uses system memory directly or as a backing store otherwise. Drivers can call drm_gem_huge_mnt_create() to create, mount and use a huge shmem mountpoint instead of the default one ('shm_mnt'). For builds with CONFIG_TRANSPARENT_HUGEPAGE enabled, further calls to drm_gem_object_init() will let shmem allocate huge pages when possible.

Drivers are responsible for the actual physical pages allocation by calling shmem_read_mapping_page_gfp() for each page. Note that they can decide to allocate pages when initializing the GEM object, or to delay allocation until the memory is needed (for instance when a page fault occurs as a result of a userspace memory access or when the driver needs to start a DMA transfer involving the memory).

Anonymous pageable memory allocation is not always desired, for instance when the hardware requires physically contiguous system memory as is often the case in embedded devices. Drivers can create GEM objects with no shmfs backing (called private GEM objects) by initializing them with a call to drm_gem_private_object_init() instead of drm_gem_object_init(). Storage for private GEM objects must be managed by drivers.

<a id="rst-gem-objects-lifetime"></a>

### GEM Objects Lifetime

All GEM objects are reference-counted by the GEM core. References can be acquired and release by calling drm_gem_object_get() and drm_gem_object_put() respectively.

When the last reference to a GEM object is released the GEM core calls the `struct drm_gem_object_funcs <gem_object_funcs>` free operation. That operation is mandatory for GEM-enabled drivers and must free the GEM object and all associated resources.

void (\*free) (struct drm_gem_object \*obj); Drivers are responsible for freeing all GEM object resources. This includes the resources created by the GEM core, which need to be released with drm_gem_object_release().

<a id="rst-gem-objects-naming"></a>

### GEM Objects Naming

Communication between userspace and the kernel refers to GEM objects using local handles, global names or, more recently, file descriptors. All of those are 32-bit integer values; the usual Linux kernel limits apply to the file descriptors.

GEM handles are local to a DRM file. Applications get a handle to a GEM object through a driver-specific ioctl, and can use that handle to refer to the GEM object in other standard or driver-specific ioctls. Closing a DRM file handle frees all its GEM handles and dereferences the associated GEM objects.

To create a handle for a GEM object drivers call drm_gem_handle_create(). The function takes a pointer to the DRM file and the GEM object and returns a locally unique handle.  When the handle is no longer needed drivers delete it with a call to drm_gem_handle_delete(). Finally the GEM object associated with a handle can be retrieved by a call to drm_gem_object_lookup().

Handles don't take ownership of GEM objects, they only take a reference to the object that will be dropped when the handle is destroyed. To avoid leaking GEM objects, drivers must make sure they drop the reference(s) they own (such as the initial reference taken at object creation time) as appropriate, without any special consideration for the handle. For example, in the particular case of combined GEM object and handle creation in the implementation of the dumb_create operation, drivers must drop the initial reference to the GEM object before returning the handle.

GEM names are similar in purpose to handles but are not local to DRM files. They can be passed between processes to reference a GEM object globally. Names can't be used directly to refer to objects in the DRM API, applications must convert handles to names and names to handles using the DRM_IOCTL_GEM_FLINK and DRM_IOCTL_GEM_OPEN ioctls respectively. The conversion is handled by the DRM core without any driver-specific support.

GEM also supports buffer sharing with dma-buf file descriptors through PRIME. GEM-based drivers must use the provided helpers functions to implement the exporting and importing correctly. See ?. Since sharing file descriptors is inherently more secure than the easily guessable and global GEM names it is the preferred buffer sharing mechanism. Sharing buffers through GEM names is only supported for legacy userspace. Furthermore PRIME also allows cross-device buffer sharing since it is based on dma-bufs.

<a id="rst-gem-objects-mapping"></a>

### GEM Objects Mapping

Because mapping operations are fairly heavyweight GEM favours read/write-like access to buffers, implemented through driver-specific ioctls, over mapping buffers to userspace. However, when random access to the buffer is needed (to perform software rendering for instance), direct access to the object can be more efficient.

The mmap system call can't be used directly to map GEM objects, as they don't have their own file handle. Two alternative methods currently co-exist to map GEM objects to userspace. The first method uses a driver-specific ioctl to perform the mapping operation, calling do_mmap() under the hood. This is often considered dubious, seems to be discouraged for new GEM-enabled drivers, and will thus not be described here.

The second method uses the mmap system call on the DRM file handle. void \*mmap(void \*addr, size_t length, int prot, int flags, int fd, off_t offset); DRM identifies the GEM object to be mapped by a fake offset passed through the mmap offset argument. Prior to being mapped, a GEM object must thus be associated with a fake offset. To do so, drivers must call drm_gem_create_mmap_offset() on the object.

Once allocated, the fake offset value must be passed to the application in a driver-specific way and can then be used as the mmap offset argument.

The GEM core provides a helper method drm_gem_mmap() to handle object mapping. The method can be set directly as the mmap file operation handler. It will look up the GEM object based on the offset value and set the VMA operations to the `struct drm_driver <drm_driver>` gem_vm_ops field. Note that drm_gem_mmap() doesn't map memory to userspace, but relies on the driver-provided fault handler to map pages individually.

To use drm_gem_mmap(), drivers must fill the struct `struct drm_driver <drm_driver>` gem_vm_ops field with a pointer to VM operations.

The VM operations is a `struct vm_operations_struct <vm_operations_struct>` made up of several fields, the more interesting ones being:



```c
struct vm_operations_struct {
        void (*open)(struct vm_area_struct * area);
        void (*close)(struct vm_area_struct * area);
        vm_fault_t (*fault)(struct vm_fault *vmf);
};
```

The open and close operations must update the GEM object reference count. Drivers can use the drm_gem_vm_open() and drm_gem_vm_close() helper functions directly as open and close handlers.

The fault operation handler is responsible for mapping pages to userspace when a page fault occurs. Depending on the memory allocation scheme, drivers can allocate pages at fault time, or can decide to allocate memory for the GEM object at the time the object is created.

Drivers that want to map the GEM object upfront instead of handling page faults can implement their own mmap file operation handler.

In order to reduce page table overhead, if the internal shmem mountpoint "shm_mnt" is configured to use transparent huge pages (for builds with CONFIG_TRANSPARENT_HUGEPAGE enabled) and if the shmem backing store managed to allocate a huge page for a faulty address, the fault handler will first attempt to insert that huge page into the VMA before falling back to individual page insertion. mmap() user address alignment for GEM objects is handled by providing a custom get_unmapped_area file operation which forwards to the shmem backing store. For most drivers, which don't create a huge mountpoint by default or through a module parameter, transparent huge pages can be enabled by either setting the "transparent_hugepage_shmem" kernel parameter or the "/sys/kernel/mm/transparent_hugepage/shmem_enabled" sysfs knob.

For platforms without MMU the GEM core provides a helper method drm_gem_dma_get_unmapped_area(). The mmap() routines will call this to get a proposed address for the mapping.

To use drm_gem_dma_get_unmapped_area(), drivers must fill the struct `struct file_operations <file_operations>` get_unmapped_area field with a pointer on drm_gem_dma_get_unmapped_area().

More detailed information about get_unmapped_area can be found in [Documentation/admin-guide/mm/nommu-mmap.rst](/kernel/administration/admin-guide/mm/nommu-mmap.md)

<a id="rst-memory-coherency"></a>

### Memory Coherency

When mapped to the device or used in a command buffer, backing pages for an object are flushed to memory and marked write combined so as to be coherent with the GPU. Likewise, if the CPU accesses an object after the GPU has finished rendering to the object, then the object must be made coherent with the CPU's view of memory, usually involving GPU cache flushing of various kinds. This core CPU&lt;-&gt;GPU coherency management is provided by a device-specific ioctl, which evaluates an object's current domain and performs any necessary flushing or synchronization to put the object into the desired coherency domain (note that the object may be busy, i.e. an active render target; in that case, setting the domain blocks the client and waits for rendering to complete before performing any necessary flushing operations).

<a id="rst-command-execution"></a>

### Command Execution

Perhaps the most important GEM function for GPU devices is providing a command execution interface to clients. Client programs construct command buffers containing references to previously allocated memory objects, and then submit them to GEM. At that point, GEM takes care to bind all the objects into the GTT, execute the buffer, and provide necessary synchronization between clients accessing the same buffers. This often involves evicting some objects from the GTT and re-binding others (a fairly expensive operation), and providing relocation support which hides fixed GTT offsets from clients. Clients must take care not to submit command buffers that reference more objects than can fit in the GTT; otherwise, GEM will reject them and no rendering will occur. Similarly, if several objects in the buffer require fence registers to be allocated for correct rendering (e.g. 2D blits on pre-965 chips), care must be taken not to require more fence registers than are available to the client. Such resource management should be abstracted from the client in libdrm.

<a id="rst-gem-function-reference"></a>

### GEM Function Reference


#### <a id="c-enum-drm_gem_object_status"></a>`enum drm_gem_object_status`

bitmask of object state for fdinfo reporting

**Constants**

- `DRM_GEM_OBJECT_RESIDENT`: object is resident in memory (ie. not unpinned)
- `DRM_GEM_OBJECT_PURGEABLE`: object marked as purgeable by userspace
- `DRM_GEM_OBJECT_ACTIVE`: object is currently used by an active submission

**Description**

Bitmask of status used for fdinfo memory stats, see [`drm_gem_object_funcs.status`](#c-struct-drm_gem_object_funcs)
and [`drm_show_fdinfo()`](/kernel/hardware/gpu/drm-internals.md#c-drm_show_fdinfo).  Note that an object can report DRM_GEM_OBJECT_PURGEABLE
and be active or not resident, in which case [`drm_show_fdinfo()`](/kernel/hardware/gpu/drm-internals.md#c-drm_show_fdinfo) will not
account for it as purgeable.  So drivers do not need to check if the buffer
is idle and resident to return this bit, i.e. userspace can mark a buffer as
purgeable even while it is still busy on the GPU. It will not get reported in
the puregeable stats until it becomes idle.  The status gem object func does
not need to consider this.

#### <a id="c-struct-drm_gem_object_funcs"></a>`struct drm_gem_object_funcs`

GEM object functions

**Definition**

```c
struct drm_gem_object_funcs {
    void (*free)(struct drm_gem_object *obj);
    int (*open)(struct drm_gem_object *obj, struct drm_file *file);
    void (*close)(struct drm_gem_object *obj, struct drm_file *file);
    void (*print_info)(struct drm_printer *p, unsigned int indent, const struct drm_gem_object *obj);
    struct dma_buf *(*export)(struct drm_gem_object *obj, int flags);
    int (*pin)(struct drm_gem_object *obj);
    void (*unpin)(struct drm_gem_object *obj);
    struct sg_table *(*get_sg_table)(struct drm_gem_object *obj);
    int (*vmap)(struct drm_gem_object *obj, struct iosys_map *map);
    void (*vunmap)(struct drm_gem_object *obj, struct iosys_map *map);
    int (*mmap)(struct drm_gem_object *obj, struct vm_area_struct *vma);
    int (*evict)(struct drm_gem_object *obj);
    enum drm_gem_object_status (*status)(struct drm_gem_object *obj);
    size_t (*rss)(struct drm_gem_object *obj);
    const struct vm_operations_struct *vm_ops;
};
```

**Members**

- `free`: Deconstructor for drm_gem_objects.

  This callback is mandatory.
- `open`: Called upon GEM handle creation.

  This callback is optional.
- `close`: Called upon GEM handle release.

  This callback is optional.
- `print_info`: If driver subclasses struct [`drm_gem_object`](#c-struct-drm_gem_object), it can implement this
  optional hook for printing additional driver specific info.

  [`drm_printf_indent()`](/kernel/hardware/gpu/drm-internals.md#c-drm_printf_indent) should be used in the callback passing it the
  indent argument.

  This callback is called from `drm_gem_print_info()`.

  This callback is optional.
- `export`: Export backing buffer as a [`dma_buf`](/kernel/hardware/driver-api/io-and-dma/dma-buf.md#c-struct-dma_buf).
  If this is not set [`drm_gem_prime_export()`](#c-drm_gem_prime_export) is used.

  This callback is optional.
- `pin`: Pin backing buffer in memory, such that dma-buf importers can
  access it. Used by the [`drm_gem_map_attach()`](#c-drm_gem_map_attach) helper.

  This callback is optional.
- `unpin`: Unpin backing buffer. Used by the [`drm_gem_map_detach()`](#c-drm_gem_map_detach) helper.

  This callback is optional.
- `get_sg_table`: Returns a Scatter-Gather table representation of the buffer.
  Used when exporting a buffer by the [`drm_gem_map_dma_buf()`](#c-drm_gem_map_dma_buf) helper.
  Releasing is done by calling `dma_unmap_sg_attrs()` and [`sg_free_table()`](/kernel/internals/core-api/dma-api.md#c-sg_free_table)
  in `drm_gem_unmap_buf()`, therefore these helpers and this callback
  here cannot be used for sg tables pointing at driver private memory
  ranges.

  See also [`drm_prime_pages_to_sg()`](#c-drm_prime_pages_to_sg).
- `vmap`: Returns a virtual address for the buffer. Used by the
  [`drm_gem_dmabuf_vmap()`](#c-drm_gem_dmabuf_vmap) helper. Called with a held GEM reservation
  lock.

  This callback is optional.
- `vunmap`: Releases the address previously returned by **vmap**. Used by the
  [`drm_gem_dmabuf_vunmap()`](#c-drm_gem_dmabuf_vunmap) helper. Called with a held GEM reservation
  lock.

  This callback is optional.
- `mmap`: Handle `mmap()` of the gem object, setup vma accordingly.

  This callback is optional.

  The callback is used by both [`drm_gem_mmap_obj()`](#c-drm_gem_mmap_obj) and
  [`drm_gem_prime_mmap()`](#c-drm_gem_prime_mmap).  When **mmap** is present **vm_ops** is not
  used, the **mmap** callback must set vma->vm_ops instead.
- `evict`: Evicts gem object out from memory. Used by the `drm_gem_object_evict()`
  helper. Returns 0 on success, -errno otherwise. Called with a held
  GEM reservation lock.

  This callback is optional.
- `status`: The optional status callback can return additional object state
  which determines which stats the object is counted against.  The
  callback is called under table_lock.  Racing against object status
  change is "harmless", and the callback can expect to not race
  against object destruction.

  Called by [`drm_show_memory_stats()`](/kernel/hardware/gpu/drm-internals.md#c-drm_show_memory_stats).
- `rss`: Return resident size of the object in physical memory.

  Called by [`drm_show_memory_stats()`](/kernel/hardware/gpu/drm-internals.md#c-drm_show_memory_stats).
- `vm_ops`: Virtual memory operations used with mmap.

  This is optional but necessary for mmap support.

#### <a id="c-struct-drm_gem_lru"></a>`struct drm_gem_lru`

A simple LRU helper

**Definition**

```c
struct drm_gem_lru {
    struct mutex *lock;
    long count;
    struct list_head list;
};
```

**Members**

- `lock`: Lock protecting movement of GEM objects between LRUs.  All
  LRUs that the object can move between should be protected
  by the same lock.
- `count`: The total number of backing pages of the GEM objects in
  this LRU.
- `list`: The LRU list.

**Description**

A helper for tracking GEM objects in a given state, to aid in
driver's shrinker implementation.  Tracks the count of pages
for lockless `shrinker.count_objects`, and provides
[`drm_gem_lru_scan`](#c-drm_gem_lru_scan) for driver's `shrinker.scan_objects`
implementation.

#### <a id="c-struct-drm_gem_object"></a>`struct drm_gem_object`

GEM buffer object

**Definition**

```c
struct drm_gem_object {
    struct kref refcount;
    unsigned handle_count;
    struct drm_device *dev;
    struct file *filp;
    struct drm_vma_offset_node vma_node;
    size_t size;
    int name;
    struct dma_buf *dma_buf;
    struct dma_buf_attachment *import_attach;
    struct dma_resv *resv;
    struct dma_resv _resv;
    struct {
        struct list_head list;
        struct mutex lock;
    } gpuva;
    const struct drm_gem_object_funcs *funcs;
    struct list_head lru_node;
    struct drm_gem_lru *lru;
};
```

**Members**

- `refcount`: Reference count of this object

  Please use [`drm_gem_object_get()`](#c-drm_gem_object_get) to acquire and `drm_gem_object_put_locked()`
  or [`drm_gem_object_put()`](#c-drm_gem_object_put) to release a reference to a GEM
  buffer object.
- `handle_count`: This is the GEM file_priv handle count of this object.

  Each handle also holds a reference. Note that when the handle_count
  drops to 0 any global names (e.g. the id in the flink namespace) will
  be cleared.

  Protected by [`drm_device.object_name_lock`](/kernel/hardware/gpu/drm-internals.md#c-struct-drm_device).
- `dev`: DRM dev this object belongs to.
- `filp`: SHMEM file node used as backing storage for swappable buffer objects.
  GEM also supports driver private objects with driver-specific backing
  storage (contiguous DMA memory, special reserved blocks). In this
  case **filp** is NULL.
- `vma_node`: Mapping info for this object to support mmap. Drivers are supposed to
  allocate the mmap offset using [`drm_gem_create_mmap_offset()`](#c-drm_gem_create_mmap_offset). The
  offset itself can be retrieved using [`drm_vma_node_offset_addr()`](#c-drm_vma_node_offset_addr).

  Memory mapping itself is handled by [`drm_gem_mmap()`](#c-drm_gem_mmap), which also checks
  that userspace is allowed to access the object.
- `size`: Size of the object, in bytes.  Immutable over the object's
  lifetime.
- `name`: Global name for this object, starts at 1. 0 means unnamed.
  Access is covered by [`drm_device.object_name_lock`](/kernel/hardware/gpu/drm-internals.md#c-struct-drm_device). This is used by
  the GEM_FLINK and GEM_OPEN ioctls.
- `dma_buf`: dma-buf associated with this GEM object.

  Pointer to the dma-buf associated with this gem object (either
  through importing or exporting). We break the resulting reference
  loop when the last gem handle for this object is released.

  Protected by [`drm_device.object_name_lock`](/kernel/hardware/gpu/drm-internals.md#c-struct-drm_device).
- `import_attach`: dma-buf attachment backing this object.

  Any foreign dma_buf imported as a gem object has this set to the
  attachment point for the device. This is invariant over the lifetime
  of a gem object.

  The [`drm_gem_object_funcs.free`](#c-struct-drm_gem_object_funcs) callback is responsible for
  cleaning up the dma_buf attachment and references acquired at import
  time.

  Note that the drm gem/prime core does not depend upon drivers setting
  this field any more. So for drivers where this doesn't make sense
  (e.g. virtual devices or a displaylink behind an usb bus) they can
  simply leave it as NULL.
- `resv`: Pointer to reservation object associated with the this GEM object.

  Normally (**resv** == &**_resv**) except for imported GEM objects.
- `_resv`: A reservation object for this GEM object.

  This is unused for imported GEM objects.
- `gpuva`: Fields used by GPUVM to manage mappings pointing to this GEM object.

  When DRM_GPUVM_IMMEDIATE_MODE is set, this list is protected by the
  mutex. Otherwise, the list is protected by the GEMs [`dma_resv`](/kernel/hardware/driver-api/io-and-dma/dma-buf.md#c-struct-dma_resv) lock.

  Note that all entries in this list must agree on whether
  DRM_GPUVM_IMMEDIATE_MODE is set.
- `gpuva.list`: list of GPUVM mappings attached to this GEM object.

  Drivers should lock list accesses with either the GEMs
  [`dma_resv`](/kernel/hardware/driver-api/io-and-dma/dma-buf.md#c-struct-dma_resv) lock ([`drm_gem_object.resv`](#c-struct-drm_gem_object)) or the
  [`drm_gem_object.gpuva`](#c-struct-drm_gem_object).lock mutex.
- `gpuva.lock`: lock protecting access to [`drm_gem_object.gpuva`](#c-struct-drm_gem_object).list
  when DRM_GPUVM_IMMEDIATE_MODE is used.

  Only used when DRM_GPUVM_IMMEDIATE_MODE is set. It should be
  safe to take this mutex during the fence signalling path, so
  do not allocate memory while holding this lock. Otherwise,
  the [`dma_resv`](/kernel/hardware/driver-api/io-and-dma/dma-buf.md#c-struct-dma_resv) lock should be used.
- `funcs`: Optional GEM object functions. If this is set, it will be used instead of the
  corresponding [`drm_driver`](/kernel/hardware/gpu/drm-internals.md#c-struct-drm_driver) GEM callbacks.

  New drivers should use this.
- `lru_node`: List node in a [`drm_gem_lru`](#c-struct-drm_gem_lru).
- `lru`: The current LRU list that the GEM object is on.

**Description**

This structure defines the generic parts for GEM buffer objects, which are
mostly around handling mmap and userspace handles.

Buffer objects are often abbreviated to BO.

#### <a id="c-DRM_GEM_FOPS"></a>`DRM_GEM_FOPS`

```c
DRM_GEM_FOPS
```

Default drm GEM file operations

**Description**

This macro provides a shorthand for setting the GEM file ops in the
`file_operations` structure.  If all you need are the default ops, use
DEFINE_DRM_GEM_FOPS instead.

#### <a id="c-DEFINE_DRM_GEM_FOPS"></a>`DEFINE_DRM_GEM_FOPS()`

```c
DEFINE_DRM_GEM_FOPS(name)
```

macro to generate file operations for GEM drivers

**Parameters**

- `name`: name for the generated structure

**Description**

This macro autogenerates a suitable `struct file_operations` for GEM based
drivers, which can be assigned to [`drm_driver.fops`](/kernel/hardware/gpu/drm-internals.md#c-struct-drm_driver). Note that this structure
cannot be shared between drivers, because it contains a reference to the
current module using THIS_MODULE.

Note that the declaration is already marked as static - if you need a
non-static version of this you're probably doing it wrong and will break the
THIS_MODULE reference by accident.

#### <a id="c-drm_gem_get_huge_mnt"></a>`drm_gem_get_huge_mnt()`

```c
struct vfsmount * drm_gem_get_huge_mnt(struct drm_device *dev)
```

Get the huge tmpfs mountpoint used by a DRM device

**Parameters**

- `struct drm_device *dev`: DRM device

**Description**

This function gets the huge tmpfs mountpoint used by DRM device **dev**. A huge
tmpfs mountpoint is used instead of `shm_mnt` after a successful call to
[`drm_gem_huge_mnt_create()`](#c-drm_gem_huge_mnt_create) when CONFIG_TRANSPARENT_HUGEPAGE is enabled.

**Return**

The huge tmpfs mountpoint in use, NULL otherwise.

#### <a id="c-drm_gem_object_get"></a>`drm_gem_object_get()`

```c
void drm_gem_object_get(struct drm_gem_object *obj)
```

acquire a GEM buffer object reference

**Parameters**

- `struct drm_gem_object *obj`: GEM buffer object

**Description**

This function acquires an additional reference to **obj**. It is illegal to
call this without already holding a reference. No locks required.

#### <a id="c-drm_gem_object_put"></a>`drm_gem_object_put()`

```c
void drm_gem_object_put(struct drm_gem_object *obj)
```

drop a GEM buffer object reference

**Parameters**

- `struct drm_gem_object *obj`: GEM buffer object

**Description**

This releases a reference to **obj**.

#### <a id="c-drm_gem_object_is_shared_for_memory_stats"></a>`drm_gem_object_is_shared_for_memory_stats()`

```c
bool drm_gem_object_is_shared_for_memory_stats(struct drm_gem_object *obj)
```

helper for shared memory stats

**Parameters**

- `struct drm_gem_object *obj`: obj in question

**Description**

This helper should only be used for fdinfo shared memory stats to determine
if a GEM object is shared.

#### <a id="c-drm_gem_is_imported"></a>`drm_gem_is_imported()`

```c
bool drm_gem_is_imported(const struct drm_gem_object *obj)
```

Tests if GEM object's buffer has been imported

**Parameters**

- `const struct drm_gem_object *obj`: the GEM object

**Return**

True if the GEM object's buffer has been imported, false otherwise

#### <a id="c-drm_gem_gpuva_init"></a>`drm_gem_gpuva_init()`

```c
void drm_gem_gpuva_init(struct drm_gem_object *obj)
```

initialize the gpuva list of a GEM object

**Parameters**

- `struct drm_gem_object *obj`: the [`drm_gem_object`](#c-struct-drm_gem_object)

**Description**

This initializes the [`drm_gem_object`](#c-struct-drm_gem_object)'s [`drm_gpuvm_bo`](#c-struct-drm_gpuvm_bo) list.

Calling this function is only necessary for drivers intending to support the
[`drm_driver_feature`](/kernel/hardware/gpu/drm-internals.md#c-enum-drm_driver_feature) DRIVER_GEM_GPUVA.

See also `drm_gem_gpuva_set_lock()`.

#### <a id="c-drm_gem_for_each_gpuvm_bo"></a>`drm_gem_for_each_gpuvm_bo()`

```c
drm_gem_for_each_gpuvm_bo(entry__, obj__)
```

iterator to walk over a list of [`drm_gpuvm_bo`](#c-struct-drm_gpuvm_bo)

**Parameters**

- `entry__`: [`drm_gpuvm_bo`](#c-struct-drm_gpuvm_bo) structure to assign to in each iteration step
- `obj__`: the [`drm_gem_object`](#c-struct-drm_gem_object) the [`drm_gpuvm_bo`](#c-struct-drm_gpuvm_bo) to walk are associated with

**Description**

This iterator walks over all [`drm_gpuvm_bo`](#c-struct-drm_gpuvm_bo) structures associated with the
[`drm_gem_object`](#c-struct-drm_gem_object).

#### <a id="c-drm_gem_for_each_gpuvm_bo_safe"></a>`drm_gem_for_each_gpuvm_bo_safe()`

```c
drm_gem_for_each_gpuvm_bo_safe(entry__, next__, obj__)
```

iterator to safely walk over a list of [`drm_gpuvm_bo`](#c-struct-drm_gpuvm_bo)

**Parameters**

- `entry__`: `drm_gpuvm_bostructure` to assign to in each iteration step
- `next__`: `next` [`drm_gpuvm_bo`](#c-struct-drm_gpuvm_bo) to store the next step
- `obj__`: the [`drm_gem_object`](#c-struct-drm_gem_object) the [`drm_gpuvm_bo`](#c-struct-drm_gpuvm_bo) to walk are associated with

**Description**

This iterator walks over all [`drm_gpuvm_bo`](#c-struct-drm_gpuvm_bo) structures associated with the
[`drm_gem_object`](#c-struct-drm_gem_object). It is implemented with [`list_for_each_entry_safe()`](/kernel/internals/core-api/list.md#c-list_for_each_entry_safe), hence
it is save against removal of elements.



#### <a id="c-drm_gem_huge_mnt_create"></a>`drm_gem_huge_mnt_create()`

```c
int drm_gem_huge_mnt_create(struct drm_device *dev, const char *value)
```

Create, mount and use a huge tmpfs mountpoint

**Parameters**

- `struct drm_device *dev`: DRM device that will use the huge tmpfs mountpoint
- `const char *value`: huge tmpfs mount option value

**Description**

This function creates and mounts a dedicated huge tmpfs mountpoint for the
lifetime of the DRM device **dev** which is used at GEM object initialization
with [`drm_gem_object_init()`](#c-drm_gem_object_init).

The most common option for **value** is "within_size" which only allocates huge
pages if the page will be fully within the GEM object size. "always",
"advise" and "never" are supported too but the latter would just create a
mountpoint similar to the default one (`shm_mnt`). See shmemfs and
Transparent Hugepage for more information.

**Return**

0 on success or a negative error code on failure.

#### <a id="c-drm_gem_object_init"></a>`drm_gem_object_init()`

```c
int drm_gem_object_init(struct drm_device *dev, struct drm_gem_object *obj, size_t size)
```

initialize an allocated shmem-backed GEM object

**Parameters**

- `struct drm_device *dev`: drm_device the object should be initialized for
- `struct drm_gem_object *obj`: drm_gem_object to initialize
- `size_t size`: object size

**Description**

Initialize an already allocated GEM object of the specified size with
shmfs backing store. A huge mountpoint can be used by calling
[`drm_gem_huge_mnt_create()`](#c-drm_gem_huge_mnt_create) beforehand.

#### <a id="c-drm_gem_private_object_init"></a>`drm_gem_private_object_init()`

```c
void drm_gem_private_object_init(struct drm_device *dev, struct drm_gem_object *obj, size_t size)
```

initialize an allocated private GEM object

**Parameters**

- `struct drm_device *dev`: drm_device the object should be initialized for
- `struct drm_gem_object *obj`: drm_gem_object to initialize
- `size_t size`: object size

**Description**

Initialize an already allocated GEM object of the specified size with
no GEM provided backing store. Instead the caller is responsible for
backing the object and handling it.

#### <a id="c-drm_gem_private_object_fini"></a>`drm_gem_private_object_fini()`

```c
void drm_gem_private_object_fini(struct drm_gem_object *obj)
```

Finalize a failed drm_gem_object

**Parameters**

- `struct drm_gem_object *obj`: drm_gem_object

**Description**

Uninitialize an already allocated GEM object when it initialized failed

#### <a id="c-drm_gem_handle_delete"></a>`drm_gem_handle_delete()`

```c
int drm_gem_handle_delete(struct drm_file *filp, u32 handle)
```

deletes the given file-private handle

**Parameters**

- `struct drm_file *filp`: drm file-private structure to use for the handle look up
- `u32 handle`: userspace handle to delete

**Description**

Removes the GEM handle from the **filp** lookup table which has been added with
[`drm_gem_handle_create()`](#c-drm_gem_handle_create). If this is the last handle also cleans up linked
resources like GEM names.

#### <a id="c-drm_gem_dumb_map_offset"></a>`drm_gem_dumb_map_offset()`

```c
int drm_gem_dumb_map_offset(struct drm_file *file, struct drm_device *dev, u32 handle, u64 *offset)
```

return the fake mmap offset for a gem object

**Parameters**

- `struct drm_file *file`: drm file-private structure containing the gem object
- `struct drm_device *dev`: corresponding drm_device
- `u32 handle`: gem object handle
- `u64 *offset`: return location for the fake mmap offset

**Description**

This implements the [`drm_driver.dumb_map_offset`](/kernel/hardware/gpu/drm-internals.md#c-struct-drm_driver) kms driver callback for
drivers which use gem to manage their backing storage.

**Return**

0 on success or a negative error code on failure.

#### <a id="c-drm_gem_handle_create"></a>`drm_gem_handle_create()`

```c
int drm_gem_handle_create(struct drm_file *file_priv, struct drm_gem_object *obj, u32 *handlep)
```

create a gem handle for an object

**Parameters**

- `struct drm_file *file_priv`: drm file-private structure to register the handle for
- `struct drm_gem_object *obj`: object to register
- `u32 *handlep`: pointer to return the created handle to the caller

**Description**

Create a handle for this object. This adds a handle reference to the object,
which includes a regular reference count. Callers will likely want to
dereference the object afterwards.

Since this publishes **obj** to userspace it must be fully set up by this point,
drivers must call this last in their buffer object creation callbacks.

#### <a id="c-drm_gem_free_mmap_offset"></a>`drm_gem_free_mmap_offset()`

```c
void drm_gem_free_mmap_offset(struct drm_gem_object *obj)
```

release a fake mmap offset for an object

**Parameters**

- `struct drm_gem_object *obj`: obj in question

**Description**

This routine frees fake offsets allocated by [`drm_gem_create_mmap_offset()`](#c-drm_gem_create_mmap_offset).

Note that [`drm_gem_object_release()`](#c-drm_gem_object_release) already calls this function, so drivers
don't have to take care of releasing the mmap offset themselves when freeing
the GEM object.

#### <a id="c-drm_gem_create_mmap_offset_size"></a>`drm_gem_create_mmap_offset_size()`

```c
int drm_gem_create_mmap_offset_size(struct drm_gem_object *obj, size_t size)
```

create a fake mmap offset for an object

**Parameters**

- `struct drm_gem_object *obj`: obj in question
- `size_t size`: the virtual size

**Description**

GEM memory mapping works by handing back to userspace a fake mmap offset
it can use in a subsequent mmap(2) call.  The DRM core code then looks
up the object based on the offset and sets up the various memory mapping
structures.

This routine allocates and attaches a fake offset for **obj**, in cases where
the virtual size differs from the physical size (ie. [`drm_gem_object.size`](#c-struct-drm_gem_object)).
Otherwise just use [`drm_gem_create_mmap_offset()`](#c-drm_gem_create_mmap_offset).

This function is idempotent and handles an already allocated mmap offset
transparently. Drivers do not need to check for this case.

#### <a id="c-drm_gem_create_mmap_offset"></a>`drm_gem_create_mmap_offset()`

```c
int drm_gem_create_mmap_offset(struct drm_gem_object *obj)
```

create a fake mmap offset for an object

**Parameters**

- `struct drm_gem_object *obj`: obj in question

**Description**

GEM memory mapping works by handing back to userspace a fake mmap offset
it can use in a subsequent mmap(2) call.  The DRM core code then looks
up the object based on the offset and sets up the various memory mapping
structures.

This routine allocates and attaches a fake offset for **obj**.

Drivers can call [`drm_gem_free_mmap_offset()`](#c-drm_gem_free_mmap_offset) before freeing **obj** to release
the fake offset again.

#### <a id="c-drm_gem_get_pages"></a>`drm_gem_get_pages()`

```c
struct page ** drm_gem_get_pages(struct drm_gem_object *obj)
```

helper to allocate backing pages for a GEM object from shmem

**Parameters**

- `struct drm_gem_object *obj`: obj in question

**Description**

This reads the page-array of the shmem-backing storage of the given gem
object. An array of pages is returned. If a page is not allocated or
swapped-out, this will allocate/swap-in the required pages. Note that the
whole object is covered by the page-array and pinned in memory.

Use [`drm_gem_put_pages()`](#c-drm_gem_put_pages) to release the array and unpin all pages.

This uses the GFP-mask set on the shmem-mapping (see `mapping_set_gfp_mask()`).
If you require other GFP-masks, you have to do those allocations yourself.

Note that you are not allowed to change gfp-zones during runtime. That is,
`shmem_read_mapping_page_gfp()` must be called with the same gfp_zone(gfp) as
set during initialization. If you have special zone constraints, set them
after [`drm_gem_object_init()`](#c-drm_gem_object_init) via `mapping_set_gfp_mask()`. shmem-core takes care
to keep pages in the required zone during swap-in.

This function is only valid on objects initialized with
[`drm_gem_object_init()`](#c-drm_gem_object_init), but not for those initialized with
[`drm_gem_private_object_init()`](#c-drm_gem_private_object_init) only.

#### <a id="c-drm_gem_put_pages"></a>`drm_gem_put_pages()`

```c
void drm_gem_put_pages(struct drm_gem_object *obj, struct page **pages, bool dirty, bool accessed)
```

helper to free backing pages for a GEM object

**Parameters**

- `struct drm_gem_object *obj`: obj in question
- `struct page **pages`: pages to free
- `bool dirty`: if true, pages will be marked as dirty
- `bool accessed`: if true, the pages will be marked as accessed

#### <a id="c-drm_gem_objects_lookup"></a>`drm_gem_objects_lookup()`

```c
int drm_gem_objects_lookup(struct drm_file *filp, void __user *bo_handles, int count, struct drm_gem_object ***objs_out)
```

look up GEM objects from an array of handles

**Parameters**

- `struct drm_file *filp`: DRM file private date
- `void __user *bo_handles`: user pointer to array of userspace handle
- `int count`: size of handle array
- `struct drm_gem_object ***objs_out`: returned pointer to array of drm_gem_object pointers

**Description**

Takes an array of userspace handles and returns a newly allocated array of
GEM objects.

For a single handle lookup, use [`drm_gem_object_lookup()`](#c-drm_gem_object_lookup).

**Return**

**objs** filled in with GEM object pointers. Returned GEM objects need to be
released with [`drm_gem_object_put()`](#c-drm_gem_object_put). -ENOENT is returned on a lookup
failure. 0 is returned on success.

#### <a id="c-drm_gem_object_lookup"></a>`drm_gem_object_lookup()`

```c
struct drm_gem_object * drm_gem_object_lookup(struct drm_file *filp, u32 handle)
```

look up a GEM object from its handle

**Parameters**

- `struct drm_file *filp`: DRM file private date
- `u32 handle`: userspace handle

**Description**

If looking up an array of handles, use [`drm_gem_objects_lookup()`](#c-drm_gem_objects_lookup).

**Return**

A reference to the object named by the handle if such exists on **filp**, NULL
otherwise.

#### <a id="c-drm_gem_dma_resv_wait"></a>`drm_gem_dma_resv_wait()`

```c
long drm_gem_dma_resv_wait(struct drm_file *filep, u32 handle, bool wait_all, unsigned long timeout)
```

Wait on GEM object's reservation's objects shared and/or exclusive fences.

**Parameters**

- `struct drm_file *filep`: DRM file private date
- `u32 handle`: userspace handle
- `bool wait_all`: if true, wait on all fences, else wait on just exclusive fence
- `unsigned long timeout`: timeout value in jiffies or zero to return immediately

**Return**

Returns -ERESTARTSYS if interrupted, 0 if the wait timed out, or
greater than 0 on success.

#### <a id="c-drm_gem_object_release"></a>`drm_gem_object_release()`

```c
void drm_gem_object_release(struct drm_gem_object *obj)
```

release GEM buffer object resources

**Parameters**

- `struct drm_gem_object *obj`: GEM buffer object

**Description**

This releases any structures and resources used by **obj** and is the inverse of
[`drm_gem_object_init()`](#c-drm_gem_object_init).

#### <a id="c-drm_gem_object_free"></a>`drm_gem_object_free()`

```c
void drm_gem_object_free(struct kref *kref)
```

free a GEM object

**Parameters**

- `struct kref *kref`: kref of the object to free

**Description**

Called after the last reference to the object has been lost.

Frees the object

#### <a id="c-drm_gem_vm_open"></a>`drm_gem_vm_open()`

```c
void drm_gem_vm_open(struct vm_area_struct *vma)
```

vma->ops->open implementation for GEM

**Parameters**

- `struct vm_area_struct *vma`: VM area structure

**Description**

This function implements the #vm_operations_struct `open()` callback for GEM
drivers. This must be used together with [`drm_gem_vm_close()`](#c-drm_gem_vm_close).

#### <a id="c-drm_gem_vm_close"></a>`drm_gem_vm_close()`

```c
void drm_gem_vm_close(struct vm_area_struct *vma)
```

vma->ops->close implementation for GEM

**Parameters**

- `struct vm_area_struct *vma`: VM area structure

**Description**

This function implements the #vm_operations_struct `close()` callback for GEM
drivers. This must be used together with [`drm_gem_vm_open()`](#c-drm_gem_vm_open).

#### <a id="c-drm_gem_mmap_obj"></a>`drm_gem_mmap_obj()`

```c
int drm_gem_mmap_obj(struct drm_gem_object *obj, unsigned long obj_size, struct vm_area_struct *vma)
```

memory map a GEM object

**Parameters**

- `struct drm_gem_object *obj`: the GEM object to map
- `unsigned long obj_size`: the object size to be mapped, in bytes
- `struct vm_area_struct *vma`: VMA for the area to be mapped

**Description**

Set up the VMA to prepare mapping of the GEM object using the GEM object's
vm_ops. Depending on their requirements, GEM objects can either
provide a fault handler in their vm_ops (in which case any accesses to
the object will be trapped, to perform migration, GTT binding, surface
register allocation, or performance monitoring), or mmap the buffer memory
synchronously after calling drm_gem_mmap_obj.

This function is mainly intended to implement the DMABUF mmap operation, when
the GEM object is not looked up based on its fake offset. To implement the
DRM mmap operation, drivers should use the [`drm_gem_mmap()`](#c-drm_gem_mmap) function.

[`drm_gem_mmap_obj()`](#c-drm_gem_mmap_obj) assumes the user is granted access to the buffer while
[`drm_gem_mmap()`](#c-drm_gem_mmap) prevents unprivileged users from mapping random objects. So
callers must verify access restrictions before calling this helper.

Return 0 or success or -EINVAL if the object size is smaller than the VMA
size, or if no vm_ops are provided.

#### <a id="c-drm_gem_get_unmapped_area"></a>`drm_gem_get_unmapped_area()`

```c
unsigned long drm_gem_get_unmapped_area(struct file *filp, unsigned long uaddr, unsigned long len, unsigned long pgoff, unsigned long flags)
```

get memory mapping region routine for GEM objects

**Parameters**

- `struct file *filp`: DRM file pointer
- `unsigned long uaddr`: User address hint
- `unsigned long len`: Mapping length
- `unsigned long pgoff`: Offset (in pages)
- `unsigned long flags`: Mapping flags

**Description**

If a driver supports GEM object mapping, before ending up in [`drm_gem_mmap()`](#c-drm_gem_mmap),
mmap calls on the DRM file descriptor will first try to find a free linear
address space large enough for a mapping. Since GEM objects are backed by
shmem buffers, this should preferably be handled by the shmem virtual memory
filesystem which can appropriately align addresses to huge page sizes when
needed.

Look up the GEM object based on the offset passed in (vma->vm_pgoff will
contain the fake offset we created) and call `shmem_get_unmapped_area()` with
the right file pointer.

If a GEM object is not available at the given offset or if the caller is not
granted access to it, fall back to `mm_get_unmapped_area()`.

#### <a id="c-drm_gem_mmap"></a>`drm_gem_mmap()`

```c
int drm_gem_mmap(struct file *filp, struct vm_area_struct *vma)
```

memory map routine for GEM objects

**Parameters**

- `struct file *filp`: DRM file pointer
- `struct vm_area_struct *vma`: VMA for the area to be mapped

**Description**

If a driver supports GEM object mapping, mmap calls on the DRM file
descriptor will end up here.

Look up the GEM object based on the offset passed in (vma->vm_pgoff will
contain the fake offset we created) and map it with a call to
[`drm_gem_mmap_obj()`](#c-drm_gem_mmap_obj).

If the caller is not granted access to the buffer object, the mmap will fail
with EACCES. Please see the vma manager for more information.

#### <a id="c-drm_gem_lock_reservations"></a>`drm_gem_lock_reservations()`

```c
int drm_gem_lock_reservations(struct drm_gem_object **objs, int count, struct ww_acquire_ctx *acquire_ctx)
```

Sets up the ww context and acquires the lock on an array of GEM objects.

**Parameters**

- `struct drm_gem_object **objs`: drm_gem_objects to lock
- `int count`: Number of objects in **objs**
- `struct ww_acquire_ctx *acquire_ctx`: struct ww_acquire_ctx that will be initialized as
  part of tracking this set of locked reservations.

**Description**

Once you've locked your reservations, you'll want to set up space
for your shared fences (if applicable), submit your job, then
`drm_gem_unlock_reservations()`.

#### <a id="c-drm_gem_lru_init"></a>`drm_gem_lru_init()`

```c
void drm_gem_lru_init(struct drm_gem_lru *lru, struct mutex *lock)
```

initialize a LRU

**Parameters**

- `struct drm_gem_lru *lru`: The LRU to initialize
- `struct mutex *lock`: The lock protecting the LRU

#### <a id="c-drm_gem_lru_remove"></a>`drm_gem_lru_remove()`

```c
void drm_gem_lru_remove(struct drm_gem_object *obj)
```

remove object from whatever LRU it is in

**Parameters**

- `struct drm_gem_object *obj`: The GEM object to remove from current LRU

**Description**

If the object is currently in any LRU, remove it.

#### <a id="c-drm_gem_lru_move_tail_locked"></a>`drm_gem_lru_move_tail_locked()`

```c
void drm_gem_lru_move_tail_locked(struct drm_gem_lru *lru, struct drm_gem_object *obj)
```

move the object to the tail of the LRU

**Parameters**

- `struct drm_gem_lru *lru`: The LRU to move the object into.
- `struct drm_gem_object *obj`: The GEM object to move into this LRU

**Description**

Like [`drm_gem_lru_move_tail`](#c-drm_gem_lru_move_tail) but lru lock must be held

#### <a id="c-drm_gem_lru_move_tail"></a>`drm_gem_lru_move_tail()`

```c
void drm_gem_lru_move_tail(struct drm_gem_lru *lru, struct drm_gem_object *obj)
```

move the object to the tail of the LRU

**Parameters**

- `struct drm_gem_lru *lru`: The LRU to move the object into.
- `struct drm_gem_object *obj`: The GEM object to move into this LRU

**Description**

If the object is already in this LRU it will be moved to the
tail.  Otherwise it will be removed from whichever other LRU
it is in (if any) and moved into this LRU.

#### <a id="c-drm_gem_lru_scan"></a>`drm_gem_lru_scan()`

```c
unsigned long drm_gem_lru_scan(struct drm_gem_lru *lru, unsigned int nr_to_scan, unsigned long *remaining, bool (*shrink)(struct drm_gem_object *obj, struct ww_acquire_ctx *ticket), struct ww_acquire_ctx *ticket)
```

helper to implement shrinker.scan_objects

**Parameters**

- `struct drm_gem_lru *lru`: The LRU to scan
- `unsigned int nr_to_scan`: The number of pages to try to reclaim
- `unsigned long *remaining`: The number of pages left to reclaim, should be initialized by caller
- `bool (*shrink)(struct drm_gem_object *obj, struct ww_acquire_ctx *ticket)`: Callback to try to shrink/reclaim the object.
- `struct ww_acquire_ctx *ticket`: Optional ww_acquire_ctx context to use for locking

**Description**

If the shrink callback succeeds, it is expected that the driver
move the object out of this LRU.

If the LRU possibly contain active buffers, it is the responsibility
of the shrink callback to check for this (ie. [`dma_resv_test_signaled()`](/kernel/hardware/driver-api/io-and-dma/dma-buf.md#c-dma_resv_test_signaled))
or if necessary block until the buffer becomes idle.

#### <a id="c-drm_gem_evict_locked"></a>`drm_gem_evict_locked()`

```c
int drm_gem_evict_locked(struct drm_gem_object *obj)
```

helper to evict backing pages for a GEM object

**Parameters**

- `struct drm_gem_object *obj`: obj in question


<a id="rst-gem-dma-helper-functions-reference"></a>

### GEM DMA Helper Functions Reference


The DRM GEM/DMA helpers are a means to provide buffer objects that are
presented to the device as a contiguous chunk of memory. This is useful
for devices that do not support scatter-gather DMA (either directly or
by using an intimately attached IOMMU).

For devices that access the memory bus through an (external) IOMMU then
the buffer objects are allocated using a traditional page-based
allocator and may be scattered through physical memory. However they
are contiguous in the IOVA space so appear contiguous to devices using
them.

For other devices then the helpers rely on CMA to provide buffer
objects that are physically contiguous in memory.

For GEM callback helpers in struct [`drm_gem_object`](#c-struct-drm_gem_object) functions, see likewise
named functions with an _object_ infix (e.g., `drm_gem_dma_object_vmap()` wraps
[`drm_gem_dma_vmap()`](#c-drm_gem_dma_vmap)). These helpers perform the necessary type conversion.



#### <a id="c-struct-drm_gem_dma_object"></a>`struct drm_gem_dma_object`

GEM object backed by DMA memory allocations

**Definition**

```c
struct drm_gem_dma_object {
    struct drm_gem_object base;
    dma_addr_t dma_addr;
    struct sg_table *sgt;
    void *vaddr;
    bool map_noncoherent;
};
```

**Members**

- `base`: base GEM object
- `dma_addr`: DMA address of the backing memory
- `sgt`: scatter/gather table for imported PRIME buffers. The table can have
  more than one entry but they are guaranteed to have contiguous
  DMA addresses.
- `vaddr`: kernel virtual address of the backing memory
- `map_noncoherent`: if true, the GEM object is backed by non-coherent memory

#### <a id="c-drm_gem_dma_object_free"></a>`drm_gem_dma_object_free()`

```c
void drm_gem_dma_object_free(struct drm_gem_object *obj)
```

GEM object function for [`drm_gem_dma_free()`](#c-drm_gem_dma_free)

**Parameters**

- `struct drm_gem_object *obj`: GEM object to free

**Description**

This function wraps `drm_gem_dma_free_object()`. Drivers that employ the DMA helpers
should use it as their [`drm_gem_object_funcs.free`](#c-struct-drm_gem_object_funcs) handler.

#### <a id="c-drm_gem_dma_object_print_info"></a>`drm_gem_dma_object_print_info()`

```c
void drm_gem_dma_object_print_info(struct drm_printer *p, unsigned int indent, const struct drm_gem_object *obj)
```

Print [`drm_gem_dma_object`](#c-struct-drm_gem_dma_object) info for debugfs

**Parameters**

- `struct drm_printer *p`: DRM printer
- `unsigned int indent`: Tab indentation level
- `const struct drm_gem_object *obj`: GEM object

**Description**

This function wraps [`drm_gem_dma_print_info()`](#c-drm_gem_dma_print_info). Drivers that employ the DMA helpers
should use this function as their [`drm_gem_object_funcs.print_info`](#c-struct-drm_gem_object_funcs) handler.

#### <a id="c-drm_gem_dma_object_get_sg_table"></a>`drm_gem_dma_object_get_sg_table()`

```c
struct sg_table * drm_gem_dma_object_get_sg_table(struct drm_gem_object *obj)
```

GEM object function for [`drm_gem_dma_get_sg_table()`](#c-drm_gem_dma_get_sg_table)

**Parameters**

- `struct drm_gem_object *obj`: GEM object

**Description**

This function wraps [`drm_gem_dma_get_sg_table()`](#c-drm_gem_dma_get_sg_table). Drivers that employ the DMA helpers should
use it as their [`drm_gem_object_funcs.get_sg_table`](#c-struct-drm_gem_object_funcs) handler.

**Return**

A pointer to the scatter/gather table of pinned pages or NULL on failure.

#### <a id="c-drm_gem_dma_object_mmap"></a>`drm_gem_dma_object_mmap()`

```c
int drm_gem_dma_object_mmap(struct drm_gem_object *obj, struct vm_area_struct *vma)
```

GEM object function for [`drm_gem_dma_mmap()`](#c-drm_gem_dma_mmap)

**Parameters**

- `struct drm_gem_object *obj`: GEM object
- `struct vm_area_struct *vma`: VMA for the area to be mapped

**Description**

This function wraps [`drm_gem_dma_mmap()`](#c-drm_gem_dma_mmap). Drivers that employ the dma helpers should
use it as their [`drm_gem_object_funcs.mmap`](#c-struct-drm_gem_object_funcs) handler.

**Return**

0 on success or a negative error code on failure.

#### <a id="c-DRM_GEM_DMA_DRIVER_OPS_WITH_DUMB_CREATE"></a>`DRM_GEM_DMA_DRIVER_OPS_WITH_DUMB_CREATE()`

```c
DRM_GEM_DMA_DRIVER_OPS_WITH_DUMB_CREATE(dumb_create_func)
```

DMA GEM driver operations

**Parameters**

- `dumb_create_func`: callback function for .dumb_create

**Description**

This macro provides a shortcut for setting the default GEM operations in the
[`drm_driver`](/kernel/hardware/gpu/drm-internals.md#c-struct-drm_driver) structure.

This macro is a variant of DRM_GEM_DMA_DRIVER_OPS for drivers that
override the default implementation of `struct rm_driver`.dumb_create. Use
DRM_GEM_DMA_DRIVER_OPS if possible. Drivers that require a virtual address
on imported buffers should use
[`DRM_GEM_DMA_DRIVER_OPS_VMAP_WITH_DUMB_CREATE()`](#c-DRM_GEM_DMA_DRIVER_OPS_VMAP_WITH_DUMB_CREATE) instead.

#### <a id="c-DRM_GEM_DMA_DRIVER_OPS"></a>`DRM_GEM_DMA_DRIVER_OPS`

```c
DRM_GEM_DMA_DRIVER_OPS
```

DMA GEM driver operations

**Description**

This macro provides a shortcut for setting the default GEM operations in the
[`drm_driver`](/kernel/hardware/gpu/drm-internals.md#c-struct-drm_driver) structure.

Drivers that come with their own implementation of
[`struct drm_driver`](/kernel/hardware/gpu/drm-internals.md#c-struct-drm_driver).dumb_create should use
[`DRM_GEM_DMA_DRIVER_OPS_WITH_DUMB_CREATE()`](#c-DRM_GEM_DMA_DRIVER_OPS_WITH_DUMB_CREATE) instead. Use
DRM_GEM_DMA_DRIVER_OPS if possible. Drivers that require a virtual address
on imported buffers should use DRM_GEM_DMA_DRIVER_OPS_VMAP instead.

#### <a id="c-DRM_GEM_DMA_DRIVER_OPS_VMAP_WITH_DUMB_CREATE"></a>`DRM_GEM_DMA_DRIVER_OPS_VMAP_WITH_DUMB_CREATE()`

```c
DRM_GEM_DMA_DRIVER_OPS_VMAP_WITH_DUMB_CREATE(dumb_create_func)
```

DMA GEM driver operations ensuring a virtual address on the buffer

**Parameters**

- `dumb_create_func`: callback function for .dumb_create

**Description**

This macro provides a shortcut for setting the default GEM operations in the
[`drm_driver`](/kernel/hardware/gpu/drm-internals.md#c-struct-drm_driver) structure for drivers that need the virtual address also on
imported buffers.

This macro is a variant of DRM_GEM_DMA_DRIVER_OPS_VMAP for drivers that
override the default implementation of [`struct drm_driver`](/kernel/hardware/gpu/drm-internals.md#c-struct-drm_driver).dumb_create. Use
DRM_GEM_DMA_DRIVER_OPS_VMAP if possible. Drivers that do not require a
virtual address on imported buffers should use
[`DRM_GEM_DMA_DRIVER_OPS_WITH_DUMB_CREATE()`](#c-DRM_GEM_DMA_DRIVER_OPS_WITH_DUMB_CREATE) instead.

#### <a id="c-DRM_GEM_DMA_DRIVER_OPS_VMAP"></a>`DRM_GEM_DMA_DRIVER_OPS_VMAP`

```c
DRM_GEM_DMA_DRIVER_OPS_VMAP
```

DMA GEM driver operations ensuring a virtual address on the buffer

**Description**

This macro provides a shortcut for setting the default GEM operations in the
[`drm_driver`](/kernel/hardware/gpu/drm-internals.md#c-struct-drm_driver) structure for drivers that need the virtual address also on
imported buffers.

Drivers that come with their own implementation of
[`struct drm_driver`](/kernel/hardware/gpu/drm-internals.md#c-struct-drm_driver).dumb_create should use
[`DRM_GEM_DMA_DRIVER_OPS_VMAP_WITH_DUMB_CREATE()`](#c-DRM_GEM_DMA_DRIVER_OPS_VMAP_WITH_DUMB_CREATE) instead. Use
DRM_GEM_DMA_DRIVER_OPS_VMAP if possible. Drivers that do not require a
virtual address on imported buffers should use DRM_GEM_DMA_DRIVER_OPS
instead.

#### <a id="c-DEFINE_DRM_GEM_DMA_FOPS"></a>`DEFINE_DRM_GEM_DMA_FOPS()`

```c
DEFINE_DRM_GEM_DMA_FOPS(name)
```

macro to generate file operations for DMA drivers

**Parameters**

- `name`: name for the generated structure

**Description**

This macro autogenerates a suitable `struct file_operations` for DMA based
drivers, which can be assigned to [`drm_driver.fops`](/kernel/hardware/gpu/drm-internals.md#c-struct-drm_driver). Note that this structure
cannot be shared between drivers, because it contains a reference to the
current module using THIS_MODULE.

Note that the declaration is already marked as static - if you need a
non-static version of this you're probably doing it wrong and will break the
THIS_MODULE reference by accident.



#### <a id="c-drm_gem_dma_create"></a>`drm_gem_dma_create()`

```c
struct drm_gem_dma_object * drm_gem_dma_create(struct drm_device *drm, size_t size)
```

allocate an object with the given size

**Parameters**

- `struct drm_device *drm`: DRM device
- `size_t size`: size of the object to allocate

**Description**

This function creates a DMA GEM object and allocates memory as backing store.
The allocated memory will occupy a contiguous chunk of bus address space.

For devices that are directly connected to the memory bus then the allocated
memory will be physically contiguous. For devices that access through an
IOMMU, then the allocated memory is not expected to be physically contiguous
because having contiguous IOVAs is sufficient to meet a devices DMA
requirements.

**Return**

A struct drm_gem_dma_object * on success or an [`ERR_PTR()`](/kernel/internals/core-api/kernel-api.md#c-ERR_PTR)-encoded negative
error code on failure.

#### <a id="c-drm_gem_dma_free"></a>`drm_gem_dma_free()`

```c
void drm_gem_dma_free(struct drm_gem_dma_object *dma_obj)
```

free resources associated with a DMA GEM object

**Parameters**

- `struct drm_gem_dma_object *dma_obj`: DMA GEM object to free

**Description**

This function frees the backing memory of the DMA GEM object, cleans up the
GEM object state and frees the memory used to store the object itself.
If the buffer is imported and the virtual address is set, it is released.

#### <a id="c-drm_gem_dma_dumb_create_internal"></a>`drm_gem_dma_dumb_create_internal()`

```c
int drm_gem_dma_dumb_create_internal(struct drm_file *file_priv, struct drm_device *drm, struct drm_mode_create_dumb *args)
```

create a dumb buffer object

**Parameters**

- `struct drm_file *file_priv`: DRM file-private structure to create the dumb buffer for
- `struct drm_device *drm`: DRM device
- `struct drm_mode_create_dumb *args`: IOCTL data

**Description**

This aligns the pitch and size arguments to the minimum required. This is
an internal helper that can be wrapped by a driver to account for hardware
with more specific alignment requirements. It should not be used directly
as their [`drm_driver.dumb_create`](/kernel/hardware/gpu/drm-internals.md#c-struct-drm_driver) callback.

**Return**

0 on success or a negative error code on failure.

#### <a id="c-drm_gem_dma_dumb_create"></a>`drm_gem_dma_dumb_create()`

```c
int drm_gem_dma_dumb_create(struct drm_file *file_priv, struct drm_device *drm, struct drm_mode_create_dumb *args)
```

create a dumb buffer object

**Parameters**

- `struct drm_file *file_priv`: DRM file-private structure to create the dumb buffer for
- `struct drm_device *drm`: DRM device
- `struct drm_mode_create_dumb *args`: IOCTL data

**Description**

This function computes the pitch of the dumb buffer and rounds it up to an
integer number of bytes per pixel. Drivers for hardware that doesn't have
any additional restrictions on the pitch can directly use this function as
their [`drm_driver.dumb_create`](/kernel/hardware/gpu/drm-internals.md#c-struct-drm_driver) callback.

For hardware with additional restrictions, drivers can adjust the fields
set up by userspace and pass the IOCTL data along to the
[`drm_gem_dma_dumb_create_internal()`](#c-drm_gem_dma_dumb_create_internal) function.

**Return**

0 on success or a negative error code on failure.

#### <a id="c-drm_gem_dma_get_unmapped_area"></a>`drm_gem_dma_get_unmapped_area()`

```c
unsigned long drm_gem_dma_get_unmapped_area(struct file *filp, unsigned long addr, unsigned long len, unsigned long pgoff, unsigned long flags)
```

propose address for mapping in noMMU cases

**Parameters**

- `struct file *filp`: file object
- `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 direct handler for the struct
`file_operations.get_unmapped_area` operation.

**Return**

mapping address on success or a negative error code on failure.

#### <a id="c-drm_gem_dma_print_info"></a>`drm_gem_dma_print_info()`

```c
void drm_gem_dma_print_info(const struct drm_gem_dma_object *dma_obj, struct drm_printer *p, unsigned int indent)
```

Print [`drm_gem_dma_object`](#c-struct-drm_gem_dma_object) info for debugfs

**Parameters**

- `const struct drm_gem_dma_object *dma_obj`: DMA GEM object
- `struct drm_printer *p`: DRM printer
- `unsigned int indent`: Tab indentation level

**Description**

This function prints dma_addr and vaddr for use in e.g. debugfs output.

#### <a id="c-drm_gem_dma_get_sg_table"></a>`drm_gem_dma_get_sg_table()`

```c
struct sg_table * drm_gem_dma_get_sg_table(struct drm_gem_dma_object *dma_obj)
```

provide a scatter/gather table of pinned pages for a DMA GEM object

**Parameters**

- `struct drm_gem_dma_object *dma_obj`: DMA GEM object

**Description**

This function exports a scatter/gather table by calling the standard
DMA mapping API.

**Return**

A pointer to the scatter/gather table of pinned pages or NULL on failure.

#### <a id="c-drm_gem_dma_prime_import_sg_table"></a>`drm_gem_dma_prime_import_sg_table()`

```c
struct drm_gem_object * drm_gem_dma_prime_import_sg_table(struct drm_device *dev, struct dma_buf_attachment *attach, struct sg_table *sgt)
```

produce a DMA GEM object from another driver's scatter/gather table of pinned pages

**Parameters**

- `struct drm_device *dev`: device to import into
- `struct dma_buf_attachment *attach`: DMA-BUF attachment
- `struct sg_table *sgt`: scatter/gather table of pinned pages

**Description**

This function imports a scatter/gather table exported via DMA-BUF by
another driver. Imported buffers must be physically contiguous in memory
(i.e. the scatter/gather table must contain a single entry). Drivers that
use the DMA helpers should set this as their
[`drm_driver.gem_prime_import_sg_table`](/kernel/hardware/gpu/drm-internals.md#c-struct-drm_driver) callback.

**Return**

A pointer to a newly created GEM object or an ERR_PTR-encoded negative
error code on failure.

#### <a id="c-drm_gem_dma_vmap"></a>`drm_gem_dma_vmap()`

```c
int drm_gem_dma_vmap(struct drm_gem_dma_object *dma_obj, struct iosys_map *map)
```

map a DMA GEM object into the kernel's virtual address space

**Parameters**

- `struct drm_gem_dma_object *dma_obj`: DMA GEM object
- `struct iosys_map *map`: Returns the kernel virtual address of the DMA GEM object's backing
  store.

**Description**

This function maps a buffer into the kernel's virtual address space.
Since the DMA buffers are already mapped into the kernel virtual address
space this simply returns the cached virtual address.

**Return**

0 on success, or a negative error code otherwise.

#### <a id="c-drm_gem_dma_mmap"></a>`drm_gem_dma_mmap()`

```c
int drm_gem_dma_mmap(struct drm_gem_dma_object *dma_obj, struct vm_area_struct *vma)
```

memory-map an exported DMA GEM object

**Parameters**

- `struct drm_gem_dma_object *dma_obj`: DMA GEM object
- `struct vm_area_struct *vma`: VMA for the area to be mapped

**Description**

This function maps a buffer into a userspace process's address space.
In addition to the usual GEM VMA setup it immediately faults in the entire
object instead of using on-demand faulting.

**Return**

0 on success or a negative error code on failure.

#### <a id="c-drm_gem_dma_prime_import_sg_table_vmap"></a>`drm_gem_dma_prime_import_sg_table_vmap()`

```c
struct drm_gem_object * drm_gem_dma_prime_import_sg_table_vmap(struct drm_device *dev, struct dma_buf_attachment *attach, struct sg_table *sgt)
```

PRIME import another driver's scatter/gather table and get the virtual address of the buffer

**Parameters**

- `struct drm_device *dev`: DRM device
- `struct dma_buf_attachment *attach`: DMA-BUF attachment
- `struct sg_table *sgt`: Scatter/gather table of pinned pages

**Description**

This function imports a scatter/gather table using
[`drm_gem_dma_prime_import_sg_table()`](#c-drm_gem_dma_prime_import_sg_table) and uses [`dma_buf_vmap()`](/kernel/hardware/driver-api/io-and-dma/dma-buf.md#c-dma_buf_vmap) to get the kernel
virtual address. This ensures that a DMA GEM object always has its virtual
address set. This address is released when the object is freed.

This function can be used as the [`drm_driver.gem_prime_import_sg_table`](/kernel/hardware/gpu/drm-internals.md#c-struct-drm_driver)
callback. The [`DRM_GEM_DMA_DRIVER_OPS_VMAP`](#c-DRM_GEM_DMA_DRIVER_OPS_VMAP) macro provides a shortcut to set
the necessary DRM driver operations.

**Return**

A pointer to a newly created GEM object or an ERR_PTR-encoded negative
error code on failure.


<a id="rst-gem-shmem-helper-function-reference"></a>

### GEM SHMEM Helper Function Reference


This library provides helpers for GEM objects backed by shmem buffers
allocated using anonymous pageable memory.

Functions that operate on the GEM object receive struct [`drm_gem_shmem_object`](#c-struct-drm_gem_shmem_object).
For GEM callback helpers in struct [`drm_gem_object`](#c-struct-drm_gem_object) functions, see likewise
named functions with an _object_ infix (e.g., `drm_gem_shmem_object_vmap()` wraps
`drm_gem_shmem_vmap()`). These helpers perform the necessary type conversion.



#### <a id="c-struct-drm_gem_shmem_object"></a>`struct drm_gem_shmem_object`

GEM object backed by shmem

**Definition**

```c
struct drm_gem_shmem_object {
    struct drm_gem_object base;
    struct page **pages;
    refcount_t pages_use_count;
    refcount_t pages_pin_count;
    int madv;
    struct list_head madv_list;
    struct sg_table *sgt;
    void *vaddr;
    refcount_t vmap_use_count;
    bool pages_mark_dirty_on_put : 1;
    bool pages_mark_accessed_on_put : 1;
    bool map_wc : 1;
};
```

**Members**

- `base`: Base GEM object
- `pages`: Page table
- `pages_use_count`: Reference count on the pages table.
  The pages are put when the count reaches zero.
- `pages_pin_count`: Reference count on the pinned pages table.

  Pages are hard-pinned and reside in memory if count
  greater than zero. Otherwise, when count is zero, the pages are
  allowed to be evicted and purged by memory shrinker.
- `madv`: State for madvise

  0 is active/inuse.
  A negative value is the object is purged.
  Positive values are driver specific and not used by the helpers.
- `madv_list`: List entry for madvise tracking

  Typically used by drivers to track purgeable objects
- `sgt`: Scatter/gather table for imported PRIME buffers
- `vaddr`: Kernel virtual address of the backing memory
- `vmap_use_count`: Reference count on the virtual address.
  The address are un-mapped when the count reaches zero.
- `pages_mark_dirty_on_put`: Mark pages as dirty when they are put.
- `pages_mark_accessed_on_put`: Mark pages as accessed when they are put.
- `map_wc`: map object write-combined (instead of using shmem defaults).

#### <a id="c-drm_gem_shmem_object_free"></a>`drm_gem_shmem_object_free()`

```c
void drm_gem_shmem_object_free(struct drm_gem_object *obj)
```

GEM object function for [`drm_gem_shmem_free()`](#c-drm_gem_shmem_free)

**Parameters**

- `struct drm_gem_object *obj`: GEM object to free

**Description**

This function wraps [`drm_gem_shmem_free()`](#c-drm_gem_shmem_free). Drivers that employ the shmem helpers
should use it as their [`drm_gem_object_funcs.free`](#c-struct-drm_gem_object_funcs) handler.

#### <a id="c-drm_gem_shmem_object_print_info"></a>`drm_gem_shmem_object_print_info()`

```c
void drm_gem_shmem_object_print_info(struct drm_printer *p, unsigned int indent, const struct drm_gem_object *obj)
```

Print [`drm_gem_shmem_object`](#c-struct-drm_gem_shmem_object) info for debugfs

**Parameters**

- `struct drm_printer *p`: DRM printer
- `unsigned int indent`: Tab indentation level
- `const struct drm_gem_object *obj`: GEM object

**Description**

This function wraps [`drm_gem_shmem_print_info()`](#c-drm_gem_shmem_print_info). Drivers that employ the shmem helpers should
use this function as their [`drm_gem_object_funcs.print_info`](#c-struct-drm_gem_object_funcs) handler.

#### <a id="c-drm_gem_shmem_object_pin"></a>`drm_gem_shmem_object_pin()`

```c
int drm_gem_shmem_object_pin(struct drm_gem_object *obj)
```

GEM object function for [`drm_gem_shmem_pin()`](#c-drm_gem_shmem_pin)

**Parameters**

- `struct drm_gem_object *obj`: GEM object

**Description**

This function wraps [`drm_gem_shmem_pin()`](#c-drm_gem_shmem_pin). Drivers that employ the shmem helpers should
use it as their [`drm_gem_object_funcs.pin`](#c-struct-drm_gem_object_funcs) handler.

#### <a id="c-drm_gem_shmem_object_unpin"></a>`drm_gem_shmem_object_unpin()`

```c
void drm_gem_shmem_object_unpin(struct drm_gem_object *obj)
```

GEM object function for [`drm_gem_shmem_unpin()`](#c-drm_gem_shmem_unpin)

**Parameters**

- `struct drm_gem_object *obj`: GEM object

**Description**

This function wraps [`drm_gem_shmem_unpin()`](#c-drm_gem_shmem_unpin). Drivers that employ the shmem helpers should
use it as their [`drm_gem_object_funcs.unpin`](#c-struct-drm_gem_object_funcs) handler.

#### <a id="c-drm_gem_shmem_object_get_sg_table"></a>`drm_gem_shmem_object_get_sg_table()`

```c
struct sg_table * drm_gem_shmem_object_get_sg_table(struct drm_gem_object *obj)
```

GEM object function for [`drm_gem_shmem_get_sg_table()`](#c-drm_gem_shmem_get_sg_table)

**Parameters**

- `struct drm_gem_object *obj`: GEM object

**Description**

This function wraps [`drm_gem_shmem_get_sg_table()`](#c-drm_gem_shmem_get_sg_table). Drivers that employ the shmem helpers should
use it as their [`drm_gem_object_funcs.get_sg_table`](#c-struct-drm_gem_object_funcs) handler.

**Return**

A pointer to the scatter/gather table of pinned pages or error pointer on failure.

#### <a id="c-drm_gem_shmem_object_mmap"></a>`drm_gem_shmem_object_mmap()`

```c
int drm_gem_shmem_object_mmap(struct drm_gem_object *obj, struct vm_area_struct *vma)
```

GEM object function for [`drm_gem_shmem_mmap()`](#c-drm_gem_shmem_mmap)

**Parameters**

- `struct drm_gem_object *obj`: GEM object
- `struct vm_area_struct *vma`: VMA for the area to be mapped

**Description**

This function wraps [`drm_gem_shmem_mmap()`](#c-drm_gem_shmem_mmap). Drivers that employ the shmem helpers should
use it as their [`drm_gem_object_funcs.mmap`](#c-struct-drm_gem_object_funcs) handler.

**Return**

0 on success or a negative error code on failure.

#### <a id="c-DRM_GEM_SHMEM_DRIVER_OPS"></a>`DRM_GEM_SHMEM_DRIVER_OPS`

```c
DRM_GEM_SHMEM_DRIVER_OPS
```

Default shmem GEM operations

**Description**

This macro provides a shortcut for setting the shmem GEM operations
in the [`drm_driver`](/kernel/hardware/gpu/drm-internals.md#c-struct-drm_driver) structure. Drivers that do not require an s/g table
for imported buffers should use this.



#### <a id="c-drm_gem_shmem_init"></a>`drm_gem_shmem_init()`

```c
int drm_gem_shmem_init(struct drm_device *dev, struct drm_gem_shmem_object *shmem, size_t size)
```

Initialize an allocated object.

**Parameters**

- `struct drm_device *dev`: DRM device
- `struct drm_gem_shmem_object *shmem`: shmem GEM object to initialize
- `size_t size`: Buffer size in bytes

**Description**

This function initializes an allocated shmem GEM object.

**Return**

0 on success, or a negative error code on failure.

#### <a id="c-drm_gem_shmem_create"></a>`drm_gem_shmem_create()`

```c
struct drm_gem_shmem_object * drm_gem_shmem_create(struct drm_device *dev, size_t size)
```

Allocate an object with the given size

**Parameters**

- `struct drm_device *dev`: DRM device
- `size_t size`: Size of the object to allocate

**Description**

This function creates a shmem GEM object.

**Return**

A struct drm_gem_shmem_object * on success or an [`ERR_PTR()`](/kernel/internals/core-api/kernel-api.md#c-ERR_PTR)-encoded negative
error code on failure.

#### <a id="c-drm_gem_shmem_release"></a>`drm_gem_shmem_release()`

```c
void drm_gem_shmem_release(struct drm_gem_shmem_object *shmem)
```

Release resources associated with a shmem GEM object.

**Parameters**

- `struct drm_gem_shmem_object *shmem`: shmem GEM object

**Description**

This function cleans up the GEM object state, but does not free the memory used to store the
object itself. This function is meant to be a dedicated helper for the Rust GEM bindings.

#### <a id="c-drm_gem_shmem_free"></a>`drm_gem_shmem_free()`

```c
void drm_gem_shmem_free(struct drm_gem_shmem_object *shmem)
```

Free resources associated with a shmem GEM object

**Parameters**

- `struct drm_gem_shmem_object *shmem`: shmem GEM object to free

**Description**

This function cleans up the GEM object state and frees the memory used to
store the object itself.

#### <a id="c-drm_gem_shmem_pin"></a>`drm_gem_shmem_pin()`

```c
int drm_gem_shmem_pin(struct drm_gem_shmem_object *shmem)
```

Pin backing pages for a shmem GEM object

**Parameters**

- `struct drm_gem_shmem_object *shmem`: shmem GEM object

**Description**

This function makes sure the backing pages are pinned in memory while the
buffer is exported.

**Return**

0 on success or a negative error code on failure.

#### <a id="c-drm_gem_shmem_unpin"></a>`drm_gem_shmem_unpin()`

```c
void drm_gem_shmem_unpin(struct drm_gem_shmem_object *shmem)
```

Unpin backing pages for a shmem GEM object

**Parameters**

- `struct drm_gem_shmem_object *shmem`: shmem GEM object

**Description**

This function removes the requirement that the backing pages are pinned in
memory.

#### <a id="c-drm_gem_shmem_dumb_create"></a>`drm_gem_shmem_dumb_create()`

```c
int drm_gem_shmem_dumb_create(struct drm_file *file, struct drm_device *dev, struct drm_mode_create_dumb *args)
```

Create a dumb shmem buffer object

**Parameters**

- `struct drm_file *file`: DRM file structure to create the dumb buffer for
- `struct drm_device *dev`: DRM device
- `struct drm_mode_create_dumb *args`: IOCTL data

**Description**

This function computes the pitch of the dumb buffer and rounds it up to an
integer number of bytes per pixel. Drivers for hardware that doesn't have
any additional restrictions on the pitch can directly use this function as
their [`drm_driver.dumb_create`](/kernel/hardware/gpu/drm-internals.md#c-struct-drm_driver) callback.

For hardware with additional restrictions, drivers can adjust the fields
set up by userspace before calling into this function.

**Return**

0 on success or a negative error code on failure.

#### <a id="c-drm_gem_shmem_mmap"></a>`drm_gem_shmem_mmap()`

```c
int drm_gem_shmem_mmap(struct drm_gem_shmem_object *shmem, struct vm_area_struct *vma)
```

Memory-map a shmem GEM object

**Parameters**

- `struct drm_gem_shmem_object *shmem`: shmem GEM object
- `struct vm_area_struct *vma`: VMA for the area to be mapped

**Description**

This function implements an augmented version of the GEM DRM file mmap
operation for shmem objects.

**Return**

0 on success or a negative error code on failure.

#### <a id="c-drm_gem_shmem_print_info"></a>`drm_gem_shmem_print_info()`

```c
void drm_gem_shmem_print_info(const struct drm_gem_shmem_object *shmem, struct drm_printer *p, unsigned int indent)
```

Print [`drm_gem_shmem_object`](#c-struct-drm_gem_shmem_object) info for debugfs

**Parameters**

- `const struct drm_gem_shmem_object *shmem`: shmem GEM object
- `struct drm_printer *p`: DRM printer
- `unsigned int indent`: Tab indentation level

#### <a id="c-drm_gem_shmem_get_sg_table"></a>`drm_gem_shmem_get_sg_table()`

```c
struct sg_table * drm_gem_shmem_get_sg_table(struct drm_gem_shmem_object *shmem)
```

Provide a scatter/gather table of pinned pages for a shmem GEM object

**Parameters**

- `struct drm_gem_shmem_object *shmem`: shmem GEM object

**Description**

This function exports a scatter/gather table suitable for PRIME usage by
calling the standard DMA mapping API.

Drivers who need to acquire an scatter/gather table for objects need to call
[`drm_gem_shmem_get_pages_sgt()`](#c-drm_gem_shmem_get_pages_sgt) instead.

**Return**

A pointer to the scatter/gather table of pinned pages or error pointer on failure.

#### <a id="c-drm_gem_shmem_get_pages_sgt"></a>`drm_gem_shmem_get_pages_sgt()`

```c
struct sg_table * drm_gem_shmem_get_pages_sgt(struct drm_gem_shmem_object *shmem)
```

Pin pages, dma map them, and return a scatter/gather table for a shmem GEM object.

**Parameters**

- `struct drm_gem_shmem_object *shmem`: shmem GEM object

**Description**

This function returns a scatter/gather table suitable for driver usage. If
the sg table doesn't exist, the pages are pinned, dma-mapped, and a sg
table created.

This is the main function for drivers to get at backing storage, and it hides
and difference between dma-buf imported and natively allocated objects.
[`drm_gem_shmem_get_sg_table()`](#c-drm_gem_shmem_get_sg_table) should not be directly called by drivers.

**Return**

A pointer to the scatter/gather table of pinned pages or errno on failure.

#### <a id="c-drm_gem_shmem_prime_import_sg_table"></a>`drm_gem_shmem_prime_import_sg_table()`

```c
struct drm_gem_object * drm_gem_shmem_prime_import_sg_table(struct drm_device *dev, struct dma_buf_attachment *attach, struct sg_table *sgt)
```

Produce a shmem GEM object from another driver's scatter/gather table of pinned pages

**Parameters**

- `struct drm_device *dev`: Device to import into
- `struct dma_buf_attachment *attach`: DMA-BUF attachment
- `struct sg_table *sgt`: Scatter/gather table of pinned pages

**Description**

This function imports a scatter/gather table exported via DMA-BUF by
another driver. Drivers that use the shmem helpers should set this as their
[`drm_driver.gem_prime_import_sg_table`](/kernel/hardware/gpu/drm-internals.md#c-struct-drm_driver) callback.

**Return**

A pointer to a newly created GEM object or an ERR_PTR-encoded negative
error code on failure.

#### <a id="c-drm_gem_shmem_prime_import_no_map"></a>`drm_gem_shmem_prime_import_no_map()`

```c
struct drm_gem_object * drm_gem_shmem_prime_import_no_map(struct drm_device *dev, struct dma_buf *dma_buf)
```

Import dmabuf without mapping its sg_table

**Parameters**

- `struct drm_device *dev`: Device to import into
- `struct dma_buf *dma_buf`: dma-buf object to import

**Description**

Drivers that use the shmem helpers but also wants to import dmabuf without
mapping its sg_table can use this as their [`drm_driver.gem_prime_import`](/kernel/hardware/gpu/drm-internals.md#c-struct-drm_driver)
implementation.


<a id="rst-gem-vram-helper-functions-reference"></a>

### GEM VRAM Helper Functions Reference


This library provides [`struct drm_gem_vram_object`](#c-struct-drm_gem_vram_object) (GEM VRAM), a GEM
buffer object that is backed by video RAM (VRAM). It can be used for
framebuffer devices with dedicated memory.

The data structure [`struct drm_vram_mm`](#c-struct-drm_vram_mm) and its helpers implement a memory
manager for simple framebuffer devices with dedicated video memory. GEM
VRAM buffer objects are either placed in the video memory or remain evicted
to system memory.

With the GEM interface userspace applications create, manage and destroy
graphics buffers, such as an on-screen framebuffer. GEM does not provide
an implementation of these interfaces. It's up to the DRM driver to
provide an implementation that suits the hardware. If the hardware device
contains dedicated video memory, the DRM driver can use the VRAM helper
library. Each active buffer object is stored in video RAM. Active
buffer are used for drawing the current frame, typically something like
the frame's scanout buffer or the cursor image. If there's no more space
left in VRAM, inactive GEM objects can be moved to system memory.

To initialize the VRAM helper library call [`drmm_vram_helper_init()`](#c-drmm_vram_helper_init).
The function allocates and initializes an instance of [`struct drm_vram_mm`](#c-struct-drm_vram_mm)
in [`struct drm_device`](/kernel/hardware/gpu/drm-internals.md#c-struct-drm_device).vram_mm . Use [`DRM_GEM_VRAM_DRIVER`](#c-DRM_GEM_VRAM_DRIVER) to initialize
[`struct drm_driver`](/kernel/hardware/gpu/drm-internals.md#c-struct-drm_driver) and  `DRM_VRAM_MM_FILE_OPERATIONS` to initialize
`struct file_operations`; as illustrated below.

```c
struct file_operations fops ={
        .owner = THIS_MODULE,
        DRM_VRAM_MM_FILE_OPERATION
};
struct drm_driver drv = {
        .driver_feature = DRM_ ... ,
        .fops = &fops,
        DRM_GEM_VRAM_DRIVER
};

int init_drm_driver()
{
        struct drm_device *dev;
        uint64_t vram_base;
        unsigned long vram_size;
        int ret;

        // setup device, vram base and size
        // ...

        ret = drmm_vram_helper_init(dev, vram_base, vram_size);
        if (ret)
                return ret;
        return 0;
}
```

This creates an instance of [`struct drm_vram_mm`](#c-struct-drm_vram_mm), exports DRM userspace
interfaces for GEM buffer management and initializes file operations to
allow for accessing created GEM buffers. With this setup, the DRM driver
manages an area of video RAM with VRAM MM and provides GEM VRAM objects
to userspace.

You don't have to clean up the instance of VRAM MM.
[`drmm_vram_helper_init()`](#c-drmm_vram_helper_init) is a managed interface that installs a
clean-up handler to run during the DRM device's release.

A buffer object that is pinned in video RAM has a fixed address within that
memory region. Call [`drm_gem_vram_offset()`](#c-drm_gem_vram_offset) to retrieve this value. Typically
it's used to program the hardware's scanout engine for framebuffers, set
the cursor overlay's image for a mouse cursor, or use it as input to the
hardware's drawing engine.

To access a buffer object's memory from the DRM driver, call
[`drm_gem_vram_vmap()`](#c-drm_gem_vram_vmap). It maps the buffer into kernel address
space and returns the memory address. Use [`drm_gem_vram_vunmap()`](#c-drm_gem_vram_vunmap) to
release the mapping.



#### <a id="c-struct-drm_gem_vram_object"></a>`struct drm_gem_vram_object`

GEM object backed by VRAM

**Definition**

```c
struct drm_gem_vram_object {
    struct ttm_buffer_object bo;
    struct iosys_map map;
    unsigned int vmap_use_count;
    struct ttm_placement placement;
    struct ttm_place placements[2];
};
```

**Members**

- `bo`: TTM buffer object
- `map`: Mapping information for **bo**
- `vmap_use_count`: Reference count on the virtual address.
  The address are un-mapped when the count reaches zero.
- `placement`: TTM placement information. Supported placements are `TTM_PL_VRAM`
  and `TTM_PL_SYSTEM`
- `placements`: TTM placement information.

**Description**

The type struct drm_gem_vram_object represents a GEM object that is
backed by VRAM. It can be used for simple framebuffer devices with
dedicated memory. The buffer object can be evicted to system memory if
video memory becomes scarce.

GEM VRAM objects perform reference counting for pin and mapping
operations. So a buffer object that has been pinned N times with
`drm_gem_vram_pin()` must be unpinned N times with
`drm_gem_vram_unpin()`. The same applies to pairs of
`drm_gem_vram_kmap()` and `drm_gem_vram_kunmap()`, as well as pairs of
[`drm_gem_vram_vmap()`](#c-drm_gem_vram_vmap) and [`drm_gem_vram_vunmap()`](#c-drm_gem_vram_vunmap).

#### <a id="c-drm_gem_vram_of_bo"></a>`drm_gem_vram_of_bo()`

```c
struct drm_gem_vram_object * drm_gem_vram_of_bo(struct ttm_buffer_object *bo)
```

Returns the container of type [`struct drm_gem_vram_object`](#c-struct-drm_gem_vram_object) for field bo.

**Parameters**

- `struct ttm_buffer_object *bo`: the VRAM buffer object

**Return**

The containing GEM VRAM object

#### <a id="c-drm_gem_vram_of_gem"></a>`drm_gem_vram_of_gem()`

```c
struct drm_gem_vram_object * drm_gem_vram_of_gem(struct drm_gem_object *gem)
```

Returns the container of type [`struct drm_gem_vram_object`](#c-struct-drm_gem_vram_object) for field gem.

**Parameters**

- `struct drm_gem_object *gem`: the GEM object

**Return**

The containing GEM VRAM object

#### <a id="c-DRM_GEM_VRAM_PLANE_HELPER_FUNCS"></a>`DRM_GEM_VRAM_PLANE_HELPER_FUNCS`

```c
DRM_GEM_VRAM_PLANE_HELPER_FUNCS
```

Initializes struct drm_plane_helper_funcs for VRAM handling

**Description**

Drivers may use GEM BOs as VRAM helpers for the framebuffer memory. This
macro initializes struct drm_plane_helper_funcs to use the respective helper
functions.

#### <a id="c-DRM_GEM_VRAM_DRIVER"></a>`DRM_GEM_VRAM_DRIVER`

```c
DRM_GEM_VRAM_DRIVER
```

default callback functions for [`struct drm_driver`](/kernel/hardware/gpu/drm-internals.md#c-struct-drm_driver)

**Description**

Drivers that use VRAM MM and GEM VRAM can use this macro to initialize
[`struct drm_driver`](/kernel/hardware/gpu/drm-internals.md#c-struct-drm_driver) with default functions.

#### <a id="c-struct-drm_vram_mm"></a>`struct drm_vram_mm`

An instance of VRAM MM

**Definition**

```c
struct drm_vram_mm {
    uint64_t vram_base;
    size_t vram_size;
    struct ttm_device bdev;
};
```

**Members**

- `vram_base`: Base address of the managed video memory
- `vram_size`: Size of the managed video memory in bytes
- `bdev`: The TTM BO device.

**Description**

The fields [`struct drm_vram_mm`](#c-struct-drm_vram_mm).vram_base and
[`struct drm_vram_mm`](#c-struct-drm_vram_mm).vrm_size are managed by VRAM MM, but are
available for public read access. Use the field
[`struct drm_vram_mm`](#c-struct-drm_vram_mm).bdev to access the TTM BO device.

#### <a id="c-drm_vram_mm_of_bdev"></a>`drm_vram_mm_of_bdev()`

```c
struct drm_vram_mm * drm_vram_mm_of_bdev(struct ttm_device *bdev)
```

Returns the container of type [`struct ttm_device`](#c-struct-ttm_device) for field bdev.

**Parameters**

- `struct ttm_device *bdev`: the TTM BO device

**Return**

The containing instance of [`struct drm_vram_mm`](#c-struct-drm_vram_mm)



#### <a id="c-drm_gem_vram_create"></a>`drm_gem_vram_create()`

```c
struct drm_gem_vram_object * drm_gem_vram_create(struct drm_device *dev, size_t size, unsigned long pg_align)
```

Creates a VRAM-backed GEM object

**Parameters**

- `struct drm_device *dev`: the DRM device
- `size_t size`: the buffer size in bytes
- `unsigned long pg_align`: the buffer's alignment in multiples of the page size

**Description**

GEM objects are allocated by calling struct drm_driver.gem_create_object,
if set. Otherwise [`kzalloc()`](/kernel/internals/core-api/mm-api.md#c-kzalloc) will be used. Drivers can set their own GEM
object functions in struct drm_driver.gem_create_object. If no functions
are set, the new GEM object will use the default functions from GEM VRAM
helpers.

**Return**

A new instance of [`struct drm_gem_vram_object`](#c-struct-drm_gem_vram_object) on success, or
an [`ERR_PTR()`](/kernel/internals/core-api/kernel-api.md#c-ERR_PTR)-encoded error code otherwise.

#### <a id="c-drm_gem_vram_put"></a>`drm_gem_vram_put()`

```c
void drm_gem_vram_put(struct drm_gem_vram_object *gbo)
```

Releases a reference to a VRAM-backed GEM object

**Parameters**

- `struct drm_gem_vram_object *gbo`: the GEM VRAM object

**Description**

See `ttm_bo_fini()` for more information.

#### <a id="c-drm_gem_vram_offset"></a>`drm_gem_vram_offset()`

```c
s64 drm_gem_vram_offset(struct drm_gem_vram_object *gbo)
```

Returns a GEM VRAM object's offset in video memory

**Parameters**

- `struct drm_gem_vram_object *gbo`: the GEM VRAM object

**Description**

This function returns the buffer object's offset in the device's video
memory. The buffer object has to be pinned to `TTM_PL_VRAM`.

**Return**

The buffer object's offset in video memory on success, or
a negative errno code otherwise.

#### <a id="c-drm_gem_vram_vmap"></a>`drm_gem_vram_vmap()`

```c
int drm_gem_vram_vmap(struct drm_gem_vram_object *gbo, struct iosys_map *map)
```

Pins and maps a GEM VRAM object into kernel address space

**Parameters**

- `struct drm_gem_vram_object *gbo`: The GEM VRAM object to map
- `struct iosys_map *map`: Returns the kernel virtual address of the VRAM GEM object's backing
  store.

**Description**

The vmap function pins a GEM VRAM object to its current location, either
system or video memory, and maps its buffer into kernel address space.
As pinned object cannot be relocated, you should avoid pinning objects
permanently. Call [`drm_gem_vram_vunmap()`](#c-drm_gem_vram_vunmap) with the returned address to
unmap and unpin the GEM VRAM object.

**Return**

0 on success, or a negative error code otherwise.

#### <a id="c-drm_gem_vram_vunmap"></a>`drm_gem_vram_vunmap()`

```c
void drm_gem_vram_vunmap(struct drm_gem_vram_object *gbo, struct iosys_map *map)
```

Unmaps and unpins a GEM VRAM object

**Parameters**

- `struct drm_gem_vram_object *gbo`: The GEM VRAM object to unmap
- `struct iosys_map *map`: Kernel virtual address where the VRAM GEM object was mapped

**Description**

A call to [`drm_gem_vram_vunmap()`](#c-drm_gem_vram_vunmap) unmaps and unpins a GEM VRAM buffer. See
the documentation for [`drm_gem_vram_vmap()`](#c-drm_gem_vram_vmap) for more information.

#### <a id="c-drm_gem_vram_fill_create_dumb"></a>`drm_gem_vram_fill_create_dumb()`

```c
int drm_gem_vram_fill_create_dumb(struct drm_file *file, struct drm_device *dev, unsigned long pg_align, unsigned long pitch_align, struct drm_mode_create_dumb *args)
```

Helper for implementing [`struct drm_driver`](/kernel/hardware/gpu/drm-internals.md#c-struct-drm_driver).dumb_create

**Parameters**

- `struct drm_file *file`: the DRM file
- `struct drm_device *dev`: the DRM device
- `unsigned long pg_align`: the buffer's alignment in multiples of the page size
- `unsigned long pitch_align`: the scanline's alignment in powers of 2
- `struct drm_mode_create_dumb *args`: the arguments as provided to
  [`struct drm_driver`](/kernel/hardware/gpu/drm-internals.md#c-struct-drm_driver).dumb_create

**Description**

This helper function fills [`struct drm_mode_create_dumb`](/kernel/hardware/gpu/drm-uapi.md#c-struct-drm_mode_create_dumb), which is used
by [`struct drm_driver`](/kernel/hardware/gpu/drm-internals.md#c-struct-drm_driver).dumb_create. Implementations of this interface
should forwards their arguments to this helper, plus the driver-specific
parameters.

**Return**

0 on success, or
a negative error code otherwise.

#### <a id="c-drm_gem_vram_driver_dumb_create"></a>`drm_gem_vram_driver_dumb_create()`

```c
int drm_gem_vram_driver_dumb_create(struct drm_file *file, struct drm_device *dev, struct drm_mode_create_dumb *args)
```

Implements [`struct drm_driver`](/kernel/hardware/gpu/drm-internals.md#c-struct-drm_driver).dumb_create

**Parameters**

- `struct drm_file *file`: the DRM file
- `struct drm_device *dev`: the DRM device
- `struct drm_mode_create_dumb *args`: the arguments as provided to
  [`struct drm_driver`](/kernel/hardware/gpu/drm-internals.md#c-struct-drm_driver).dumb_create

**Description**

This function requires the driver to use **drm_device.vram_mm** for its
instance of VRAM MM.

**Return**

0 on success, or
a negative error code otherwise.

#### <a id="c-drm_gem_vram_plane_helper_prepare_fb"></a>`drm_gem_vram_plane_helper_prepare_fb()`

```c
int drm_gem_vram_plane_helper_prepare_fb(struct drm_plane *plane, struct drm_plane_state *new_state)
```

Implements [`struct drm_plane_helper_funcs`](/kernel/hardware/gpu/drm-kms-helpers.md#c-struct-drm_plane_helper_funcs).prepare_fb

**Parameters**

- `struct drm_plane *plane`: a DRM plane
- `struct drm_plane_state *new_state`: the plane's new state

**Description**

During plane updates, this function sets the plane's fence and
pins the GEM VRAM objects of the plane's new framebuffer to VRAM.
Call [`drm_gem_vram_plane_helper_cleanup_fb()`](#c-drm_gem_vram_plane_helper_cleanup_fb) to unpin them.

**Return**

0 on success, or
a negative errno code otherwise.

#### <a id="c-drm_gem_vram_plane_helper_cleanup_fb"></a>`drm_gem_vram_plane_helper_cleanup_fb()`

```c
void drm_gem_vram_plane_helper_cleanup_fb(struct drm_plane *plane, struct drm_plane_state *old_state)
```

Implements [`struct drm_plane_helper_funcs`](/kernel/hardware/gpu/drm-kms-helpers.md#c-struct-drm_plane_helper_funcs).cleanup_fb

**Parameters**

- `struct drm_plane *plane`: a DRM plane
- `struct drm_plane_state *old_state`: the plane's old state

**Description**

During plane updates, this function unpins the GEM VRAM
objects of the plane's old framebuffer from VRAM. Complements
[`drm_gem_vram_plane_helper_prepare_fb()`](#c-drm_gem_vram_plane_helper_prepare_fb).

#### <a id="c-drm_vram_mm_debugfs_init"></a>`drm_vram_mm_debugfs_init()`

```c
void drm_vram_mm_debugfs_init(struct drm_minor *minor)
```

Register VRAM MM debugfs file.

**Parameters**

- `struct drm_minor *minor`: drm minor device.

#### <a id="c-drmm_vram_helper_init"></a>`drmm_vram_helper_init()`

```c
int drmm_vram_helper_init(struct drm_device *dev, uint64_t vram_base, size_t vram_size)
```

Initializes a device's instance of [`struct drm_vram_mm`](#c-struct-drm_vram_mm)

**Parameters**

- `struct drm_device *dev`: the DRM device
- `uint64_t vram_base`: the base address of the video memory
- `size_t vram_size`: the size of the video memory in bytes

**Description**

Creates a new instance of [`struct drm_vram_mm`](#c-struct-drm_vram_mm) and stores it in
struct [`drm_device.vram_mm`](/kernel/hardware/gpu/drm-internals.md#c-struct-drm_device). The instance is auto-managed and cleaned
up as part of device cleanup. Calling this function multiple times
will generate an error message.

**Return**

0 on success, or a negative errno code otherwise.

#### <a id="c-drm_vram_helper_mode_valid"></a>`drm_vram_helper_mode_valid()`

```c
enum drm_mode_status drm_vram_helper_mode_valid(struct drm_device *dev, const struct drm_display_mode *mode)
```

Tests if a display mode's framebuffer fits into the available video memory.

**Parameters**

- `struct drm_device *dev`: the DRM device
- `const struct drm_display_mode *mode`: the mode to test

**Description**

This function tests if enough video memory is available for using the
specified display mode. Atomic modesetting requires importing the
designated framebuffer into video memory before evicting the active
one. Hence, any framebuffer may consume at most half of the available
VRAM. Display modes that require a larger framebuffer can not be used,
even if the CRTC does support them. Each framebuffer is assumed to
have 32-bit color depth.

**Note**

The function can only test if the display mode is supported in
general. If there are too many framebuffers pinned to video memory,
a display mode may still not be usable in practice. The color depth of
32-bit fits all current use case. A more flexible test can be added
when necessary.

**Return**

MODE_OK if the display mode is supported, or an error code of type
enum drm_mode_status otherwise.


<a id="rst-gem-ttm-helper-functions-reference"></a>

### GEM TTM Helper Functions Reference


This library provides helper functions for gem objects backed by
ttm.



#### <a id="c-drm_gem_ttm_print_info"></a>`drm_gem_ttm_print_info()`

```c
void drm_gem_ttm_print_info(struct drm_printer *p, unsigned int indent, const struct drm_gem_object *gem)
```

Print `ttm_buffer_object` info for debugfs

**Parameters**

- `struct drm_printer *p`: DRM printer
- `unsigned int indent`: Tab indentation level
- `const struct drm_gem_object *gem`: GEM object

**Description**

This function can be used as [`drm_gem_object_funcs.print_info`](#c-struct-drm_gem_object_funcs)
callback.

#### <a id="c-drm_gem_ttm_vmap"></a>`drm_gem_ttm_vmap()`

```c
int drm_gem_ttm_vmap(struct drm_gem_object *gem, struct iosys_map *map)
```

vmap `ttm_buffer_object`

**Parameters**

- `struct drm_gem_object *gem`: GEM object.
- `struct iosys_map *map`: \[out\] returns the dma-buf mapping.

**Description**

Maps a GEM object with `ttm_bo_vmap()`. This function can be used as
[`drm_gem_object_funcs.vmap`](#c-struct-drm_gem_object_funcs) callback.

**Return**

0 on success, or a negative errno code otherwise.

#### <a id="c-drm_gem_ttm_vunmap"></a>`drm_gem_ttm_vunmap()`

```c
void drm_gem_ttm_vunmap(struct drm_gem_object *gem, struct iosys_map *map)
```

vunmap `ttm_buffer_object`

**Parameters**

- `struct drm_gem_object *gem`: GEM object.
- `struct iosys_map *map`: dma-buf mapping.

**Description**

Unmaps a GEM object with `ttm_bo_vunmap()`. This function can be used as
[`drm_gem_object_funcs.vmap`](#c-struct-drm_gem_object_funcs) callback.

#### <a id="c-drm_gem_ttm_mmap"></a>`drm_gem_ttm_mmap()`

```c
int drm_gem_ttm_mmap(struct drm_gem_object *gem, struct vm_area_struct *vma)
```

mmap `ttm_buffer_object`

**Parameters**

- `struct drm_gem_object *gem`: GEM object.
- `struct vm_area_struct *vma`: vm area.

**Description**

This function can be used as [`drm_gem_object_funcs.mmap`](#c-struct-drm_gem_object_funcs)
callback.

#### <a id="c-drm_gem_ttm_dumb_map_offset"></a>`drm_gem_ttm_dumb_map_offset()`

```c
int drm_gem_ttm_dumb_map_offset(struct drm_file *file, struct drm_device *dev, uint32_t handle, uint64_t *offset)
```

Implements struct [`drm_driver.dumb_map_offset`](/kernel/hardware/gpu/drm-internals.md#c-struct-drm_driver)

**Parameters**

- `struct drm_file *file`: DRM file pointer.
- `struct drm_device *dev`: DRM device.
- `uint32_t handle`: GEM handle
- `uint64_t *offset`: Returns the mapping's memory offset on success

**Description**

Provides an implementation of struct [`drm_driver.dumb_map_offset`](/kernel/hardware/gpu/drm-internals.md#c-struct-drm_driver) for
TTM-based GEM drivers. TTM allocates the offset internally and
[`drm_gem_ttm_dumb_map_offset()`](#c-drm_gem_ttm_dumb_map_offset) returns it for dumb-buffer implementations.

See struct [`drm_driver.dumb_map_offset`](/kernel/hardware/gpu/drm-internals.md#c-struct-drm_driver).

**Return**

0 on success, or a negative errno code otherwise.


<a id="rst-vma-offset-manager"></a>

## VMA Offset Manager


The vma-manager is responsible to map arbitrary driver-dependent memory
regions into the linear user address-space. It provides offsets to the
caller which can then be used on the address_space of the drm-device. It
takes care to not overlap regions, size them appropriately and to not
confuse mm-core by inconsistent fake vm_pgoff fields.
Drivers shouldn't use this for object placement in VMEM. This manager should
only be used to manage mappings into linear user-space VMs.

We use drm_mm as backend to manage object allocations. But it is highly
optimized for alloc/free calls, not lookups. Hence, we use an rb-tree to
speed up offset lookups.

You must not use multiple offset managers on a single address_space.
Otherwise, mm-core will be unable to tear down memory mappings as the VM will
no longer be linear.

This offset manager works on page-based addresses. That is, every argument
and return code (with the exception of [`drm_vma_node_offset_addr()`](#c-drm_vma_node_offset_addr)) is given
in number of pages, not number of bytes. That means, object sizes and offsets
must always be page-aligned (as usual).
If you want to get a valid byte-based user-space address for a given offset,
please see [`drm_vma_node_offset_addr()`](#c-drm_vma_node_offset_addr).

Additionally to offset management, the vma offset manager also handles access
management. For every open-file context that is allowed to access a given
node, you must call [`drm_vma_node_allow()`](#c-drm_vma_node_allow). Otherwise, an `mmap()` call on this
open-file with the offset of the node will fail with -EACCES. To revoke
access again, use [`drm_vma_node_revoke()`](#c-drm_vma_node_revoke). However, the caller is responsible
for destroying already existing mappings, if required.



#### <a id="c-drm_vma_offset_exact_lookup_locked"></a>`drm_vma_offset_exact_lookup_locked()`

```c
struct drm_vma_offset_node * drm_vma_offset_exact_lookup_locked(struct drm_vma_offset_manager *mgr, unsigned long start, unsigned long pages)
```

Look up node by exact address

**Parameters**

- `struct drm_vma_offset_manager *mgr`: Manager object
- `unsigned long start`: Start address (page-based, not byte-based)
- `unsigned long pages`: Size of object (page-based)

**Description**

Same as [`drm_vma_offset_lookup_locked()`](#c-drm_vma_offset_lookup_locked) but does not allow any offset into the node.
It only returns the exact object with the given start address.

**Return**

Node at exact start address **start**.

#### <a id="c-drm_vma_offset_lock_lookup"></a>`drm_vma_offset_lock_lookup()`

```c
void drm_vma_offset_lock_lookup(struct drm_vma_offset_manager *mgr)
```

Lock lookup for extended private use

**Parameters**

- `struct drm_vma_offset_manager *mgr`: Manager object

**Description**

Lock VMA manager for extended lookups. Only locked VMA function calls
are allowed while holding this lock. All other contexts are blocked from VMA
until the lock is released via [`drm_vma_offset_unlock_lookup()`](#c-drm_vma_offset_unlock_lookup).

Use this if you need to take a reference to the objects returned by
[`drm_vma_offset_lookup_locked()`](#c-drm_vma_offset_lookup_locked) before releasing this lock again.

This lock must not be used for anything else than extended lookups. You must
not call any other VMA helpers while holding this lock.

**Note**

You're in atomic-context while holding this lock!

#### <a id="c-drm_vma_offset_unlock_lookup"></a>`drm_vma_offset_unlock_lookup()`

```c
void drm_vma_offset_unlock_lookup(struct drm_vma_offset_manager *mgr)
```

Unlock lookup for extended private use

**Parameters**

- `struct drm_vma_offset_manager *mgr`: Manager object

**Description**

Release lookup-lock. See [`drm_vma_offset_lock_lookup()`](#c-drm_vma_offset_lock_lookup) for more information.

#### <a id="c-drm_vma_node_reset"></a>`drm_vma_node_reset()`

```c
void drm_vma_node_reset(struct drm_vma_offset_node *node)
```

Initialize or reset node object

**Parameters**

- `struct drm_vma_offset_node *node`: Node to initialize or reset

**Description**

Reset a node to its initial state. This must be called before using it with
any VMA offset manager.

This must not be called on an already allocated node, or you will leak
memory.

#### <a id="c-drm_vma_node_start"></a>`drm_vma_node_start()`

```c
unsigned long drm_vma_node_start(const struct drm_vma_offset_node *node)
```

Return start address for page-based addressing

**Parameters**

- `const struct drm_vma_offset_node *node`: Node to inspect

**Description**

Return the start address of the given node. This can be used as offset into
the linear VM space that is provided by the VMA offset manager. Note that
this can only be used for page-based addressing. If you need a proper offset
for user-space mappings, you must apply "\<\< PAGE_SHIFT" or use the
[`drm_vma_node_offset_addr()`](#c-drm_vma_node_offset_addr) helper instead.

**Return**

Start address of **node** for page-based addressing. 0 if the node does not
have an offset allocated.

#### <a id="c-drm_vma_node_size"></a>`drm_vma_node_size()`

```c
unsigned long drm_vma_node_size(struct drm_vma_offset_node *node)
```

Return size (page-based)

**Parameters**

- `struct drm_vma_offset_node *node`: Node to inspect

**Description**

Return the size as number of pages for the given node. This is the same size
that was passed to [`drm_vma_offset_add()`](#c-drm_vma_offset_add). If no offset is allocated for the
node, this is 0.

**Return**

Size of **node** as number of pages. 0 if the node does not have an offset
allocated.

#### <a id="c-drm_vma_node_offset_addr"></a>`drm_vma_node_offset_addr()`

```c
__u64 drm_vma_node_offset_addr(struct drm_vma_offset_node *node)
```

Return sanitized offset for user-space mmaps

**Parameters**

- `struct drm_vma_offset_node *node`: Linked offset node

**Description**

Same as [`drm_vma_node_start()`](#c-drm_vma_node_start) but returns the address as a valid offset that
can be used for user-space mappings during `mmap()`.
This must not be called on unlinked nodes.

**Return**

Offset of **node** for byte-based addressing. 0 if the node does not have an
object allocated.

#### <a id="c-drm_vma_node_unmap"></a>`drm_vma_node_unmap()`

```c
void drm_vma_node_unmap(struct drm_vma_offset_node *node, struct address_space *file_mapping)
```

Unmap offset node

**Parameters**

- `struct drm_vma_offset_node *node`: Offset node
- `struct address_space *file_mapping`: Address space to unmap **node** from

**Description**

Unmap all userspace mappings for a given offset node. The mappings must be
associated with the **file_mapping** address-space. If no offset exists
nothing is done.

This call is unlocked. The caller must guarantee that [`drm_vma_offset_remove()`](#c-drm_vma_offset_remove)
is not called on this node concurrently.

#### <a id="c-drm_vma_node_verify_access"></a>`drm_vma_node_verify_access()`

```c
int drm_vma_node_verify_access(struct drm_vma_offset_node *node, struct drm_file *tag)
```

Access verification helper for TTM

**Parameters**

- `struct drm_vma_offset_node *node`: Offset node
- `struct drm_file *tag`: Tag of file to check

**Description**

This checks whether **tag** is granted access to **node**. It is the same as
[`drm_vma_node_is_allowed()`](#c-drm_vma_node_is_allowed) but suitable as drop-in helper for TTM
`verify_access()` callbacks.

**Return**

0 if access is granted, -EACCES otherwise.



#### <a id="c-drm_vma_offset_manager_init"></a>`drm_vma_offset_manager_init()`

```c
void drm_vma_offset_manager_init(struct drm_vma_offset_manager *mgr, unsigned long page_offset, unsigned long size)
```

Initialize new offset-manager

**Parameters**

- `struct drm_vma_offset_manager *mgr`: Manager object
- `unsigned long page_offset`: Offset of available memory area (page-based)
- `unsigned long size`: Size of available address space range (page-based)

**Description**

Initialize a new offset-manager. The offset and area size available for the
manager are given as **page_offset** and **size**. Both are interpreted as
page-numbers, not bytes.

Adding/removing nodes from the manager is locked internally and protected
against concurrent access. However, node allocation and destruction is left
for the caller. While calling into the vma-manager, a given node must
always be guaranteed to be referenced.

#### <a id="c-drm_vma_offset_manager_destroy"></a>`drm_vma_offset_manager_destroy()`

```c
void drm_vma_offset_manager_destroy(struct drm_vma_offset_manager *mgr)
```

Destroy offset manager

**Parameters**

- `struct drm_vma_offset_manager *mgr`: Manager object

**Description**

Destroy an object manager which was previously created via
[`drm_vma_offset_manager_init()`](#c-drm_vma_offset_manager_init). The caller must remove all allocated nodes
before destroying the manager. Otherwise, drm_mm will refuse to free the
requested resources.

The manager must not be accessed after this function is called.

#### <a id="c-drm_vma_offset_lookup_locked"></a>`drm_vma_offset_lookup_locked()`

```c
struct drm_vma_offset_node * drm_vma_offset_lookup_locked(struct drm_vma_offset_manager *mgr, unsigned long start, unsigned long pages)
```

Find node in offset space

**Parameters**

- `struct drm_vma_offset_manager *mgr`: Manager object
- `unsigned long start`: Start address for object (page-based)
- `unsigned long pages`: Size of object (page-based)

**Description**

Find a node given a start address and object size. This returns the _best_
match for the given node. That is, **start** may point somewhere into a valid
region and the given node will be returned, as long as the node spans the
whole requested area (given the size in number of pages as **pages**).

Note that before lookup the vma offset manager lookup lock must be acquired
with [`drm_vma_offset_lock_lookup()`](#c-drm_vma_offset_lock_lookup). See there for an example. This can then be
used to implement weakly referenced lookups using [`kref_get_unless_zero()`](/kernel/internals/core-api/kref.md#c-kref_get_unless_zero).

**Example**

```text
drm_vma_offset_lock_lookup(mgr);
node = drm_vma_offset_lookup_locked(mgr);
if (node)
    kref_get_unless_zero(container_of(node, sth, entr));
drm_vma_offset_unlock_lookup(mgr);
```

**Return**

Returns NULL if no suitable node can be found. Otherwise, the best match
is returned. It's the caller's responsibility to make sure the node doesn't
get destroyed before the caller can access it.

#### <a id="c-drm_vma_offset_add"></a>`drm_vma_offset_add()`

```c
int drm_vma_offset_add(struct drm_vma_offset_manager *mgr, struct drm_vma_offset_node *node, unsigned long pages)
```

Add offset node to manager

**Parameters**

- `struct drm_vma_offset_manager *mgr`: Manager object
- `struct drm_vma_offset_node *node`: Node to be added
- `unsigned long pages`: Allocation size visible to user-space (in number of pages)

**Description**

Add a node to the offset-manager. If the node was already added, this does
nothing and return 0. **pages** is the size of the object given in number of
pages.
After this call succeeds, you can access the offset of the node until it
is removed again.

If this call fails, it is safe to retry the operation or call
[`drm_vma_offset_remove()`](#c-drm_vma_offset_remove), anyway. However, no cleanup is required in that
case.

**pages** is not required to be the same size as the underlying memory object
that you want to map. It only limits the size that user-space can map into
their address space.

**Return**

0 on success, negative error code on failure.

#### <a id="c-drm_vma_offset_remove"></a>`drm_vma_offset_remove()`

```c
void drm_vma_offset_remove(struct drm_vma_offset_manager *mgr, struct drm_vma_offset_node *node)
```

Remove offset node from manager

**Parameters**

- `struct drm_vma_offset_manager *mgr`: Manager object
- `struct drm_vma_offset_node *node`: Node to be removed

**Description**

Remove a node from the offset manager. If the node wasn't added before, this
does nothing. After this call returns, the offset and size will be 0 until a
new offset is allocated via [`drm_vma_offset_add()`](#c-drm_vma_offset_add) again. Helper functions like
[`drm_vma_node_start()`](#c-drm_vma_node_start) and [`drm_vma_node_offset_addr()`](#c-drm_vma_node_offset_addr) will return 0 if no
offset is allocated.

#### <a id="c-drm_vma_node_allow"></a>`drm_vma_node_allow()`

```c
int drm_vma_node_allow(struct drm_vma_offset_node *node, struct drm_file *tag)
```

Add open-file to list of allowed users

**Parameters**

- `struct drm_vma_offset_node *node`: Node to modify
- `struct drm_file *tag`: Tag of file to remove

**Description**

Add **tag** to the list of allowed open-files for this node. If **tag** is
already on this list, the ref-count is incremented.

The list of allowed-users is preserved across [`drm_vma_offset_add()`](#c-drm_vma_offset_add) and
[`drm_vma_offset_remove()`](#c-drm_vma_offset_remove) calls. You may even call it if the node is currently
not added to any offset-manager.

You must remove all open-files the same number of times as you added them
before destroying the node. Otherwise, you will leak memory.

This is locked against concurrent access internally.

**Return**

0 on success, negative error code on internal failure (out-of-mem)

#### <a id="c-drm_vma_node_allow_once"></a>`drm_vma_node_allow_once()`

```c
int drm_vma_node_allow_once(struct drm_vma_offset_node *node, struct drm_file *tag)
```

Add open-file to list of allowed users

**Parameters**

- `struct drm_vma_offset_node *node`: Node to modify
- `struct drm_file *tag`: Tag of file to remove

**Description**

Add **tag** to the list of allowed open-files for this node.

The list of allowed-users is preserved across [`drm_vma_offset_add()`](#c-drm_vma_offset_add) and
[`drm_vma_offset_remove()`](#c-drm_vma_offset_remove) calls. You may even call it if the node is currently
not added to any offset-manager.

This is not ref-counted unlike [`drm_vma_node_allow()`](#c-drm_vma_node_allow) hence [`drm_vma_node_revoke()`](#c-drm_vma_node_revoke)
should only be called once after this.

This is locked against concurrent access internally.

**Return**

0 on success, negative error code on internal failure (out-of-mem)

#### <a id="c-drm_vma_node_revoke"></a>`drm_vma_node_revoke()`

```c
void drm_vma_node_revoke(struct drm_vma_offset_node *node, struct drm_file *tag)
```

Remove open-file from list of allowed users

**Parameters**

- `struct drm_vma_offset_node *node`: Node to modify
- `struct drm_file *tag`: Tag of file to remove

**Description**

Decrement the ref-count of **tag** in the list of allowed open-files on **node**.
If the ref-count drops to zero, remove **tag** from the list. You must call
this once for every [`drm_vma_node_allow()`](#c-drm_vma_node_allow) on **tag**.

This is locked against concurrent access internally.

If **tag** is not on the list, nothing is done.

#### <a id="c-drm_vma_node_is_allowed"></a>`drm_vma_node_is_allowed()`

```c
bool drm_vma_node_is_allowed(struct drm_vma_offset_node *node, struct drm_file *tag)
```

Check whether an open-file is granted access

**Parameters**

- `struct drm_vma_offset_node *node`: Node to check
- `struct drm_file *tag`: Tag of file to remove

**Description**

Search the list in **node** whether **tag** is currently on the list of allowed
open-files (see [`drm_vma_node_allow()`](#c-drm_vma_node_allow)).

This is locked against concurrent access internally.

**Return**

true if **filp** is on the list


<a id="rst-prime-buffer-sharing-1"></a>
<a id="rst-prime-buffer-sharing"></a>

## PRIME Buffer Sharing

PRIME is the cross device buffer sharing framework in drm, originally created for the OPTIMUS range of multi-gpu platforms. To userspace PRIME buffers are dma-buf based file descriptors.

<a id="rst-overview-and-lifetime-rules"></a>

### Overview and Lifetime Rules


Similar to GEM global names, PRIME file descriptors are also used to share
buffer objects across processes. They offer additional security: as file
descriptors must be explicitly sent over UNIX domain sockets to be shared
between applications, they can't be guessed like the globally unique GEM
names.

Drivers that support the PRIME API implement the drm_gem_object_funcs.export
and [`drm_driver.gem_prime_import`](/kernel/hardware/gpu/drm-internals.md#c-struct-drm_driver) hooks. [`dma_buf_ops`](/kernel/hardware/driver-api/io-and-dma/dma-buf.md#c-struct-dma_buf_ops) implementations for
drivers are all individually exported for drivers which need to overwrite
or reimplement some of them.

**Reference Counting for GEM Drivers**

On the export the [`dma_buf`](/kernel/hardware/driver-api/io-and-dma/dma-buf.md#c-struct-dma_buf) holds a reference to the exported buffer object,
usually a [`drm_gem_object`](#c-struct-drm_gem_object). It takes this reference in the PRIME_HANDLE_TO_FD
IOCTL, when it first calls [`drm_gem_object_funcs.export`](#c-struct-drm_gem_object_funcs)
and stores the exporting GEM object in the [`dma_buf.priv`](/kernel/hardware/driver-api/io-and-dma/dma-buf.md#c-struct-dma_buf) field. This
reference needs to be released when the final reference to the [`dma_buf`](/kernel/hardware/driver-api/io-and-dma/dma-buf.md#c-struct-dma_buf)
itself is dropped and its [`dma_buf_ops.release`](/kernel/hardware/driver-api/io-and-dma/dma-buf.md#c-struct-dma_buf_ops) function is called.  For
GEM-based drivers, the [`dma_buf`](/kernel/hardware/driver-api/io-and-dma/dma-buf.md#c-struct-dma_buf) should be exported using
[`drm_gem_dmabuf_export()`](#c-drm_gem_dmabuf_export) and then released by [`drm_gem_dmabuf_release()`](#c-drm_gem_dmabuf_release).

Thus the chain of references always flows in one direction, avoiding loops:
importing GEM object -> dma-buf -> exported GEM bo. A further complication
are the lookup caches for import and export. These are required to guarantee
that any given object will always have only one unique userspace handle. This
is required to allow userspace to detect duplicated imports, since some GEM
drivers do fail command submissions if a given buffer object is listed more
than once. These import and export caches in [`drm_prime_file_private`](#c-struct-drm_prime_file_private) only
retain a weak reference, which is cleaned up when the corresponding object is
released.

Self-importing: If userspace is using PRIME as a replacement for flink then
it will get a fd->handle request for a GEM object that it created.  Drivers
should detect this situation and return back the underlying object from the
dma-buf private. For GEM based drivers this is handled in
[`drm_gem_prime_import()`](#c-drm_gem_prime_import) already.


<a id="rst-prime-helper-functions"></a>

### PRIME Helper Functions


Drivers can implement [`drm_gem_object_funcs.export`](#c-struct-drm_gem_object_funcs) and
[`drm_driver.gem_prime_import`](/kernel/hardware/gpu/drm-internals.md#c-struct-drm_driver) in terms of simpler APIs by using the helper
functions [`drm_gem_prime_export()`](#c-drm_gem_prime_export) and [`drm_gem_prime_import()`](#c-drm_gem_prime_import). These functions
implement dma-buf support in terms of some lower-level helpers, which are
again exported for drivers to use individually:

**Exporting buffers**

Optional pinning of buffers is handled at dma-buf attach and detach time in
[`drm_gem_map_attach()`](#c-drm_gem_map_attach) and [`drm_gem_map_detach()`](#c-drm_gem_map_detach). Backing storage itself is
handled by [`drm_gem_map_dma_buf()`](#c-drm_gem_map_dma_buf) and [`drm_gem_unmap_dma_buf()`](#c-drm_gem_unmap_dma_buf), which relies on
[`drm_gem_object_funcs.get_sg_table`](#c-struct-drm_gem_object_funcs). If [`drm_gem_object_funcs.get_sg_table`](#c-struct-drm_gem_object_funcs) is
unimplemented, exports into another device are rejected.

For kernel-internal access there's [`drm_gem_dmabuf_vmap()`](#c-drm_gem_dmabuf_vmap) and
[`drm_gem_dmabuf_vunmap()`](#c-drm_gem_dmabuf_vunmap). Userspace mmap support is provided by
[`drm_gem_dmabuf_mmap()`](#c-drm_gem_dmabuf_mmap).

Note that these export helpers can only be used if the underlying backing
storage is fully coherent and either permanently pinned, or it is safe to pin
it indefinitely.

FIXME: The underlying helper functions are named rather inconsistently.

**Importing buffers**

Importing dma-bufs using [`drm_gem_prime_import()`](#c-drm_gem_prime_import) relies on
[`drm_driver.gem_prime_import_sg_table`](/kernel/hardware/gpu/drm-internals.md#c-struct-drm_driver).

Note that similarly to the export helpers this permanently pins the
underlying backing storage. Which is ok for scanout, but is not the best
option for sharing lots of buffers for rendering.


<a id="rst-prime-function-references"></a>

### PRIME Function References


#### <a id="c-struct-drm_prime_file_private"></a>`struct drm_prime_file_private`

per-file tracking for PRIME

**Definition**

```c
struct drm_prime_file_private {
};
```

**Description**

This just contains the internal [`struct dma_buf`](/kernel/hardware/driver-api/io-and-dma/dma-buf.md#c-struct-dma_buf) and handle caches for each
[`struct drm_file`](/kernel/hardware/gpu/drm-internals.md#c-struct-drm_file) used by the PRIME core code.



#### <a id="c-drm_gem_dmabuf_export"></a>`drm_gem_dmabuf_export()`

```c
struct dma_buf * drm_gem_dmabuf_export(struct drm_device *dev, struct dma_buf_export_info *exp_info)
```

[`dma_buf`](/kernel/hardware/driver-api/io-and-dma/dma-buf.md#c-struct-dma_buf) export implementation for GEM

**Parameters**

- `struct drm_device *dev`: parent device for the exported dmabuf
- `struct dma_buf_export_info *exp_info`: the export information used by [`dma_buf_export()`](/kernel/hardware/driver-api/io-and-dma/dma-buf.md#c-dma_buf_export)

**Description**

This wraps [`dma_buf_export()`](/kernel/hardware/driver-api/io-and-dma/dma-buf.md#c-dma_buf_export) for use by generic GEM drivers that are using
[`drm_gem_dmabuf_release()`](#c-drm_gem_dmabuf_release). In addition to calling [`dma_buf_export()`](/kernel/hardware/driver-api/io-and-dma/dma-buf.md#c-dma_buf_export), we take
a reference to the [`drm_device`](/kernel/hardware/gpu/drm-internals.md#c-struct-drm_device) and the exported [`drm_gem_object`](#c-struct-drm_gem_object) (stored in
[`dma_buf_export_info.priv`](/kernel/hardware/driver-api/io-and-dma/dma-buf.md#c-struct-dma_buf_export_info)) which is released by [`drm_gem_dmabuf_release()`](#c-drm_gem_dmabuf_release).

Returns the new dmabuf.

#### <a id="c-drm_gem_dmabuf_release"></a>`drm_gem_dmabuf_release()`

```c
void drm_gem_dmabuf_release(struct dma_buf *dma_buf)
```

[`dma_buf`](/kernel/hardware/driver-api/io-and-dma/dma-buf.md#c-struct-dma_buf) release implementation for GEM

**Parameters**

- `struct dma_buf *dma_buf`: buffer to be released

**Description**

Generic release function for dma_bufs exported as PRIME buffers. GEM drivers
must use this in their [`dma_buf_ops`](/kernel/hardware/driver-api/io-and-dma/dma-buf.md#c-struct-dma_buf_ops) structure as the release callback.
[`drm_gem_dmabuf_release()`](#c-drm_gem_dmabuf_release) should be used in conjunction with
[`drm_gem_dmabuf_export()`](#c-drm_gem_dmabuf_export).

#### <a id="c-drm_gem_prime_fd_to_handle"></a>`drm_gem_prime_fd_to_handle()`

```c
int drm_gem_prime_fd_to_handle(struct drm_device *dev, struct drm_file *file_priv, int prime_fd, uint32_t *handle)
```

PRIME import function for GEM drivers

**Parameters**

- `struct drm_device *dev`: drm_device to import into
- `struct drm_file *file_priv`: drm file-private structure
- `int prime_fd`: fd id of the dma-buf which should be imported
- `uint32_t *handle`: pointer to storage for the handle of the imported buffer object

**Description**

This is the PRIME import function which must be used mandatorily by GEM
drivers to ensure correct lifetime management of the underlying GEM object.
The actual importing of GEM object from the dma-buf is done through the
[`drm_driver.gem_prime_import`](/kernel/hardware/gpu/drm-internals.md#c-struct-drm_driver) driver callback.

Returns 0 on success or a negative error code on failure.

#### <a id="c-drm_gem_prime_handle_to_dmabuf"></a>`drm_gem_prime_handle_to_dmabuf()`

```c
struct dma_buf * drm_gem_prime_handle_to_dmabuf(struct drm_device *dev, struct drm_file *file_priv, uint32_t handle, uint32_t flags)
```

PRIME export function for GEM drivers

**Parameters**

- `struct drm_device *dev`: dev to export the buffer from
- `struct drm_file *file_priv`: drm file-private structure
- `uint32_t handle`: buffer handle to export
- `uint32_t flags`: flags like DRM_CLOEXEC

**Description**

This is the PRIME export function which must be used mandatorily by GEM
drivers to ensure correct lifetime management of the underlying GEM object.
The actual exporting from GEM object to a dma-buf is done through the
[`drm_gem_object_funcs.export`](#c-struct-drm_gem_object_funcs) callback.

Unlike [`drm_gem_prime_handle_to_fd()`](#c-drm_gem_prime_handle_to_fd), it returns the struct dma_buf it
has created, without attaching it to any file descriptors.  The difference
between those two is similar to that between [`anon_inode_getfile()`](/kernel/internals/filesystems/api-summary.md#c-anon_inode_getfile) and
[`anon_inode_getfd()`](/kernel/internals/filesystems/api-summary.md#c-anon_inode_getfd); insertion into descriptor table is something you
can not revert if any cleanup is needed, so the descriptor-returning
variants should only be used when you are past the last failure exit
and the only thing left is passing the new file descriptor to userland.
When all you need is the object itself or when you need to do something
else that might fail, use that one instead.

#### <a id="c-drm_gem_prime_handle_to_fd"></a>`drm_gem_prime_handle_to_fd()`

```c
int drm_gem_prime_handle_to_fd(struct drm_device *dev, struct drm_file *file_priv, uint32_t handle, uint32_t flags, int *prime_fd)
```

PRIME export function for GEM drivers

**Parameters**

- `struct drm_device *dev`: dev to export the buffer from
- `struct drm_file *file_priv`: drm file-private structure
- `uint32_t handle`: buffer handle to export
- `uint32_t flags`: flags like DRM_CLOEXEC
- `int *prime_fd`: pointer to storage for the fd id of the create dma-buf

**Description**

This is the PRIME export function which must be used mandatorily by GEM
drivers to ensure correct lifetime management of the underlying GEM object.
The actual exporting from GEM object to a dma-buf is done through the
[`drm_gem_object_funcs.export`](#c-struct-drm_gem_object_funcs) callback.

#### <a id="c-drm_gem_map_attach"></a>`drm_gem_map_attach()`

```c
int drm_gem_map_attach(struct dma_buf *dma_buf, struct dma_buf_attachment *attach)
```

dma_buf attach implementation for GEM

**Parameters**

- `struct dma_buf *dma_buf`: buffer to attach device to
- `struct dma_buf_attachment *attach`: buffer attachment data

**Description**

Calls [`drm_gem_object_funcs.pin`](#c-struct-drm_gem_object_funcs) for device specific handling. This can be
used as the [`dma_buf_ops.attach`](/kernel/hardware/driver-api/io-and-dma/dma-buf.md#c-struct-dma_buf_ops) callback. Must be used together with
[`drm_gem_map_detach()`](#c-drm_gem_map_detach).

Returns 0 on success, negative error code on failure.

#### <a id="c-drm_gem_map_detach"></a>`drm_gem_map_detach()`

```c
void drm_gem_map_detach(struct dma_buf *dma_buf, struct dma_buf_attachment *attach)
```

dma_buf detach implementation for GEM

**Parameters**

- `struct dma_buf *dma_buf`: buffer to detach from
- `struct dma_buf_attachment *attach`: attachment to be detached

**Description**

Calls [`drm_gem_object_funcs.pin`](#c-struct-drm_gem_object_funcs) for device specific handling.  Cleans up
[`dma_buf_attachment`](/kernel/hardware/driver-api/io-and-dma/dma-buf.md#c-struct-dma_buf_attachment) from [`drm_gem_map_attach()`](#c-drm_gem_map_attach). This can be used as the
[`dma_buf_ops.detach`](/kernel/hardware/driver-api/io-and-dma/dma-buf.md#c-struct-dma_buf_ops) callback.

#### <a id="c-drm_gem_map_dma_buf"></a>`drm_gem_map_dma_buf()`

```c
struct sg_table * drm_gem_map_dma_buf(struct dma_buf_attachment *attach, enum dma_data_direction dir)
```

map_dma_buf implementation for GEM

**Parameters**

- `struct dma_buf_attachment *attach`: attachment whose scatterlist is to be returned
- `enum dma_data_direction dir`: direction of DMA transfer

**Description**

Calls [`drm_gem_object_funcs.get_sg_table`](#c-struct-drm_gem_object_funcs) and then maps the scatterlist. This
can be used as the [`dma_buf_ops.map_dma_buf`](/kernel/hardware/driver-api/io-and-dma/dma-buf.md#c-struct-dma_buf_ops) callback. Should be used together
with [`drm_gem_unmap_dma_buf()`](#c-drm_gem_unmap_dma_buf).

**Return**

sg_table containing the scatterlist to be returned; returns ERR_PTR
on error. May return -EINTR if it is interrupted by a signal.

#### <a id="c-drm_gem_unmap_dma_buf"></a>`drm_gem_unmap_dma_buf()`

```c
void drm_gem_unmap_dma_buf(struct dma_buf_attachment *attach, struct sg_table *sgt, enum dma_data_direction dir)
```

unmap_dma_buf implementation for GEM

**Parameters**

- `struct dma_buf_attachment *attach`: attachment to unmap buffer from
- `struct sg_table *sgt`: scatterlist info of the buffer to unmap
- `enum dma_data_direction dir`: direction of DMA transfer

**Description**

This can be used as the [`dma_buf_ops.unmap_dma_buf`](/kernel/hardware/driver-api/io-and-dma/dma-buf.md#c-struct-dma_buf_ops) callback.

#### <a id="c-drm_gem_dmabuf_vmap"></a>`drm_gem_dmabuf_vmap()`

```c
int drm_gem_dmabuf_vmap(struct dma_buf *dma_buf, struct iosys_map *map)
```

dma_buf vmap implementation for GEM

**Parameters**

- `struct dma_buf *dma_buf`: buffer to be mapped
- `struct iosys_map *map`: the virtual address of the buffer

**Description**

Sets up a kernel virtual mapping. This can be used as the [`dma_buf_ops.vmap`](/kernel/hardware/driver-api/io-and-dma/dma-buf.md#c-struct-dma_buf_ops)
callback. Calls into [`drm_gem_object_funcs.vmap`](#c-struct-drm_gem_object_funcs) for device specific handling.
The kernel virtual address is returned in map.

Returns 0 on success or a negative errno code otherwise.

#### <a id="c-drm_gem_dmabuf_vunmap"></a>`drm_gem_dmabuf_vunmap()`

```c
void drm_gem_dmabuf_vunmap(struct dma_buf *dma_buf, struct iosys_map *map)
```

dma_buf vunmap implementation for GEM

**Parameters**

- `struct dma_buf *dma_buf`: buffer to be unmapped
- `struct iosys_map *map`: the virtual address of the buffer

**Description**

Releases a kernel virtual mapping. This can be used as the
[`dma_buf_ops.vunmap`](/kernel/hardware/driver-api/io-and-dma/dma-buf.md#c-struct-dma_buf_ops) callback. Calls into [`drm_gem_object_funcs.vunmap`](#c-struct-drm_gem_object_funcs) for device specific handling.

#### <a id="c-drm_gem_prime_mmap"></a>`drm_gem_prime_mmap()`

```c
int drm_gem_prime_mmap(struct drm_gem_object *obj, struct vm_area_struct *vma)
```

PRIME mmap function for GEM drivers

**Parameters**

- `struct drm_gem_object *obj`: GEM object
- `struct vm_area_struct *vma`: Virtual address range

**Description**

This function sets up a userspace mapping for PRIME exported buffers using
the same codepath that is used for regular GEM buffer mapping on the DRM fd.
The fake GEM offset is added to vma->vm_pgoff and [`drm_driver->fops`](/kernel/hardware/gpu/drm-internals.md#c-struct-drm_driver)->mmap is
called to set up the mapping.

#### <a id="c-drm_gem_dmabuf_mmap"></a>`drm_gem_dmabuf_mmap()`

```c
int drm_gem_dmabuf_mmap(struct dma_buf *dma_buf, struct vm_area_struct *vma)
```

dma_buf mmap implementation for GEM

**Parameters**

- `struct dma_buf *dma_buf`: buffer to be mapped
- `struct vm_area_struct *vma`: virtual address range

**Description**

Provides memory mapping for the buffer. This can be used as the
[`dma_buf_ops.mmap`](/kernel/hardware/driver-api/io-and-dma/dma-buf.md#c-struct-dma_buf_ops) callback. It just forwards to [`drm_gem_prime_mmap()`](#c-drm_gem_prime_mmap).

Returns 0 on success or a negative error code on failure.

#### <a id="c-drm_prime_pages_to_sg"></a>`drm_prime_pages_to_sg()`

```c
struct sg_table * drm_prime_pages_to_sg(struct drm_device *dev, struct page **pages, unsigned int nr_pages)
```

converts a page array into an sg list

**Parameters**

- `struct drm_device *dev`: DRM device
- `struct page **pages`: pointer to the array of page pointers to convert
- `unsigned int nr_pages`: length of the page vector

**Description**

This helper creates an sg table object from a set of pages
the driver is responsible for mapping the pages into the
importers address space for use with dma_buf itself.

This is useful for implementing [`drm_gem_object_funcs.get_sg_table`](#c-struct-drm_gem_object_funcs).

#### <a id="c-drm_prime_get_contiguous_size"></a>`drm_prime_get_contiguous_size()`

```c
unsigned long drm_prime_get_contiguous_size(struct sg_table *sgt)
```

returns the contiguous size of the buffer

**Parameters**

- `struct sg_table *sgt`: sg_table describing the buffer to check

**Description**

This helper calculates the contiguous size in the DMA address space
of the buffer described by the provided sg_table.

This is useful for implementing
[`drm_gem_object_funcs.gem_prime_import_sg_table`](#c-struct-drm_gem_object_funcs).

#### <a id="c-drm_gem_prime_export"></a>`drm_gem_prime_export()`

```c
struct dma_buf * drm_gem_prime_export(struct drm_gem_object *obj, int flags)
```

helper library implementation of the export callback

**Parameters**

- `struct drm_gem_object *obj`: GEM object to export
- `int flags`: flags like DRM_CLOEXEC and DRM_RDWR

**Description**

This is the implementation of the [`drm_gem_object_funcs.export`](#c-struct-drm_gem_object_funcs) functions for GEM drivers
using the PRIME helpers. It is used as the default in
[`drm_gem_prime_handle_to_fd()`](#c-drm_gem_prime_handle_to_fd).

#### <a id="c-drm_gem_is_prime_exported_dma_buf"></a>`drm_gem_is_prime_exported_dma_buf()`

```c
bool drm_gem_is_prime_exported_dma_buf(struct drm_device *dev, struct dma_buf *dma_buf)
```

checks if the DMA-BUF was exported from a GEM object belonging to **dev**.

**Parameters**

- `struct drm_device *dev`: drm_device to check against
- `struct dma_buf *dma_buf`: dma-buf object to import

**Return**

true if the DMA-BUF was exported from a GEM object belonging
to **dev**, false otherwise.

#### <a id="c-drm_gem_prime_import_dev"></a>`drm_gem_prime_import_dev()`

```c
struct drm_gem_object * drm_gem_prime_import_dev(struct drm_device *dev, struct dma_buf *dma_buf, struct device *attach_dev)
```

core implementation of the import callback

**Parameters**

- `struct drm_device *dev`: drm_device to import into
- `struct dma_buf *dma_buf`: dma-buf object to import
- `struct device *attach_dev`: struct device to dma_buf attach

**Description**

This is the core of [`drm_gem_prime_import()`](#c-drm_gem_prime_import). It's designed to be called by
drivers who want to use a different device structure than [`drm_device.dev`](/kernel/hardware/gpu/drm-internals.md#c-struct-drm_device) for
attaching via dma_buf. This function calls
[`drm_driver.gem_prime_import_sg_table`](/kernel/hardware/gpu/drm-internals.md#c-struct-drm_driver) internally.

Drivers must arrange to call [`drm_prime_gem_destroy()`](#c-drm_prime_gem_destroy) from their
[`drm_gem_object_funcs.free`](#c-struct-drm_gem_object_funcs) hook when using this function.

#### <a id="c-drm_gem_prime_import"></a>`drm_gem_prime_import()`

```c
struct drm_gem_object * drm_gem_prime_import(struct drm_device *dev, struct dma_buf *dma_buf)
```

helper library implementation of the import callback

**Parameters**

- `struct drm_device *dev`: drm_device to import into
- `struct dma_buf *dma_buf`: dma-buf object to import

**Description**

This is the implementation of the gem_prime_import functions for GEM drivers
using the PRIME helpers. Drivers can use this as their
[`drm_driver.gem_prime_import`](/kernel/hardware/gpu/drm-internals.md#c-struct-drm_driver) implementation. It is used as the default
implementation in [`drm_gem_prime_fd_to_handle()`](#c-drm_gem_prime_fd_to_handle).

Drivers must arrange to call [`drm_prime_gem_destroy()`](#c-drm_prime_gem_destroy) from their
[`drm_gem_object_funcs.free`](#c-struct-drm_gem_object_funcs) hook when using this function.

#### <a id="c-drm_prime_sg_to_page_array"></a>`drm_prime_sg_to_page_array()`

```c
int drm_prime_sg_to_page_array(struct sg_table *sgt, struct page **pages, int max_entries)
```

convert an sg table into a page array

**Parameters**

- `struct sg_table *sgt`: scatter-gather table to convert
- `struct page **pages`: array of page pointers to store the pages in
- `int max_entries`: size of the passed-in array

**Description**

Exports an sg table into an array of pages.

This function is deprecated and strongly discouraged to be used.
The page array is only useful for page faults and those can corrupt fields
in the struct page if they are not handled by the exporting driver.

#### <a id="c-drm_prime_sg_to_dma_addr_array"></a>`drm_prime_sg_to_dma_addr_array()`

```c
int drm_prime_sg_to_dma_addr_array(struct sg_table *sgt, dma_addr_t *addrs, int max_entries)
```

convert an sg table into a dma addr array

**Parameters**

- `struct sg_table *sgt`: scatter-gather table to convert
- `dma_addr_t *addrs`: array to store the dma bus address of each page
- `int max_entries`: size of both the passed-in arrays

**Description**

Exports an sg table into an array of addresses.

Drivers should use this in their [`drm_driver.gem_prime_import_sg_table`](/kernel/hardware/gpu/drm-internals.md#c-struct-drm_driver)
implementation.

#### <a id="c-drm_prime_gem_destroy"></a>`drm_prime_gem_destroy()`

```c
void drm_prime_gem_destroy(struct drm_gem_object *obj, struct sg_table *sg)
```

helper to clean up a PRIME-imported GEM object

**Parameters**

- `struct drm_gem_object *obj`: GEM object which was created from a dma-buf
- `struct sg_table *sg`: the sg-table which was pinned at import time

**Description**

This is the cleanup functions which GEM drivers need to call when they use
[`drm_gem_prime_import()`](#c-drm_gem_prime_import) or [`drm_gem_prime_import_dev()`](#c-drm_gem_prime_import_dev) to import dma-bufs.


<a id="rst-drm-mm-range-allocator"></a>

## DRM MM Range Allocator

<a id="rst-overview"></a>

### Overview


drm_mm provides a simple range allocator. The drivers are free to use the
resource allocator from the linux core if it suits them, the upside of drm_mm
is that it's in the DRM core. Which means that it's easier to extend for
some of the crazier special purpose needs of gpus.

The main data struct is [`drm_mm`](#c-struct-drm_mm), allocations are tracked in [`drm_mm_node`](#c-struct-drm_mm_node).
Drivers are free to embed either of them into their own suitable
datastructures. drm_mm itself will not do any memory allocations of its own,
so if drivers choose not to embed nodes they need to still allocate them
themselves.

The range allocator also supports reservation of preallocated blocks. This is
useful for taking over initial mode setting configurations from the firmware,
where an object needs to be created which exactly matches the firmware's
scanout target. As long as the range is still free it can be inserted anytime
after the allocator is initialized, which helps with avoiding looped
dependencies in the driver load sequence.

drm_mm maintains a stack of most recently freed holes, which of all
simplistic datastructures seems to be a fairly decent approach to clustering
allocations and avoiding too much fragmentation. This means free space
searches are O(num_holes). Given that all the fancy features drm_mm supports
something better would be fairly complex and since gfx thrashing is a fairly
steep cliff not a real concern. Removing a node again is O(1).

drm_mm supports a few features: Alignment and range restrictions can be
supplied. Furthermore every [`drm_mm_node`](#c-struct-drm_mm_node) has a color value (which is just an
opaque unsigned long) which in conjunction with a driver callback can be used
to implement sophisticated placement restrictions. The i915 DRM driver uses
this to implement guard pages between incompatible caching domains in the
graphics TT.

Two behaviors are supported for searching and allocating: bottom-up and
top-down. The default is bottom-up. Top-down allocation can be used if the
memory area has different restrictions, or just to reduce fragmentation.

Finally iteration helpers to walk all nodes and all holes are provided as are
some basic allocator dumpers for debugging.

Note that this range allocator is not thread-safe, drivers need to protect
modifications with their own locking. The idea behind this is that for a full
memory manager additional data needs to be protected anyway, hence internal
locking would be fully redundant.


<a id="rst-lru-scan-eviction-support"></a>

### LRU Scan/Eviction Support


Very often GPUs need to have continuous allocations for a given object. When
evicting objects to make space for a new one it is therefore not most
efficient when we simply start to select all objects from the tail of an LRU
until there's a suitable hole: Especially for big objects or nodes that
otherwise have special allocation constraints there's a good chance we evict
lots of (smaller) objects unnecessarily.

The DRM range allocator supports this use-case through the scanning
interfaces. First a scan operation needs to be initialized with
[`drm_mm_scan_init()`](#c-drm_mm_scan_init) or [`drm_mm_scan_init_with_range()`](#c-drm_mm_scan_init_with_range). The driver adds
objects to the roster, probably by walking an LRU list, but this can be
freely implemented. Eviction candidates are added using
[`drm_mm_scan_add_block()`](#c-drm_mm_scan_add_block) until a suitable hole is found or there are no
further evictable objects. Eviction roster metadata is tracked in [`struct drm_mm_scan`](#c-struct-drm_mm_scan).

The driver must walk through all objects again in exactly the reverse
order to restore the allocator state. Note that while the allocator is used
in the scan mode no other operation is allowed.

Finally the driver evicts all objects selected ([`drm_mm_scan_remove_block()`](#c-drm_mm_scan_remove_block)
reported true) in the scan, and any overlapping nodes after color adjustment
([`drm_mm_scan_color_evict()`](#c-drm_mm_scan_color_evict)). Adding and removing an object is O(1), and
since freeing a node is also O(1) the overall complexity is
O(scanned_objects). So like the free stack which needs to be walked before a
scan operation even begins this is linear in the number of objects. It
doesn't seem to hurt too badly.


<a id="rst-drm-mm-range-allocator-function-references"></a>

### DRM MM Range Allocator Function References


#### <a id="c-enum-drm_mm_insert_mode"></a>`enum drm_mm_insert_mode`

control search and allocation behaviour

**Constants**

- `DRM_MM_INSERT_BEST`: Search for the smallest hole (within the search range) that fits
  the desired node.

  Allocates the node from the bottom of the found hole.
- `DRM_MM_INSERT_LOW`: Search for the lowest hole (address closest to 0, within the search
  range) that fits the desired node.

  Allocates the node from the bottom of the found hole.
- `DRM_MM_INSERT_HIGH`: Search for the highest hole (address closest to U64_MAX, within the
  search range) that fits the desired node.

  Allocates the node from the *top* of the found hole. The specified
  alignment for the node is applied to the base of the node
  ([`drm_mm_node.start`](#c-struct-drm_mm_node)).
- `DRM_MM_INSERT_EVICT`: Search for the most recently evicted hole (within the search range)
  that fits the desired node. This is appropriate for use immediately
  after performing an eviction scan (see [`drm_mm_scan_init()`](#c-drm_mm_scan_init)) and
  removing the selected nodes to form a hole.

  Allocates the node from the bottom of the found hole.
- `DRM_MM_INSERT_ONCE`: Only check the first hole for suitablity and report -ENOSPC
  immediately otherwise, rather than check every hole until a
  suitable one is found. Can only be used in conjunction with another
  search method such as DRM_MM_INSERT_HIGH or DRM_MM_INSERT_LOW.
- `DRM_MM_INSERT_HIGHEST`: Only check the highest hole (the hole with the largest address) and
  insert the node at the top of the hole or report -ENOSPC if
  unsuitable.

  Does not search all holes.
- `DRM_MM_INSERT_LOWEST`: Only check the lowest hole (the hole with the smallest address) and
  insert the node at the bottom of the hole or report -ENOSPC if
  unsuitable.

  Does not search all holes.

**Description**

The [`struct drm_mm`](#c-struct-drm_mm) range manager supports finding a suitable modes using
a number of search trees. These trees are oranised by size, by address and
in most recent eviction order. This allows the user to find either the
smallest hole to reuse, the lowest or highest address to reuse, or simply
reuse the most recent eviction that fits. When allocating the [`drm_mm_node`](#c-struct-drm_mm_node)
from within the hole, the [`drm_mm_insert_mode`](#c-enum-drm_mm_insert_mode) also dictate whether to
allocate the lowest matching address or the highest.

#### <a id="c-struct-drm_mm_node"></a>`struct drm_mm_node`

allocated block in the DRM allocator

**Definition**

```c
struct drm_mm_node {
    unsigned long color;
    u64 start;
    u64 size;
};
```

**Members**

- `color`: Opaque driver-private tag.
- `start`: Start address of the allocated block.
- `size`: Size of the allocated block.

**Description**

This represents an allocated block in a [`drm_mm`](#c-struct-drm_mm) allocator. Except for
pre-reserved nodes inserted using [`drm_mm_reserve_node()`](#c-drm_mm_reserve_node) the structure is
entirely opaque and should only be accessed through the provided funcions.
Since allocation of these nodes is entirely handled by the driver they can be
embedded.

#### <a id="c-struct-drm_mm"></a>`struct drm_mm`

DRM allocator

**Definition**

```c
struct drm_mm {
    void (*color_adjust)(const struct drm_mm_node *node, unsigned long color, u64 *start, u64 *end);
};
```

**Members**

- `color_adjust`: Optional driver callback to further apply restrictions on a hole. The
  node argument points at the node containing the hole from which the
  block would be allocated (see [`drm_mm_hole_follows()`](#c-drm_mm_hole_follows) and friends). The
  other arguments are the size of the block to be allocated. The driver
  can adjust the start and end as needed to e.g. insert guard pages.

**Description**

DRM range allocator with a few special functions and features geared towards
managing GPU memory. Except for the **color_adjust** callback the structure is
entirely opaque and should only be accessed through the provided functions
and macros. This structure can be embedded into larger driver structures.

#### <a id="c-struct-drm_mm_scan"></a>`struct drm_mm_scan`

DRM allocator eviction roaster data

**Definition**

```c
struct drm_mm_scan {
};
```

**Description**

This structure tracks data needed for the eviction roaster set up using
[`drm_mm_scan_init()`](#c-drm_mm_scan_init), and used with [`drm_mm_scan_add_block()`](#c-drm_mm_scan_add_block) and
[`drm_mm_scan_remove_block()`](#c-drm_mm_scan_remove_block). The structure is entirely opaque and should only
be accessed through the provided functions and macros. It is meant to be
allocated temporarily by the driver on the stack.

#### <a id="c-drm_mm_node_allocated"></a>`drm_mm_node_allocated()`

```c
bool drm_mm_node_allocated(const struct drm_mm_node *node)
```

checks whether a node is allocated

**Parameters**

- `const struct drm_mm_node *node`: drm_mm_node to check

**Description**

Drivers are required to clear a node prior to using it with the
drm_mm range manager.

Drivers should use this helper for proper encapsulation of drm_mm
internals.

**Return**

True if the **node** is allocated.

#### <a id="c-drm_mm_initialized"></a>`drm_mm_initialized()`

```c
bool drm_mm_initialized(const struct drm_mm *mm)
```

checks whether an allocator is initialized

**Parameters**

- `const struct drm_mm *mm`: drm_mm to check

**Description**

Drivers should clear the struct drm_mm prior to initialisation if they
want to use this function.

Drivers should use this helper for proper encapsulation of drm_mm
internals.

**Return**

True if the **mm** is initialized.

#### <a id="c-drm_mm_hole_follows"></a>`drm_mm_hole_follows()`

```c
bool drm_mm_hole_follows(const struct drm_mm_node *node)
```

checks whether a hole follows this node

**Parameters**

- `const struct drm_mm_node *node`: drm_mm_node to check

**Description**

Holes are embedded into the drm_mm using the tail of a drm_mm_node.
If you wish to know whether a hole follows this particular node,
query this function. See also [`drm_mm_hole_node_start()`](#c-drm_mm_hole_node_start) and
[`drm_mm_hole_node_end()`](#c-drm_mm_hole_node_end).

**Return**

True if a hole follows the **node**.

#### <a id="c-drm_mm_hole_node_start"></a>`drm_mm_hole_node_start()`

```c
u64 drm_mm_hole_node_start(const struct drm_mm_node *hole_node)
```

computes the start of the hole following **node**

**Parameters**

- `const struct drm_mm_node *hole_node`: drm_mm_node which implicitly tracks the following hole

**Description**

This is useful for driver-specific debug dumpers. Otherwise drivers should
not inspect holes themselves. Drivers must check first whether a hole indeed
follows by looking at [`drm_mm_hole_follows()`](#c-drm_mm_hole_follows)

**Return**

Start of the subsequent hole.

#### <a id="c-drm_mm_hole_node_end"></a>`drm_mm_hole_node_end()`

```c
u64 drm_mm_hole_node_end(const struct drm_mm_node *hole_node)
```

computes the end of the hole following **node**

**Parameters**

- `const struct drm_mm_node *hole_node`: drm_mm_node which implicitly tracks the following hole

**Description**

This is useful for driver-specific debug dumpers. Otherwise drivers should
not inspect holes themselves. Drivers must check first whether a hole indeed
follows by looking at [`drm_mm_hole_follows()`](#c-drm_mm_hole_follows).

**Return**

End of the subsequent hole.

#### <a id="c-drm_mm_nodes"></a>`drm_mm_nodes()`

```c
drm_mm_nodes(mm)
```

list of nodes under the drm_mm range manager

**Parameters**

- `mm`: the struct drm_mm range manager

**Description**

As the drm_mm range manager hides its node_list deep with its
structure, extracting it looks painful and repetitive. This is
not expected to be used outside of the [`drm_mm_for_each_node()`](#c-drm_mm_for_each_node)
macros and similar internal functions.

**Return**

The node list, may be empty.

#### <a id="c-drm_mm_for_each_node"></a>`drm_mm_for_each_node()`

```c
drm_mm_for_each_node(entry, mm)
```

iterator to walk over all allocated nodes

**Parameters**

- `entry`: [`struct drm_mm_node`](#c-struct-drm_mm_node) to assign to in each iteration step
- `mm`: [`drm_mm`](#c-struct-drm_mm) allocator to walk

**Description**

This iterator walks over all nodes in the range allocator. It is implemented
with [`list_for_each()`](/kernel/internals/core-api/list.md#c-list_for_each), so not save against removal of elements.

#### <a id="c-drm_mm_for_each_node_safe"></a>`drm_mm_for_each_node_safe()`

```c
drm_mm_for_each_node_safe(entry, next, mm)
```

iterator to walk over all allocated nodes

**Parameters**

- `entry`: [`struct drm_mm_node`](#c-struct-drm_mm_node) to assign to in each iteration step
- `next`: [`struct drm_mm_node`](#c-struct-drm_mm_node) to store the next step
- `mm`: [`drm_mm`](#c-struct-drm_mm) allocator to walk

**Description**

This iterator walks over all nodes in the range allocator. It is implemented
with [`list_for_each_safe()`](/kernel/internals/core-api/list.md#c-list_for_each_safe), so save against removal of elements.

#### <a id="c-drm_mm_for_each_hole"></a>`drm_mm_for_each_hole()`

```c
drm_mm_for_each_hole(pos, mm, hole_start, hole_end)
```

iterator to walk over all holes

**Parameters**

- `pos`: [`drm_mm_node`](#c-struct-drm_mm_node) used internally to track progress
- `mm`: [`drm_mm`](#c-struct-drm_mm) allocator to walk
- `hole_start`: ulong variable to assign the hole start to on each iteration
- `hole_end`: ulong variable to assign the hole end to on each iteration

**Description**

This iterator walks over all holes in the range allocator. It is implemented
with [`list_for_each()`](/kernel/internals/core-api/list.md#c-list_for_each), so not save against removal of elements. **entry** is used
internally and will not reflect a real drm_mm_node for the very first hole.
Hence users of this iterator may not access it.

Implementation Note:
We need to inline list_for_each_entry in order to be able to set hole_start
and hole_end on each iteration while keeping the macro sane.

#### <a id="c-drm_mm_insert_node_generic"></a>`drm_mm_insert_node_generic()`

```c
int drm_mm_insert_node_generic(struct drm_mm *mm, struct drm_mm_node *node, u64 size, u64 alignment, unsigned long color, enum drm_mm_insert_mode mode)
```

search for space and insert **node**

**Parameters**

- `struct drm_mm *mm`: drm_mm to allocate from
- `struct drm_mm_node *node`: preallocate node to insert
- `u64 size`: size of the allocation
- `u64 alignment`: alignment of the allocation
- `unsigned long color`: opaque tag value to use for this node
- `enum drm_mm_insert_mode mode`: fine-tune the allocation search and placement

**Description**

This is a simplified version of [`drm_mm_insert_node_in_range()`](#c-drm_mm_insert_node_in_range) with no
range restrictions applied.

The preallocated node must be cleared to 0.

**Return**

0 on success, -ENOSPC if there's no suitable hole.

#### <a id="c-drm_mm_insert_node"></a>`drm_mm_insert_node()`

```c
int drm_mm_insert_node(struct drm_mm *mm, struct drm_mm_node *node, u64 size)
```

search for space and insert **node**

**Parameters**

- `struct drm_mm *mm`: drm_mm to allocate from
- `struct drm_mm_node *node`: preallocate node to insert
- `u64 size`: size of the allocation

**Description**

This is a simplified version of [`drm_mm_insert_node_generic()`](#c-drm_mm_insert_node_generic) with **color** set
to 0.

The preallocated node must be cleared to 0.

**Return**

0 on success, -ENOSPC if there's no suitable hole.

#### <a id="c-drm_mm_clean"></a>`drm_mm_clean()`

```c
bool drm_mm_clean(const struct drm_mm *mm)
```

checks whether an allocator is clean

**Parameters**

- `const struct drm_mm *mm`: drm_mm allocator to check

**Return**

True if the allocator is completely free, false if there's still a node
allocated in it.

#### <a id="c-drm_mm_for_each_node_in_range"></a>`drm_mm_for_each_node_in_range()`

```c
drm_mm_for_each_node_in_range(node__, mm__, start__, end__)
```

iterator to walk over a range of allocated nodes

**Parameters**

- `node__`: drm_mm_node structure to assign to in each iteration step
- `mm__`: drm_mm allocator to walk
- `start__`: starting offset, the first node will overlap this
- `end__`: ending offset, the last node will start before this (but may overlap)

**Description**

This iterator walks over all nodes in the range allocator that lie
between **start** and **end**. It is implemented similarly to [`list_for_each()`](/kernel/internals/core-api/list.md#c-list_for_each),
but using the internal interval tree to accelerate the search for the
starting node, and so not safe against removal of elements. It assumes
that **end** is within (or is the upper limit of) the drm_mm allocator.
If \[**start**, **end**\] are beyond the range of the drm_mm, the iterator may walk
over the special _unallocated_ [`drm_mm.head_node`](#c-struct-drm_mm), and may even continue
indefinitely.

#### <a id="c-drm_mm_scan_init"></a>`drm_mm_scan_init()`

```c
void drm_mm_scan_init(struct drm_mm_scan *scan, struct drm_mm *mm, u64 size, u64 alignment, unsigned long color, enum drm_mm_insert_mode mode)
```

initialize lru scanning

**Parameters**

- `struct drm_mm_scan *scan`: scan state
- `struct drm_mm *mm`: drm_mm to scan
- `u64 size`: size of the allocation
- `u64 alignment`: alignment of the allocation
- `unsigned long color`: opaque tag value to use for the allocation
- `enum drm_mm_insert_mode mode`: fine-tune the allocation search and placement

**Description**

This is a simplified version of [`drm_mm_scan_init_with_range()`](#c-drm_mm_scan_init_with_range) with no range
restrictions applied.

This simply sets up the scanning routines with the parameters for the desired
hole.

Warning:
As long as the scan list is non-empty, no other operations than
adding/removing nodes to/from the scan list are allowed.



#### <a id="c-drm_mm_reserve_node"></a>`drm_mm_reserve_node()`

```c
int drm_mm_reserve_node(struct drm_mm *mm, struct drm_mm_node *node)
```

insert an pre-initialized node

**Parameters**

- `struct drm_mm *mm`: drm_mm allocator to insert **node** into
- `struct drm_mm_node *node`: drm_mm_node to insert

**Description**

This functions inserts an already set-up [`drm_mm_node`](#c-struct-drm_mm_node) into the allocator,
meaning that start, size and color must be set by the caller. All other
fields must be cleared to 0. This is useful to initialize the allocator with
preallocated objects which must be set-up before the range allocator can be
set-up, e.g. when taking over a firmware framebuffer.

**Return**

0 on success, -ENOSPC if there's no hole where **node** is.

#### <a id="c-drm_mm_insert_node_in_range"></a>`drm_mm_insert_node_in_range()`

```c
int drm_mm_insert_node_in_range(struct drm_mm * const mm, struct drm_mm_node * const node, u64 size, u64 alignment, unsigned long color, u64 range_start, u64 range_end, enum drm_mm_insert_mode mode)
```

ranged search for space and insert **node**

**Parameters**

- `struct drm_mm * const mm`: drm_mm to allocate from
- `struct drm_mm_node * const node`: preallocate node to insert
- `u64 size`: size of the allocation
- `u64 alignment`: alignment of the allocation
- `unsigned long color`: opaque tag value to use for this node
- `u64 range_start`: start of the allowed range for this node
- `u64 range_end`: end of the allowed range for this node
- `enum drm_mm_insert_mode mode`: fine-tune the allocation search and placement

**Description**

The preallocated **node** must be cleared to 0.

**Return**

0 on success, -ENOSPC if there's no suitable hole.

#### <a id="c-drm_mm_remove_node"></a>`drm_mm_remove_node()`

```c
void drm_mm_remove_node(struct drm_mm_node *node)
```

Remove a memory node from the allocator.

**Parameters**

- `struct drm_mm_node *node`: drm_mm_node to remove

**Description**

This just removes a node from its drm_mm allocator. The node does not need to
be cleared again before it can be re-inserted into this or any other drm_mm
allocator. It is a bug to call this function on a unallocated node.

#### <a id="c-drm_mm_scan_init_with_range"></a>`drm_mm_scan_init_with_range()`

```c
void drm_mm_scan_init_with_range(struct drm_mm_scan *scan, struct drm_mm *mm, u64 size, u64 alignment, unsigned long color, u64 start, u64 end, enum drm_mm_insert_mode mode)
```

initialize range-restricted lru scanning

**Parameters**

- `struct drm_mm_scan *scan`: scan state
- `struct drm_mm *mm`: drm_mm to scan
- `u64 size`: size of the allocation
- `u64 alignment`: alignment of the allocation
- `unsigned long color`: opaque tag value to use for the allocation
- `u64 start`: start of the allowed range for the allocation
- `u64 end`: end of the allowed range for the allocation
- `enum drm_mm_insert_mode mode`: fine-tune the allocation search and placement

**Description**

This simply sets up the scanning routines with the parameters for the desired
hole.

Warning:
As long as the scan list is non-empty, no other operations than
adding/removing nodes to/from the scan list are allowed.

#### <a id="c-drm_mm_scan_add_block"></a>`drm_mm_scan_add_block()`

```c
bool drm_mm_scan_add_block(struct drm_mm_scan *scan, struct drm_mm_node *node)
```

add a node to the scan list

**Parameters**

- `struct drm_mm_scan *scan`: the active drm_mm scanner
- `struct drm_mm_node *node`: drm_mm_node to add

**Description**

Add a node to the scan list that might be freed to make space for the desired
hole.

**Return**

True if a hole has been found, false otherwise.

#### <a id="c-drm_mm_scan_remove_block"></a>`drm_mm_scan_remove_block()`

```c
bool drm_mm_scan_remove_block(struct drm_mm_scan *scan, struct drm_mm_node *node)
```

remove a node from the scan list

**Parameters**

- `struct drm_mm_scan *scan`: the active drm_mm scanner
- `struct drm_mm_node *node`: drm_mm_node to remove

**Description**

Nodes **must** be removed in exactly the reverse order from the scan list as
they have been added (e.g. using [`list_add()`](/kernel/internals/core-api/list.md#c-list_add) as they are added and then
[`list_for_each()`](/kernel/internals/core-api/list.md#c-list_for_each) over that eviction list to remove), otherwise the internal
state of the memory manager will be corrupted.

When the scan list is empty, the selected memory nodes can be freed. An
immediately following `drm_mm_insert_node_in_range_generic()` or one of the
simpler versions of that function with !DRM_MM_SEARCH_BEST will then return
the just freed block (because it's at the top of the free_stack list).

**Return**

True if this block should be evicted, false otherwise. Will always
return false when no hole has been found.

#### <a id="c-drm_mm_scan_color_evict"></a>`drm_mm_scan_color_evict()`

```c
struct drm_mm_node * drm_mm_scan_color_evict(struct drm_mm_scan *scan)
```

evict overlapping nodes on either side of hole

**Parameters**

- `struct drm_mm_scan *scan`: drm_mm scan with target hole

**Description**

After completing an eviction scan and removing the selected nodes, we may
need to remove a few more nodes from either side of the target hole if
mm.color_adjust is being used.

**Return**

A node to evict, or NULL if there are no overlapping nodes.

#### <a id="c-drm_mm_init"></a>`drm_mm_init()`

```c
void drm_mm_init(struct drm_mm *mm, u64 start, u64 size)
```

initialize a drm-mm allocator

**Parameters**

- `struct drm_mm *mm`: the drm_mm structure to initialize
- `u64 start`: start of the range managed by **mm**
- `u64 size`: end of the range managed by **mm**

**Description**

Note that **mm** must be cleared to 0 before calling this function.

#### <a id="c-drm_mm_takedown"></a>`drm_mm_takedown()`

```c
void drm_mm_takedown(struct drm_mm *mm)
```

clean up a drm_mm allocator

**Parameters**

- `struct drm_mm *mm`: drm_mm allocator to clean up

**Description**

Note that it is a bug to call this function on an allocator which is not
clean.

#### <a id="c-drm_mm_print"></a>`drm_mm_print()`

```c
void drm_mm_print(const struct drm_mm *mm, struct drm_printer *p)
```

print allocator state

**Parameters**

- `const struct drm_mm *mm`: drm_mm allocator to print
- `struct drm_printer *p`: DRM printer to use


<a id="rst-drm-gpuvm-1"></a>
<a id="rst-drm-gpuvm"></a>

## DRM GPUVM

<a id="rst-overview-1"></a>

### Overview


The DRM GPU VA Manager, represented by struct drm_gpuvm keeps track of a
GPU's virtual address (VA) space and manages the corresponding virtual
mappings represented by [`drm_gpuva`](#c-struct-drm_gpuva) objects. It also keeps track of the
mapping's backing [`drm_gem_object`](#c-struct-drm_gem_object) buffers.

[`drm_gem_object`](#c-struct-drm_gem_object) buffers maintain a list of [`drm_gpuva`](#c-struct-drm_gpuva) objects representing
all existing GPU VA mappings using this [`drm_gem_object`](#c-struct-drm_gem_object) as backing buffer.

GPU VAs can be flagged as sparse, such that drivers may use GPU VAs to also
keep track of sparse PTEs in order to support Vulkan 'Sparse Resources'.

The GPU VA manager internally uses a rb-tree to manage the
[`drm_gpuva`](#c-struct-drm_gpuva) mappings within a GPU's virtual address space.

The [`drm_gpuvm`](#c-struct-drm_gpuvm) structure contains a special [`drm_gpuva`](#c-struct-drm_gpuva) representing the
portion of VA space reserved by the kernel. This node is initialized together
with the GPU VA manager instance and removed when the GPU VA manager is
destroyed.

In a typical application drivers would embed struct drm_gpuvm and
struct drm_gpuva within their own driver specific structures, there won't be
any memory allocations of its own nor memory allocations of [`drm_gpuva`](#c-struct-drm_gpuva)
entries.

The data structures needed to store `drm_gpuvas` within the [`drm_gpuvm`](#c-struct-drm_gpuvm) are
contained within struct drm_gpuva already. Hence, for inserting [`drm_gpuva`](#c-struct-drm_gpuva)
entries from within dma-fence signalling critical sections it is enough to
pre-allocate the [`drm_gpuva`](#c-struct-drm_gpuva) structures.

`drm_gem_objects` which are private to a single VM can share a common
[`dma_resv`](/kernel/hardware/driver-api/io-and-dma/dma-buf.md#c-struct-dma_resv) in order to improve locking efficiency (e.g. with [`drm_exec`](#c-struct-drm_exec)).
For this purpose drivers must pass a [`drm_gem_object`](#c-struct-drm_gem_object) to [`drm_gpuvm_init()`](#c-drm_gpuvm_init), in
the following called 'resv object', which serves as the container of the
GPUVM's shared [`dma_resv`](/kernel/hardware/driver-api/io-and-dma/dma-buf.md#c-struct-dma_resv). This resv object can be a driver specific
[`drm_gem_object`](#c-struct-drm_gem_object), such as the [`drm_gem_object`](#c-struct-drm_gem_object) containing the root page table,
but it can also be a 'dummy' object, which can be allocated with
[`drm_gpuvm_resv_object_alloc()`](#c-drm_gpuvm_resv_object_alloc).

In order to connect a struct drm_gpuva to its backing [`drm_gem_object`](#c-struct-drm_gem_object) each
[`drm_gem_object`](#c-struct-drm_gem_object) maintains a list of [`drm_gpuvm_bo`](#c-struct-drm_gpuvm_bo) structures, and each
[`drm_gpuvm_bo`](#c-struct-drm_gpuvm_bo) contains a list of [`drm_gpuva`](#c-struct-drm_gpuva) structures.

A [`drm_gpuvm_bo`](#c-struct-drm_gpuvm_bo) is an abstraction that represents a combination of a
[`drm_gpuvm`](#c-struct-drm_gpuvm) and a [`drm_gem_object`](#c-struct-drm_gem_object). Every such combination should be unique.
This is ensured by the API through `drm_gpuvm_bo_obtain()` and
[`drm_gpuvm_bo_obtain_prealloc()`](#c-drm_gpuvm_bo_obtain_prealloc) which first look into the corresponding
[`drm_gem_object`](#c-struct-drm_gem_object) list of `drm_gpuvm_bos` for an existing instance of this
particular combination. If not present, a new instance is created and linked
to the [`drm_gem_object`](#c-struct-drm_gem_object).

[`drm_gpuvm_bo`](#c-struct-drm_gpuvm_bo) structures, since unique for a given [`drm_gpuvm`](#c-struct-drm_gpuvm), are also used
as entry for the [`drm_gpuvm`](#c-struct-drm_gpuvm)'s lists of external and evicted objects. Those
lists are maintained in order to accelerate locking of dma-resv locks and
validation of evicted objects bound in a [`drm_gpuvm`](#c-struct-drm_gpuvm). For instance, all
[`drm_gem_object`](#c-struct-drm_gem_object)'s [`dma_resv`](/kernel/hardware/driver-api/io-and-dma/dma-buf.md#c-struct-dma_resv) of a given [`drm_gpuvm`](#c-struct-drm_gpuvm) can be locked by calling
[`drm_gpuvm_exec_lock()`](#c-drm_gpuvm_exec_lock). Once locked drivers can call [`drm_gpuvm_validate()`](#c-drm_gpuvm_validate) in
order to validate all evicted `drm_gem_objects`. It is also possible to lock
additional `drm_gem_objects` by providing the corresponding parameters to
[`drm_gpuvm_exec_lock()`](#c-drm_gpuvm_exec_lock) as well as open code the [`drm_exec`](#c-struct-drm_exec) loop while making
use of helper functions such as [`drm_gpuvm_prepare_range()`](#c-drm_gpuvm_prepare_range) or
[`drm_gpuvm_prepare_objects()`](#c-drm_gpuvm_prepare_objects).

Every bound [`drm_gem_object`](#c-struct-drm_gem_object) is treated as external object when its [`dma_resv`](/kernel/hardware/driver-api/io-and-dma/dma-buf.md#c-struct-dma_resv)
structure is different than the [`drm_gpuvm`](#c-struct-drm_gpuvm)'s common [`dma_resv`](/kernel/hardware/driver-api/io-and-dma/dma-buf.md#c-struct-dma_resv) structure.


<a id="rst-split-and-merge"></a>

### Split and Merge


Besides its capability to manage and represent a GPU VA space, the
GPU VA manager also provides functions to let the [`drm_gpuvm`](#c-struct-drm_gpuvm) calculate a
sequence of operations to satisfy a given map or unmap request.

Therefore the DRM GPU VA manager provides an algorithm implementing splitting
and merging of existing GPU VA mappings with the ones that are requested to
be mapped or unmapped. This feature is required by the Vulkan API to
implement Vulkan 'Sparse Memory Bindings' - drivers UAPIs often refer to this
as VM BIND.

Drivers can call [`drm_gpuvm_sm_map()`](#c-drm_gpuvm_sm_map) to receive a sequence of callbacks
containing map, unmap and remap operations for a given newly requested
mapping. The sequence of callbacks represents the set of operations to
execute in order to integrate the new mapping cleanly into the current state
of the GPU VA space.

Depending on how the new GPU VA mapping intersects with the existing mappings
of the GPU VA space the [`drm_gpuvm_ops`](#c-struct-drm_gpuvm_ops) callbacks contain an arbitrary amount
of unmap operations, a maximum of two remap operations and a single map
operation. The caller might receive no callback at all if no operation is
required, e.g. if the requested mapping already exists in the exact same way.

The single map operation represents the original map operation requested by
the caller.

[`drm_gpuva_op_unmap`](#c-struct-drm_gpuva_op_unmap) contains a 'keep' field, which indicates whether the
[`drm_gpuva`](#c-struct-drm_gpuva) to unmap is physically contiguous with the original mapping
request. Optionally, if 'keep' is set, drivers may keep the actual page table
entries for this [`drm_gpuva`](#c-struct-drm_gpuva), adding the missing page table entries only and
update the [`drm_gpuvm`](#c-struct-drm_gpuvm)'s view of things accordingly.

Drivers may do the same optimization, namely delta page table updates, also
for remap operations. This is possible since [`drm_gpuva_op_remap`](#c-struct-drm_gpuva_op_remap) consists of
one unmap operation and one or two map operations, such that drivers can
derive the page table update delta accordingly.

Note that there can't be more than two existing mappings to split up, one at
the beginning and one at the end of the new mapping, hence there is a
maximum of two remap operations.

Analogous to [`drm_gpuvm_sm_map()`](#c-drm_gpuvm_sm_map) [`drm_gpuvm_sm_unmap()`](#c-drm_gpuvm_sm_unmap) uses [`drm_gpuvm_ops`](#c-struct-drm_gpuvm_ops) to
call back into the driver in order to unmap a range of GPU VA space. The
logic behind this function is way simpler though: For all existing mappings
enclosed by the given range unmap operations are created. For mappings which
are only partially located within the given range, remap operations are
created such that those mappings are split up and re-mapped partially.

As an alternative to [`drm_gpuvm_sm_map()`](#c-drm_gpuvm_sm_map) and [`drm_gpuvm_sm_unmap()`](#c-drm_gpuvm_sm_unmap),
[`drm_gpuvm_sm_map_ops_create()`](#c-drm_gpuvm_sm_map_ops_create) and [`drm_gpuvm_sm_unmap_ops_create()`](#c-drm_gpuvm_sm_unmap_ops_create) can be used
to directly obtain an instance of struct drm_gpuva_ops containing a list of
[`drm_gpuva_op`](#c-struct-drm_gpuva_op), which can be iterated with [`drm_gpuva_for_each_op()`](#c-drm_gpuva_for_each_op). This list
contains the [`drm_gpuva_ops`](#c-struct-drm_gpuva_ops) analogous to the callbacks one would receive when
calling [`drm_gpuvm_sm_map()`](#c-drm_gpuvm_sm_map) or [`drm_gpuvm_sm_unmap()`](#c-drm_gpuvm_sm_unmap). While this way requires
more memory (to allocate the [`drm_gpuva_ops`](#c-struct-drm_gpuva_ops)), it provides drivers a way to
iterate the [`drm_gpuva_op`](#c-struct-drm_gpuva_op) multiple times, e.g. once in a context where memory
allocations are possible (e.g. to allocate GPU page tables) and once in the
dma-fence signalling critical path.

To update the [`drm_gpuvm`](#c-struct-drm_gpuvm)'s view of the GPU VA space [`drm_gpuva_insert()`](#c-drm_gpuva_insert) and
[`drm_gpuva_remove()`](#c-drm_gpuva_remove) may be used. These functions can safely be used from
[`drm_gpuvm_ops`](#c-struct-drm_gpuvm_ops) callbacks originating from [`drm_gpuvm_sm_map()`](#c-drm_gpuvm_sm_map) or
[`drm_gpuvm_sm_unmap()`](#c-drm_gpuvm_sm_unmap). However, it might be more convenient to use the
provided helper functions [`drm_gpuva_map()`](#c-drm_gpuva_map), [`drm_gpuva_remap()`](#c-drm_gpuva_remap) and
[`drm_gpuva_unmap()`](#c-drm_gpuva_unmap) instead.

The following diagram depicts the basic relationships of existing GPU VA
mappings, a newly requested mapping and the resulting mappings as implemented
by [`drm_gpuvm_sm_map()`](#c-drm_gpuvm_sm_map) - it doesn't cover any arbitrary combinations of these.

1) Requested mapping is identical. Replace it, but indicate the backing PTEs
   could be kept.

```text
     0     a     1
old: |-----------| (bo_offset=n)

     0     a     1
req: |-----------| (bo_offset=n)

     0     a     1
new: |-----------| (bo_offset=n)
```

2) Requested mapping is identical, except for the BO offset, hence replace
   the mapping.

```text
     0     a     1
old: |-----------| (bo_offset=n)

     0     a     1
req: |-----------| (bo_offset=m)

     0     a     1
new: |-----------| (bo_offset=m)
```

3) Requested mapping is identical, except for the backing BO, hence replace
   the mapping.

```text
     0     a     1
old: |-----------| (bo_offset=n)

     0     b     1
req: |-----------| (bo_offset=n)

     0     b     1
new: |-----------| (bo_offset=n)
```

4) Existent mapping is a left aligned subset of the requested one, hence
   replace the existing one.

```text
     0  a  1
old: |-----|       (bo_offset=n)

     0     a     2
req: |-----------| (bo_offset=n)

     0     a     2
new: |-----------| (bo_offset=n)
```

> [!NOTE]
> We expect to see the same result for a request with a different BO
> and/or non-contiguous BO offset.

5) Requested mapping's range is a left aligned subset of the existing one,
   but backed by a different BO. Hence, map the requested mapping and split
   the existing one adjusting its BO offset.

```text
     0     a     2
old: |-----------| (bo_offset=n)

     0  b  1
req: |-----|       (bo_offset=n)

     0  b  1  a' 2
new: |-----|-----| (b.bo_offset=n, a.bo_offset=n+1)
```

> [!NOTE]
> We expect to see the same result for a request with a different BO
> and/or non-contiguous BO offset.

6) Existent mapping is a superset of the requested mapping. Split it up, but
   indicate that the backing PTEs could be kept.

```text
     0     a     2
old: |-----------| (bo_offset=n)

     0  a  1
req: |-----|       (bo_offset=n)

     0  a  1  a' 2
new: |-----|-----| (a.bo_offset=n, a'.bo_offset=n+1)
```

7) Requested mapping's range is a right aligned subset of the existing one,
   but backed by a different BO. Hence, map the requested mapping and split
   the existing one, without adjusting the BO offset.

```text
     0     a     2
old: |-----------| (bo_offset=n)

           1  b  2
req:       |-----| (bo_offset=m)

     0  a  1  b  2
new: |-----|-----| (a.bo_offset=n,b.bo_offset=m)
```

8) Existent mapping is a superset of the requested mapping. Split it up, but
   indicate that the backing PTEs could be kept.

```text
      0     a     2
old: |-----------| (bo_offset=n)

           1  a  2
req:       |-----| (bo_offset=n+1)

     0  a' 1  a  2
new: |-----|-----| (a'.bo_offset=n, a.bo_offset=n+1)
```

9) Existent mapping is overlapped at the end by the requested mapping backed
   by a different BO. Hence, map the requested mapping and split up the
   existing one, without adjusting the BO offset.

```text
     0     a     2
old: |-----------|       (bo_offset=n)

           1     b     3
req:       |-----------| (bo_offset=m)

     0  a  1     b     3
new: |-----|-----------| (a.bo_offset=n,b.bo_offset=m)
```

10) Existent mapping is overlapped by the requested mapping, both having the
    same backing BO with a contiguous offset. Indicate the backing PTEs of
    the old mapping could be kept.

```text
     0     a     2
old: |-----------|       (bo_offset=n)

           1     a     3
req:       |-----------| (bo_offset=n+1)

     0  a' 1     a     3
new: |-----|-----------| (a'.bo_offset=n, a.bo_offset=n+1)
```

11) Requested mapping's range is a centered subset of the existing one
    having a different backing BO. Hence, map the requested mapping and split
    up the existing one in two mappings, adjusting the BO offset of the right
    one accordingly.

```text
     0        a        3
old: |-----------------| (bo_offset=n)

           1  b  2
req:       |-----|       (bo_offset=m)

     0  a  1  b  2  a' 3
new: |-----|-----|-----| (a.bo_offset=n,b.bo_offset=m,a'.bo_offset=n+2)
```

12) Requested mapping is a contiguous subset of the existing one. Split it
    up, but indicate that the backing PTEs could be kept.

```text
     0        a        3
old: |-----------------| (bo_offset=n)

           1  a  2
req:       |-----|       (bo_offset=n+1)

     0  a' 1  a  2 a'' 3
old: |-----|-----|-----| (a'.bo_offset=n, a.bo_offset=n+1, a''.bo_offset=n+2)
```

13) Existent mapping is a right aligned subset of the requested one, hence
    replace the existing one.

```text
           1  a  2
old:       |-----| (bo_offset=n+1)

     0     a     2
req: |-----------| (bo_offset=n)

     0     a     2
new: |-----------| (bo_offset=n)
```

> [!NOTE]
> We expect to see the same result for a request with a different bo
> and/or non-contiguous bo_offset.

14) Existent mapping is a centered subset of the requested one, hence
    replace the existing one.

```text
           1  a  2
old:       |-----| (bo_offset=n+1)

     0        a       3
req: |----------------| (bo_offset=n)

     0        a       3
new: |----------------| (bo_offset=n)
```

> [!NOTE]
> We expect to see the same result for a request with a different bo
> and/or non-contiguous bo_offset.

15) Existent mappings is overlapped at the beginning by the requested mapping
    backed by a different BO. Hence, map the requested mapping and split up
    the existing one, adjusting its BO offset accordingly.

```text
           1     a     3
old:       |-----------| (bo_offset=n)

     0     b     2
req: |-----------|       (bo_offset=m)

     0     b     2  a' 3
new: |-----------|-----| (b.bo_offset=m,a.bo_offset=n+2)
```


<a id="rst-locking"></a>
<a id="rst-drm-gpuvm-locking"></a>

### Locking


In terms of managing [`drm_gpuva`](#c-struct-drm_gpuva) entries DRM GPUVM does not take care of
locking itself, it is the drivers responsibility to take care about locking.
Drivers might want to protect the following operations: inserting, removing
and iterating [`drm_gpuva`](#c-struct-drm_gpuva) objects as well as generating all kinds of
operations, such as split / merge or prefetch.

DRM GPUVM also does not take care of the locking of the backing
[`drm_gem_object`](#c-struct-drm_gem_object) buffers GPU VA lists and [`drm_gpuvm_bo`](#c-struct-drm_gpuvm_bo) abstractions by
itself; drivers are responsible to enforce mutual exclusion using either the
GEMs dma_resv lock or the GEMs gpuva.lock mutex.

However, DRM GPUVM contains lockdep checks to ensure callers of its API hold
the corresponding lock whenever the `drm_gem_objects` GPU VA list is accessed
by functions such as [`drm_gpuva_link()`](#c-drm_gpuva_link) or [`drm_gpuva_unlink()`](#c-drm_gpuva_unlink), but also
`drm_gpuvm_bo_obtain()` and [`drm_gpuvm_bo_put()`](#c-drm_gpuvm_bo_put).

The latter is required since on creation and destruction of a [`drm_gpuvm_bo`](#c-struct-drm_gpuvm_bo)
the [`drm_gpuvm_bo`](#c-struct-drm_gpuvm_bo) is attached / removed from the `drm_gem_objects` gpuva list.
Subsequent calls to `drm_gpuvm_bo_obtain()` for the same [`drm_gpuvm`](#c-struct-drm_gpuvm) and
[`drm_gem_object`](#c-struct-drm_gem_object) must be able to observe previous creations and destructions
of `drm_gpuvm_bos` in order to keep instances unique.

The [`drm_gpuvm`](#c-struct-drm_gpuvm)'s lists for keeping track of external and evicted objects are
protected against concurrent insertion / removal and iteration internally.

However, drivers still need ensure to protect concurrent calls to functions
iterating those lists, namely [`drm_gpuvm_prepare_objects()`](#c-drm_gpuvm_prepare_objects) and
[`drm_gpuvm_validate()`](#c-drm_gpuvm_validate).

Alternatively, drivers can set the `DRM_GPUVM_RESV_PROTECTED` flag to indicate
that the corresponding [`dma_resv`](/kernel/hardware/driver-api/io-and-dma/dma-buf.md#c-struct-dma_resv) locks are held in order to protect the
lists. If `DRM_GPUVM_RESV_PROTECTED` is set, internal locking is disabled and
the corresponding lockdep checks are enabled. This is an optimization for
drivers which are capable of taking the corresponding [`dma_resv`](/kernel/hardware/driver-api/io-and-dma/dma-buf.md#c-struct-dma_resv) locks and
hence do not require internal locking.


<a id="rst-examples"></a>

### Examples


This section gives two examples on how to let the DRM GPUVA Manager generate
[`drm_gpuva_op`](#c-struct-drm_gpuva_op) in order to satisfy a given map or unmap request and how to
make use of them.

The below code is strictly limited to illustrate the generic usage pattern.
To maintain simplicity, it doesn't make use of any abstractions for common
code, different (asynchronous) stages with fence signalling critical paths,
any other helpers or error handling in terms of freeing memory and dropping
previously taken locks.

1) Obtain a list of [`drm_gpuva_op`](#c-struct-drm_gpuva_op) to create a new mapping:

```text
// Allocates a new &drm_gpuva.
struct drm_gpuva * driver_gpuva_alloc(void);

// Typically drivers would embed the &drm_gpuvm and &drm_gpuva
// structure in individual driver structures and lock the dma-resv with
// drm_exec or similar helpers.
int driver_mapping_create(struct drm_gpuvm *gpuvm,
                          u64 addr, u64 range,
                          struct drm_gem_object *obj, u64 offset)
{
        struct drm_gpuvm_map_req map_req = {
                .map.va.addr = addr,
                .map.va.range = range,
                .map.gem.obj = obj,
                .map.gem.offset = offset,
           };
        struct drm_gpuva_ops *ops;
        struct drm_gpuva_op *op
        struct drm_gpuvm_bo *vm_bo;

        driver_lock_va_space();
        ops = drm_gpuvm_sm_map_ops_create(gpuvm, &map_req);
        if (IS_ERR(ops))
                return PTR_ERR(ops);

        vm_bo = drm_gpuvm_bo_obtain(gpuvm, obj);
        if (IS_ERR(vm_bo))
                return PTR_ERR(vm_bo);

        drm_gpuva_for_each_op(op, ops) {
                struct drm_gpuva *va;

                switch (op->op) {
                case DRM_GPUVA_OP_MAP:
                        va = driver_gpuva_alloc();
                        if (!va)
                                ; // unwind previous VA space updates,
                                  // free memory and unlock

                        driver_vm_map();
                        drm_gpuva_map(gpuvm, va, &op->map);
                        drm_gpuva_link(va, vm_bo);

                        break;
                case DRM_GPUVA_OP_REMAP: {
                        struct drm_gpuva *prev = NULL, *next = NULL;

                        va = op->remap.unmap->va;

                        if (op->remap.prev) {
                                prev = driver_gpuva_alloc();
                                if (!prev)
                                        ; // unwind previous VA space
                                          // updates, free memory and
                                          // unlock
                        }

                        if (op->remap.next) {
                                next = driver_gpuva_alloc();
                                if (!next)
                                        ; // unwind previous VA space
                                          // updates, free memory and
                                          // unlock
                        }

                        driver_vm_remap();
                        drm_gpuva_remap(prev, next, &op->remap);

                        if (prev)
                                drm_gpuva_link(prev, va->vm_bo);
                        if (next)
                                drm_gpuva_link(next, va->vm_bo);
                        drm_gpuva_unlink(va);

                        break;
                }
                case DRM_GPUVA_OP_UNMAP:
                        va = op->unmap->va;

                        driver_vm_unmap();
                        drm_gpuva_unlink(va);
                        drm_gpuva_unmap(&op->unmap);

                        break;
                default:
                        break;
                }
        }
        drm_gpuvm_bo_put(vm_bo);
        driver_unlock_va_space();

        return 0;
}
```

2) Receive a callback for each [`drm_gpuva_op`](#c-struct-drm_gpuva_op) to create a new mapping:

```text
struct driver_context {
        struct drm_gpuvm *gpuvm;
        struct drm_gpuvm_bo *vm_bo;
        struct drm_gpuva *new_va;
        struct drm_gpuva *prev_va;
        struct drm_gpuva *next_va;
};

// ops to pass to drm_gpuvm_init()
static const struct drm_gpuvm_ops driver_gpuvm_ops = {
        .sm_step_map = driver_gpuva_map,
        .sm_step_remap = driver_gpuva_remap,
        .sm_step_unmap = driver_gpuva_unmap,
};

// Typically drivers would embed the &drm_gpuvm and &drm_gpuva
// structure in individual driver structures and lock the dma-resv with
// drm_exec or similar helpers.
int driver_mapping_create(struct drm_gpuvm *gpuvm,
                          u64 addr, u64 range,
                          struct drm_gem_object *obj, u64 offset)
{
        struct driver_context ctx;
        struct drm_gpuvm_bo *vm_bo;
        struct drm_gpuva_ops *ops;
        struct drm_gpuva_op *op;
        int ret = 0;

        ctx.gpuvm = gpuvm;

        ctx.new_va = kzalloc(sizeof(*ctx.new_va), GFP_KERNEL);
        ctx.prev_va = kzalloc(sizeof(*ctx.prev_va), GFP_KERNEL);
        ctx.next_va = kzalloc(sizeof(*ctx.next_va), GFP_KERNEL);
        ctx.vm_bo = drm_gpuvm_bo_create(gpuvm, obj);
        if (!ctx.new_va || !ctx.prev_va || !ctx.next_va || !vm_bo) {
                ret = -ENOMEM;
                goto out;
        }

        // Typically protected with a driver specific GEM gpuva lock
        // used in the fence signaling path for drm_gpuva_link() and
        // drm_gpuva_unlink(), hence pre-allocate.
        ctx.vm_bo = drm_gpuvm_bo_obtain_prealloc(ctx.vm_bo);

        driver_lock_va_space();
        ret = drm_gpuvm_sm_map(gpuvm, &ctx, addr, range, obj, offset);
        driver_unlock_va_space();

out:
        drm_gpuvm_bo_put(ctx.vm_bo);
        kfree(ctx.new_va);
        kfree(ctx.prev_va);
        kfree(ctx.next_va);
        return ret;
}

int driver_gpuva_map(struct drm_gpuva_op *op, void *__ctx)
{
        struct driver_context *ctx = __ctx;

        drm_gpuva_map(ctx->vm, ctx->new_va, &op->map);

        drm_gpuva_link(ctx->new_va, ctx->vm_bo);

        // prevent the new GPUVA from being freed in
        // driver_mapping_create()
        ctx->new_va = NULL;

        return 0;
}

int driver_gpuva_remap(struct drm_gpuva_op *op, void *__ctx)
{
        struct driver_context *ctx = __ctx;
        struct drm_gpuva *va = op->remap.unmap->va;

        drm_gpuva_remap(ctx->prev_va, ctx->next_va, &op->remap);

        if (op->remap.prev) {
                drm_gpuva_link(ctx->prev_va, va->vm_bo);
                ctx->prev_va = NULL;
        }

        if (op->remap.next) {
                drm_gpuva_link(ctx->next_va, va->vm_bo);
                ctx->next_va = NULL;
        }

        drm_gpuva_unlink(va);
        kfree(va);

        return 0;
}

int driver_gpuva_unmap(struct drm_gpuva_op *op, void *__ctx)
{
        drm_gpuva_unlink(op->unmap.va);
        drm_gpuva_unmap(&op->unmap);
        kfree(op->unmap.va);

        return 0;
}
```


<a id="rst-drm-gpuvm-function-references"></a>

### DRM GPUVM Function References


#### <a id="c-enum-drm_gpuva_flags"></a>`enum drm_gpuva_flags`

flags for struct drm_gpuva

**Constants**

- `DRM_GPUVA_INVALIDATED`: Flag indicating that the [`drm_gpuva`](#c-struct-drm_gpuva)'s backing GEM is invalidated.
- `DRM_GPUVA_SPARSE`: Flag indicating that the [`drm_gpuva`](#c-struct-drm_gpuva) is a sparse mapping.
- `DRM_GPUVA_USERBITS`: user defined bits

#### <a id="c-struct-drm_gpuva"></a>`struct drm_gpuva`

structure to track a GPU VA mapping

**Definition**

```c
struct drm_gpuva {
    struct drm_gpuvm *vm;
    struct drm_gpuvm_bo *vm_bo;
    enum drm_gpuva_flags flags;
    struct {
        u64 addr;
        u64 range;
    } va;
    struct {
        u64 offset;
        struct drm_gem_object *obj;
        struct list_head entry;
    } gem;
    struct {
        struct rb_node node;
        struct list_head entry;
        u64 __subtree_last;
    } rb;
};
```

**Members**

- `vm`: the [`drm_gpuvm`](#c-struct-drm_gpuvm) this object is associated with
- `vm_bo`: the [`drm_gpuvm_bo`](#c-struct-drm_gpuvm_bo) abstraction for the mapped
  [`drm_gem_object`](#c-struct-drm_gem_object)
- `flags`: the [`drm_gpuva_flags`](#c-enum-drm_gpuva_flags) for this mapping
- `va`: structure containing the address and range of the [`drm_gpuva`](#c-struct-drm_gpuva)
- `va.addr`: the start address
- `gem`: structure containing the [`drm_gem_object`](#c-struct-drm_gem_object) and its offset
- `gem.offset`: the offset within the [`drm_gem_object`](#c-struct-drm_gem_object)
- `gem.obj`: the mapped [`drm_gem_object`](#c-struct-drm_gem_object)
- `gem.entry`: the `list_head` to attach this object to a [`drm_gpuvm_bo`](#c-struct-drm_gpuvm_bo)
- `rb`: structure containing data to store `drm_gpuvas` in a rb-tree
- `rb.node`: the rb-tree node
- `rb.entry`: The `list_head` to additionally connect `drm_gpuvas`
  in the same order they appear in the interval tree. This is
  useful to keep iterating `drm_gpuvas` from a start node found
  through the rb-tree while doing modifications on the rb-tree
  itself.
- `rb.__subtree_last`: needed by the interval tree, holding last-in-subtree

**Description**

This structure represents a GPU VA mapping and is associated with a
[`drm_gpuvm`](#c-struct-drm_gpuvm).

Typically, this structure is embedded in bigger driver structures.

#### <a id="c-drm_gpuva_invalidate"></a>`drm_gpuva_invalidate()`

```c
void drm_gpuva_invalidate(struct drm_gpuva *va, bool invalidate)
```

sets whether the backing GEM of this [`drm_gpuva`](#c-struct-drm_gpuva) is invalidated

**Parameters**

- `struct drm_gpuva *va`: the [`drm_gpuva`](#c-struct-drm_gpuva) to set the invalidate flag for
- `bool invalidate`: indicates whether the [`drm_gpuva`](#c-struct-drm_gpuva) is invalidated

#### <a id="c-drm_gpuva_invalidated"></a>`drm_gpuva_invalidated()`

```c
bool drm_gpuva_invalidated(struct drm_gpuva *va)
```

indicates whether the backing BO of this [`drm_gpuva`](#c-struct-drm_gpuva) is invalidated

**Parameters**

- `struct drm_gpuva *va`: the [`drm_gpuva`](#c-struct-drm_gpuva) to check

**Return**

`true` if the GPU VA is invalidated, `false` otherwise

#### <a id="c-enum-drm_gpuvm_flags"></a>`enum drm_gpuvm_flags`

flags for struct drm_gpuvm

**Constants**

- `DRM_GPUVM_RESV_PROTECTED`: GPUVM is protected externally by the
  GPUVM's [`dma_resv`](/kernel/hardware/driver-api/io-and-dma/dma-buf.md#c-struct-dma_resv) lock
- `DRM_GPUVM_IMMEDIATE_MODE`: use the locking scheme for GEMs designed
  for modifying the GPUVM during the fence signalling path

  When set, gpuva.lock is used to protect gpuva.list in all GEM
  objects associated with this GPUVM. Otherwise, the GEMs dma-resv is
  used.
- `DRM_GPUVM_USERBITS`: user defined bits

#### <a id="c-struct-drm_gpuvm"></a>`struct drm_gpuvm`

DRM GPU VA Manager

**Definition**

```c
struct drm_gpuvm {
    const char *name;
    enum drm_gpuvm_flags flags;
    struct drm_device *drm;
    u64 mm_start;
    u64 mm_range;
    struct {
        struct rb_root_cached tree;
        struct list_head list;
    } rb;
    struct kref kref;
    struct drm_gpuva kernel_alloc_node;
    const struct drm_gpuvm_ops *ops;
    struct drm_gem_object *r_obj;
    struct {
        struct list_head list;
        struct list_head *local_list;
        spinlock_t lock;
    } extobj;
    struct {
        struct list_head list;
        struct list_head *local_list;
        spinlock_t lock;
    } evict;
    struct llist_head bo_defer;
};
```

**Members**

- `name`: the name of the DRM GPU VA space
- `flags`: the [`drm_gpuvm_flags`](#c-enum-drm_gpuvm_flags) of this GPUVM
- `drm`: the [`drm_device`](/kernel/hardware/gpu/drm-internals.md#c-struct-drm_device) this VM lives in
- `mm_start`: start of the VA space
- `mm_range`: length of the VA space
- `rb`: structures to track [`drm_gpuva`](#c-struct-drm_gpuva) entries
- `rb.tree`: the rb-tree to track GPU VA mappings
- `rb.list`: the `list_head` to track GPU VA mappings
- `kref`: reference count of this object
- `kernel_alloc_node`: [`drm_gpuva`](#c-struct-drm_gpuva) representing the address space cutout reserved for
  the kernel
- `ops`: [`drm_gpuvm_ops`](#c-struct-drm_gpuvm_ops) providing the split/merge steps to drivers
- `r_obj`: Resv GEM object; representing the GPUVM's common [`dma_resv`](/kernel/hardware/driver-api/io-and-dma/dma-buf.md#c-struct-dma_resv).
- `extobj`: structure holding the extobj list
- `extobj.list`: `list_head` storing `drm_gpuvm_bos` serving as
  external object
- `extobj.local_list`: pointer to the local list temporarily
  storing entries from the external object list
- `extobj.lock`: spinlock to protect the extobj list
- `evict`: structure holding the evict list and evict list lock
- `evict.list`: `list_head` storing `drm_gpuvm_bos` currently
  being evicted
- `evict.local_list`: pointer to the local list temporarily
  storing entries from the evicted object list
- `evict.lock`: spinlock to protect the evict list
- `bo_defer`: structure holding vm_bos that need to be destroyed

**Description**

The DRM GPU VA Manager keeps track of a GPU's virtual address space by using
`maple_tree` structures. Typically, this structure is embedded in bigger
driver structures.

Drivers can pass addresses and ranges in an arbitrary unit, e.g. bytes or
pages.

There should be one manager instance per GPU virtual address space.

#### <a id="c-drm_gpuvm_get"></a>`drm_gpuvm_get()`

```c
struct drm_gpuvm * drm_gpuvm_get(struct drm_gpuvm *gpuvm)
```

acquire a struct drm_gpuvm reference

**Parameters**

- `struct drm_gpuvm *gpuvm`: the [`drm_gpuvm`](#c-struct-drm_gpuvm) to acquire the reference of

**Description**

This function acquires an additional reference to **gpuvm**. It is illegal to
call this without already holding a reference. No locks required.

**Return**

the [`struct drm_gpuvm`](#c-struct-drm_gpuvm) pointer

#### <a id="c-drm_gpuvm_resv_protected"></a>`drm_gpuvm_resv_protected()`

```c
bool drm_gpuvm_resv_protected(struct drm_gpuvm *gpuvm)
```

indicates whether `DRM_GPUVM_RESV_PROTECTED` is set

**Parameters**

- `struct drm_gpuvm *gpuvm`: the [`drm_gpuvm`](#c-struct-drm_gpuvm)

**Return**

true if `DRM_GPUVM_RESV_PROTECTED` is set, false otherwise.

#### <a id="c-drm_gpuvm_immediate_mode"></a>`drm_gpuvm_immediate_mode()`

```c
bool drm_gpuvm_immediate_mode(struct drm_gpuvm *gpuvm)
```

indicates whether `DRM_GPUVM_IMMEDIATE_MODE` is set

**Parameters**

- `struct drm_gpuvm *gpuvm`: the [`drm_gpuvm`](#c-struct-drm_gpuvm)

**Return**

true if `DRM_GPUVM_IMMEDIATE_MODE` is set, false otherwise.

#### <a id="c-drm_gpuvm_resv"></a>`drm_gpuvm_resv()`

```c
drm_gpuvm_resv(gpuvm__)
```

returns the [`drm_gpuvm`](#c-struct-drm_gpuvm)'s [`dma_resv`](/kernel/hardware/driver-api/io-and-dma/dma-buf.md#c-struct-dma_resv)

**Parameters**

- `gpuvm__`: the [`drm_gpuvm`](#c-struct-drm_gpuvm)

**Return**

a pointer to the [`drm_gpuvm`](#c-struct-drm_gpuvm)'s shared [`dma_resv`](/kernel/hardware/driver-api/io-and-dma/dma-buf.md#c-struct-dma_resv)

#### <a id="c-drm_gpuvm_resv_obj"></a>`drm_gpuvm_resv_obj()`

```c
drm_gpuvm_resv_obj(gpuvm__)
```

returns the [`drm_gem_object`](#c-struct-drm_gem_object) holding the [`drm_gpuvm`](#c-struct-drm_gpuvm)'s [`dma_resv`](/kernel/hardware/driver-api/io-and-dma/dma-buf.md#c-struct-dma_resv)

**Parameters**

- `gpuvm__`: the [`drm_gpuvm`](#c-struct-drm_gpuvm)

**Return**

a pointer to the [`drm_gem_object`](#c-struct-drm_gem_object) holding the [`drm_gpuvm`](#c-struct-drm_gpuvm)'s shared
[`dma_resv`](/kernel/hardware/driver-api/io-and-dma/dma-buf.md#c-struct-dma_resv)

#### <a id="c-drm_gpuvm_is_extobj"></a>`drm_gpuvm_is_extobj()`

```c
bool drm_gpuvm_is_extobj(struct drm_gpuvm *gpuvm, struct drm_gem_object *obj)
```

indicates whether the given [`drm_gem_object`](#c-struct-drm_gem_object) is an external object

**Parameters**

- `struct drm_gpuvm *gpuvm`: the [`drm_gpuvm`](#c-struct-drm_gpuvm) to check
- `struct drm_gem_object *obj`: the [`drm_gem_object`](#c-struct-drm_gem_object) to check

**Return**

true if the [`drm_gem_object`](#c-struct-drm_gem_object) [`dma_resv`](/kernel/hardware/driver-api/io-and-dma/dma-buf.md#c-struct-dma_resv) differs from the
`drm_gpuvms` [`dma_resv`](/kernel/hardware/driver-api/io-and-dma/dma-buf.md#c-struct-dma_resv), false otherwise

#### <a id="c-drm_gpuvm_for_each_va_range"></a>`drm_gpuvm_for_each_va_range()`

```c
drm_gpuvm_for_each_va_range(va__, gpuvm__, start__, end__)
```

iterate over a range of `drm_gpuvas`

**Parameters**

- `va__`: [`drm_gpuva`](#c-struct-drm_gpuva) structure to assign to in each iteration step
- `gpuvm__`: [`drm_gpuvm`](#c-struct-drm_gpuvm) to walk over
- `start__`: starting offset, the first gpuva will overlap this
- `end__`: ending offset, the last gpuva will start before this (but may
  overlap)

**Description**

This iterator walks over all `drm_gpuvas` in the [`drm_gpuvm`](#c-struct-drm_gpuvm) that lie
between **start__** and **end__**. It is implemented similarly to [`list_for_each()`](/kernel/internals/core-api/list.md#c-list_for_each),
but is using the [`drm_gpuvm`](#c-struct-drm_gpuvm)'s internal interval tree to accelerate
the search for the starting [`drm_gpuva`](#c-struct-drm_gpuva), and hence isn't safe against removal
of elements. It assumes that **end__** is within (or is the upper limit of) the
[`drm_gpuvm`](#c-struct-drm_gpuvm). This iterator does not skip over the [`drm_gpuvm`](#c-struct-drm_gpuvm)'s
**kernel_alloc_node**.

#### <a id="c-drm_gpuvm_for_each_va_range_safe"></a>`drm_gpuvm_for_each_va_range_safe()`

```c
drm_gpuvm_for_each_va_range_safe(va__, next__, gpuvm__, start__, end__)
```

safely iterate over a range of `drm_gpuvas`

**Parameters**

- `va__`: [`drm_gpuva`](#c-struct-drm_gpuva) to assign to in each iteration step
- `next__`: another [`drm_gpuva`](#c-struct-drm_gpuva) to use as temporary storage
- `gpuvm__`: [`drm_gpuvm`](#c-struct-drm_gpuvm) to walk over
- `start__`: starting offset, the first gpuva will overlap this
- `end__`: ending offset, the last gpuva will start before this (but may
  overlap)

**Description**

This iterator walks over all `drm_gpuvas` in the [`drm_gpuvm`](#c-struct-drm_gpuvm) that lie
between **start__** and **end__**. It is implemented similarly to
[`list_for_each_safe()`](/kernel/internals/core-api/list.md#c-list_for_each_safe), but is using the [`drm_gpuvm`](#c-struct-drm_gpuvm)'s internal interval
tree to accelerate the search for the starting [`drm_gpuva`](#c-struct-drm_gpuva), and hence is safe
against removal of elements. It assumes that **end__** is within (or is the
upper limit of) the [`drm_gpuvm`](#c-struct-drm_gpuvm). This iterator does not skip over the
[`drm_gpuvm`](#c-struct-drm_gpuvm)'s **kernel_alloc_node**.

#### <a id="c-drm_gpuvm_for_each_va"></a>`drm_gpuvm_for_each_va()`

```c
drm_gpuvm_for_each_va(va__, gpuvm__)
```

iterate over all `drm_gpuvas`

**Parameters**

- `va__`: [`drm_gpuva`](#c-struct-drm_gpuva) to assign to in each iteration step
- `gpuvm__`: [`drm_gpuvm`](#c-struct-drm_gpuvm) to walk over

**Description**

This iterator walks over all [`drm_gpuva`](#c-struct-drm_gpuva) structures associated with the given
[`drm_gpuvm`](#c-struct-drm_gpuvm).

#### <a id="c-drm_gpuvm_for_each_va_safe"></a>`drm_gpuvm_for_each_va_safe()`

```c
drm_gpuvm_for_each_va_safe(va__, next__, gpuvm__)
```

safely iterate over all `drm_gpuvas`

**Parameters**

- `va__`: [`drm_gpuva`](#c-struct-drm_gpuva) to assign to in each iteration step
- `next__`: another [`drm_gpuva`](#c-struct-drm_gpuva) to use as temporary storage
- `gpuvm__`: [`drm_gpuvm`](#c-struct-drm_gpuvm) to walk over

**Description**

This iterator walks over all [`drm_gpuva`](#c-struct-drm_gpuva) structures associated with the given
[`drm_gpuvm`](#c-struct-drm_gpuvm). It is implemented with [`list_for_each_entry_safe()`](/kernel/internals/core-api/list.md#c-list_for_each_entry_safe), and
hence safe against the removal of elements.

#### <a id="c-struct-drm_gpuvm_exec"></a>`struct drm_gpuvm_exec`

[`drm_gpuvm`](#c-struct-drm_gpuvm) abstraction of [`drm_exec`](#c-struct-drm_exec)

**Definition**

```c
struct drm_gpuvm_exec {
    struct drm_exec exec;
    u32 flags;
    struct drm_gpuvm *vm;
    unsigned int num_fences;
    struct {
        int (*fn)(struct drm_gpuvm_exec *vm_exec);
        void *priv;
    } extra;
};
```

**Members**

- `exec`: the [`drm_exec`](#c-struct-drm_exec) structure
- `flags`: the flags for the struct drm_exec
- `vm`: the [`drm_gpuvm`](#c-struct-drm_gpuvm) to lock its DMA reservations
- `num_fences`: the number of fences to reserve for the [`dma_resv`](/kernel/hardware/driver-api/io-and-dma/dma-buf.md#c-struct-dma_resv) of the
  locked `drm_gem_objects`
- `extra`: Callback and corresponding private data for the driver to
  lock arbitrary additional `drm_gem_objects`.
- `extra.fn`: The driver callback to lock additional
  `drm_gem_objects`.
- `extra.priv`: driver private data for the **fn** callback

**Description**

This structure should be created on the stack as [`drm_exec`](#c-struct-drm_exec) should be.

Optionally, **extra** can be set in order to lock additional `drm_gem_objects`.

#### <a id="c-drm_gpuvm_exec_unlock"></a>`drm_gpuvm_exec_unlock()`

```c
void drm_gpuvm_exec_unlock(struct drm_gpuvm_exec *vm_exec)
```

lock all dma-resv of all assoiciated BOs

**Parameters**

- `struct drm_gpuvm_exec *vm_exec`: the [`drm_gpuvm_exec`](#c-struct-drm_gpuvm_exec) wrapper

**Description**

Releases all dma-resv locks of all `drm_gem_objects` previously acquired
through [`drm_gpuvm_exec_lock()`](#c-drm_gpuvm_exec_lock) or its variants.

**Return**

0 on success, negative error code on failure.

#### <a id="c-drm_gpuvm_exec_resv_add_fence"></a>`drm_gpuvm_exec_resv_add_fence()`

```c
void drm_gpuvm_exec_resv_add_fence(struct drm_gpuvm_exec *vm_exec, struct dma_fence *fence, enum dma_resv_usage private_usage, enum dma_resv_usage extobj_usage)
```

add fence to private and all extobj

**Parameters**

- `struct drm_gpuvm_exec *vm_exec`: the [`drm_gpuvm_exec`](#c-struct-drm_gpuvm_exec) wrapper
- `struct dma_fence *fence`: fence to add
- `enum dma_resv_usage private_usage`: private dma-resv usage
- `enum dma_resv_usage extobj_usage`: extobj dma-resv usage

**Description**

See [`drm_gpuvm_resv_add_fence()`](#c-drm_gpuvm_resv_add_fence).

#### <a id="c-drm_gpuvm_exec_validate"></a>`drm_gpuvm_exec_validate()`

```c
int drm_gpuvm_exec_validate(struct drm_gpuvm_exec *vm_exec)
```

validate all BOs marked as evicted

**Parameters**

- `struct drm_gpuvm_exec *vm_exec`: the [`drm_gpuvm_exec`](#c-struct-drm_gpuvm_exec) wrapper

**Description**

See [`drm_gpuvm_validate()`](#c-drm_gpuvm_validate).

**Return**

0 on success, negative error code on failure.

#### <a id="c-struct-drm_gpuvm_bo"></a>`struct drm_gpuvm_bo`

structure representing a [`drm_gpuvm`](#c-struct-drm_gpuvm) and [`drm_gem_object`](#c-struct-drm_gem_object) combination

**Definition**

```c
struct drm_gpuvm_bo {
    struct drm_gpuvm *vm;
    struct drm_gem_object *obj;
    bool evicted;
    struct kref kref;
    struct {
        struct list_head gpuva;
        struct {
            struct list_head gem;
            struct list_head extobj;
            struct list_head evict;
            struct llist_node bo_defer;
        } entry;
    } list;
};
```

**Members**

- `vm`: The [`drm_gpuvm`](#c-struct-drm_gpuvm) the **obj** is mapped in. This is a reference
  counted pointer.
- `obj`: The [`drm_gem_object`](#c-struct-drm_gem_object) being mapped in **vm**. This is a reference
  counted pointer.
- `evicted`: Indicates whether the [`drm_gem_object`](#c-struct-drm_gem_object) is evicted; field
  protected by the [`drm_gem_object`](#c-struct-drm_gem_object)'s dma-resv lock.
- `kref`: The reference count for this [`drm_gpuvm_bo`](#c-struct-drm_gpuvm_bo).
- `list`: Structure containing all `list_heads`.
- `list.gpuva`: The list of linked `drm_gpuvas`.

  It is safe to access entries from this list as long as the
  GEM's gpuva lock is held. See also struct drm_gem_object.
- `list.entry`: Structure containing all `list_heads` serving as
  entry.
- `list.entry.gem`: List entry to attach to the
  `drm_gem_objects` gpuva list.
- `list.entry.evict`: List entry to attach to the
  `drm_gpuvms` evict list.
- `list.entry.bo_defer`: List entry to attach to
  the `drm_gpuvms` bo_defer list.

**Description**

This structure is an abstraction representing a [`drm_gpuvm`](#c-struct-drm_gpuvm) and
[`drm_gem_object`](#c-struct-drm_gem_object) combination. It serves as an indirection to accelerate
iterating all `drm_gpuvas` within a [`drm_gpuvm`](#c-struct-drm_gpuvm) backed by the same
[`drm_gem_object`](#c-struct-drm_gem_object).

Furthermore it is used cache evicted GEM objects for a certain GPU-VM to
accelerate validation.

Typically, drivers want to create an instance of a struct drm_gpuvm_bo once
a GEM object is mapped first in a GPU-VM and release the instance once the
last mapping of the GEM object in this GPU-VM is unmapped.

#### <a id="c-drm_gpuvm_bo_get"></a>`drm_gpuvm_bo_get()`

```c
struct drm_gpuvm_bo * drm_gpuvm_bo_get(struct drm_gpuvm_bo *vm_bo)
```

acquire a struct drm_gpuvm_bo reference

**Parameters**

- `struct drm_gpuvm_bo *vm_bo`: the [`drm_gpuvm_bo`](#c-struct-drm_gpuvm_bo) to acquire the reference of

**Description**

This function acquires an additional reference to **vm_bo**. It is illegal to
call this without already holding a reference. No locks required.

**Return**

the `struct vm_bo` pointer

#### <a id="c-drm_gpuvm_bo_gem_evict"></a>`drm_gpuvm_bo_gem_evict()`

```c
void drm_gpuvm_bo_gem_evict(struct drm_gem_object *obj, bool evict)
```

add/remove all [`drm_gpuvm_bo`](#c-struct-drm_gpuvm_bo)'s in the list to/from the `drm_gpuvms` evicted list

**Parameters**

- `struct drm_gem_object *obj`: the [`drm_gem_object`](#c-struct-drm_gem_object)
- `bool evict`: indicates whether **obj** is evicted

**Description**

See [`drm_gpuvm_bo_evict()`](#c-drm_gpuvm_bo_evict).

#### <a id="c-drm_gpuvm_bo_for_each_va"></a>`drm_gpuvm_bo_for_each_va()`

```c
drm_gpuvm_bo_for_each_va(va__, vm_bo__)
```

iterator to walk over a list of [`drm_gpuva`](#c-struct-drm_gpuva)

**Parameters**

- `va__`: [`drm_gpuva`](#c-struct-drm_gpuva) structure to assign to in each iteration step
- `vm_bo__`: the [`drm_gpuvm_bo`](#c-struct-drm_gpuvm_bo) the [`drm_gpuva`](#c-struct-drm_gpuva) to walk are associated with

**Description**

This iterator walks over all [`drm_gpuva`](#c-struct-drm_gpuva) structures associated with the
[`drm_gpuvm_bo`](#c-struct-drm_gpuvm_bo).

The caller must hold the GEM's gpuva lock.

#### <a id="c-drm_gpuvm_bo_for_each_va_safe"></a>`drm_gpuvm_bo_for_each_va_safe()`

```c
drm_gpuvm_bo_for_each_va_safe(va__, next__, vm_bo__)
```

iterator to safely walk over a list of [`drm_gpuva`](#c-struct-drm_gpuva)

**Parameters**

- `va__`: [`drm_gpuva`](#c-struct-drm_gpuva) structure to assign to in each iteration step
- `next__`: `next` [`drm_gpuva`](#c-struct-drm_gpuva) to store the next step
- `vm_bo__`: the [`drm_gpuvm_bo`](#c-struct-drm_gpuvm_bo) the [`drm_gpuva`](#c-struct-drm_gpuva) to walk are associated with

**Description**

This iterator walks over all [`drm_gpuva`](#c-struct-drm_gpuva) structures associated with the
[`drm_gpuvm_bo`](#c-struct-drm_gpuvm_bo). It is implemented with [`list_for_each_entry_safe()`](/kernel/internals/core-api/list.md#c-list_for_each_entry_safe), hence
it is save against removal of elements.

The caller must hold the GEM's gpuva lock.

#### <a id="c-enum-drm_gpuva_op_type"></a>`enum drm_gpuva_op_type`

GPU VA operation type

**Constants**

- `DRM_GPUVA_OP_MAP`: the map op type
- `DRM_GPUVA_OP_REMAP`: the remap op type
- `DRM_GPUVA_OP_UNMAP`: the unmap op type
- `DRM_GPUVA_OP_PREFETCH`: the prefetch op type
- `DRM_GPUVA_OP_DRIVER`: the driver defined op type

**Description**

Operations to alter the GPU VA mappings tracked by the [`drm_gpuvm`](#c-struct-drm_gpuvm).

#### <a id="c-struct-drm_gpuva_op_map"></a>`struct drm_gpuva_op_map`

GPU VA map operation

**Definition**

```c
struct drm_gpuva_op_map {
    struct {
        u64 addr;
        u64 range;
    } va;
    struct {
        u64 offset;
        struct drm_gem_object *obj;
    } gem;
};
```

**Members**

- `va`: structure containing address and range of a map
  operation
- `va.addr`: the base address of the new mapping
- `va.range`: the range of the new mapping
- `gem`: structure containing the [`drm_gem_object`](#c-struct-drm_gem_object) and its offset
- `gem.offset`: the offset within the [`drm_gem_object`](#c-struct-drm_gem_object)
- `gem.obj`: the [`drm_gem_object`](#c-struct-drm_gem_object) to map

**Description**

This structure represents a single map operation generated by the
DRM GPU VA manager.

#### <a id="c-struct-drm_gpuva_op_unmap"></a>`struct drm_gpuva_op_unmap`

GPU VA unmap operation

**Definition**

```c
struct drm_gpuva_op_unmap {
    struct drm_gpuva *va;
    bool keep;
};
```

**Members**

- `va`: the [`drm_gpuva`](#c-struct-drm_gpuva) to unmap
- `keep`: Indicates whether this [`drm_gpuva`](#c-struct-drm_gpuva) is physically contiguous with the
  original mapping request.

  Optionally, if `keep` is set, drivers may keep the actual page table
  mappings for this [`drm_gpuva`](#c-struct-drm_gpuva), adding the missing page table entries
  only and update the [`drm_gpuvm`](#c-struct-drm_gpuvm) accordingly.

**Description**

This structure represents a single unmap operation generated by the
DRM GPU VA manager.

#### <a id="c-struct-drm_gpuva_op_remap"></a>`struct drm_gpuva_op_remap`

GPU VA remap operation

**Definition**

```c
struct drm_gpuva_op_remap {
    struct drm_gpuva_op_map *prev;
    struct drm_gpuva_op_map *next;
    struct drm_gpuva_op_unmap *unmap;
};
```

**Members**

- `prev`: the preceding part of a split mapping
- `next`: the subsequent part of a split mapping
- `unmap`: the unmap operation for the original existing mapping

**Description**

This represents a single remap operation generated by the DRM GPU VA manager.

A remap operation is generated when an existing GPU VA mmapping is split up
by inserting a new GPU VA mapping or by partially unmapping existent
mapping(s), hence it consists of a maximum of two map and one unmap
operation.

The **unmap** operation takes care of removing the original existing mapping.
**prev** is used to remap the preceding part, **next** the subsequent part.

If either a new mapping's start address is aligned with the start address
of the old mapping or the new mapping's end address is aligned with the
end address of the old mapping, either **prev** or **next** is NULL.

Note, the reason for a dedicated remap operation, rather than arbitrary
unmap and map operations, is to give drivers the chance of extracting driver
specific data for creating the new mappings from the unmap operations's
[`drm_gpuva`](#c-struct-drm_gpuva) structure which typically is embedded in larger driver specific
structures.

#### <a id="c-struct-drm_gpuva_op_prefetch"></a>`struct drm_gpuva_op_prefetch`

GPU VA prefetch operation

**Definition**

```c
struct drm_gpuva_op_prefetch {
    struct drm_gpuva *va;
};
```

**Members**

- `va`: the [`drm_gpuva`](#c-struct-drm_gpuva) to prefetch

**Description**

This structure represents a single prefetch operation generated by the
DRM GPU VA manager.

#### <a id="c-struct-drm_gpuva_op"></a>`struct drm_gpuva_op`

GPU VA operation

**Definition**

```c
struct drm_gpuva_op {
    struct list_head entry;
    enum drm_gpuva_op_type op;
    union {
        struct drm_gpuva_op_map map;
        struct drm_gpuva_op_remap remap;
        struct drm_gpuva_op_unmap unmap;
        struct drm_gpuva_op_prefetch prefetch;
    };
};
```

**Members**

- `entry`: The `list_head` used to distribute instances of this struct within
  [`drm_gpuva_ops`](#c-struct-drm_gpuva_ops).
- `op`: the type of the operation
- `{unnamed_union}`: anonymous
- `map`: the map operation
- `remap`: the remap operation
- `unmap`: the unmap operation
- `prefetch`: the prefetch operation

**Description**

This structure represents a single generic operation.

The particular type of the operation is defined by **op**.

#### <a id="c-struct-drm_gpuva_ops"></a>`struct drm_gpuva_ops`

wraps a list of [`drm_gpuva_op`](#c-struct-drm_gpuva_op)

**Definition**

```c
struct drm_gpuva_ops {
    struct list_head list;
};
```

**Members**

- `list`: the `list_head`

#### <a id="c-drm_gpuva_for_each_op"></a>`drm_gpuva_for_each_op()`

```c
drm_gpuva_for_each_op(op, ops)
```

iterator to walk over [`drm_gpuva_ops`](#c-struct-drm_gpuva_ops)

**Parameters**

- `op`: [`drm_gpuva_op`](#c-struct-drm_gpuva_op) to assign in each iteration step
- `ops`: [`drm_gpuva_ops`](#c-struct-drm_gpuva_ops) to walk

**Description**

This iterator walks over all ops within a given list of operations.

#### <a id="c-drm_gpuva_for_each_op_safe"></a>`drm_gpuva_for_each_op_safe()`

```c
drm_gpuva_for_each_op_safe(op, next, ops)
```

iterator to safely walk over [`drm_gpuva_ops`](#c-struct-drm_gpuva_ops)

**Parameters**

- `op`: [`drm_gpuva_op`](#c-struct-drm_gpuva_op) to assign in each iteration step
- `next`: `next` [`drm_gpuva_op`](#c-struct-drm_gpuva_op) to store the next step
- `ops`: [`drm_gpuva_ops`](#c-struct-drm_gpuva_ops) to walk

**Description**

This iterator walks over all ops within a given list of operations. It is
implemented with [`list_for_each_safe()`](/kernel/internals/core-api/list.md#c-list_for_each_safe), so save against removal of elements.

#### <a id="c-drm_gpuva_for_each_op_from_reverse"></a>`drm_gpuva_for_each_op_from_reverse()`

```c
drm_gpuva_for_each_op_from_reverse(op, ops)
```

iterate backwards from the given point

**Parameters**

- `op`: [`drm_gpuva_op`](#c-struct-drm_gpuva_op) to assign in each iteration step
- `ops`: [`drm_gpuva_ops`](#c-struct-drm_gpuva_ops) to walk

**Description**

This iterator walks over all ops within a given list of operations beginning
from the given operation in reverse order.

#### <a id="c-drm_gpuva_for_each_op_reverse"></a>`drm_gpuva_for_each_op_reverse()`

```c
drm_gpuva_for_each_op_reverse(op, ops)
```

iterator to walk over [`drm_gpuva_ops`](#c-struct-drm_gpuva_ops) in reverse

**Parameters**

- `op`: [`drm_gpuva_op`](#c-struct-drm_gpuva_op) to assign in each iteration step
- `ops`: [`drm_gpuva_ops`](#c-struct-drm_gpuva_ops) to walk

**Description**

This iterator walks over all ops within a given list of operations in reverse

#### <a id="c-drm_gpuva_first_op"></a>`drm_gpuva_first_op()`

```c
drm_gpuva_first_op(ops)
```

returns the first [`drm_gpuva_op`](#c-struct-drm_gpuva_op) from [`drm_gpuva_ops`](#c-struct-drm_gpuva_ops)

**Parameters**

- `ops`: the [`drm_gpuva_ops`](#c-struct-drm_gpuva_ops) to get the fist [`drm_gpuva_op`](#c-struct-drm_gpuva_op) from

#### <a id="c-drm_gpuva_last_op"></a>`drm_gpuva_last_op()`

```c
drm_gpuva_last_op(ops)
```

returns the last [`drm_gpuva_op`](#c-struct-drm_gpuva_op) from [`drm_gpuva_ops`](#c-struct-drm_gpuva_ops)

**Parameters**

- `ops`: the [`drm_gpuva_ops`](#c-struct-drm_gpuva_ops) to get the last [`drm_gpuva_op`](#c-struct-drm_gpuva_op) from

#### <a id="c-drm_gpuva_prev_op"></a>`drm_gpuva_prev_op()`

```c
drm_gpuva_prev_op(op)
```

previous [`drm_gpuva_op`](#c-struct-drm_gpuva_op) in the list

**Parameters**

- `op`: the current [`drm_gpuva_op`](#c-struct-drm_gpuva_op)

#### <a id="c-drm_gpuva_next_op"></a>`drm_gpuva_next_op()`

```c
drm_gpuva_next_op(op)
```

next [`drm_gpuva_op`](#c-struct-drm_gpuva_op) in the list

**Parameters**

- `op`: the current [`drm_gpuva_op`](#c-struct-drm_gpuva_op)

#### <a id="c-struct-drm_gpuvm_map_req"></a>`struct drm_gpuvm_map_req`

arguments passed to drm_gpuvm_sm_map\[_ops_create\]()

**Definition**

```c
struct drm_gpuvm_map_req {
    struct drm_gpuva_op_map map;
};
```

**Members**

- `map`: struct drm_gpuva_op_map

#### <a id="c-struct-drm_gpuvm_ops"></a>`struct drm_gpuvm_ops`

callbacks for split/merge steps

**Definition**

```c
struct drm_gpuvm_ops {
    void (*vm_free)(struct drm_gpuvm *gpuvm);
    struct drm_gpuva_op *(*op_alloc)(void);
    void (*op_free)(struct drm_gpuva_op *op);
    struct drm_gpuvm_bo *(*vm_bo_alloc)(void);
    void (*vm_bo_free)(struct drm_gpuvm_bo *vm_bo);
    int (*vm_bo_validate)(struct drm_gpuvm_bo *vm_bo, struct drm_exec *exec);
    int (*sm_step_map)(struct drm_gpuva_op *op, void *priv);
    int (*sm_step_remap)(struct drm_gpuva_op *op, void *priv);
    int (*sm_step_unmap)(struct drm_gpuva_op *op, void *priv);
};
```

**Members**

- `vm_free`: called when the last reference of a struct drm_gpuvm is
  dropped

  This callback is mandatory.
- `op_alloc`: called when the [`drm_gpuvm`](#c-struct-drm_gpuvm) allocates
  a struct drm_gpuva_op

  Some drivers may want to embed struct drm_gpuva_op into driver
  specific structures. By implementing this callback drivers can
  allocate memory accordingly.

  This callback is optional.
- `op_free`: called when the [`drm_gpuvm`](#c-struct-drm_gpuvm) frees a
  struct drm_gpuva_op

  Some drivers may want to embed struct drm_gpuva_op into driver
  specific structures. By implementing this callback drivers can
  free the previously allocated memory accordingly.

  This callback is optional.
- `vm_bo_alloc`: called when the [`drm_gpuvm`](#c-struct-drm_gpuvm) allocates
  a struct drm_gpuvm_bo

  Some drivers may want to embed struct drm_gpuvm_bo into driver
  specific structures. By implementing this callback drivers can
  allocate memory accordingly.

  This callback is optional.
- `vm_bo_free`: called when the [`drm_gpuvm`](#c-struct-drm_gpuvm) frees a
  struct drm_gpuvm_bo

  Some drivers may want to embed struct drm_gpuvm_bo into driver
  specific structures. By implementing this callback drivers can
  free the previously allocated memory accordingly.

  This callback is optional.
- `vm_bo_validate`: called from [`drm_gpuvm_validate()`](#c-drm_gpuvm_validate)

  Drivers receive this callback for every evicted [`drm_gem_object`](#c-struct-drm_gem_object) being
  mapped in the corresponding [`drm_gpuvm`](#c-struct-drm_gpuvm).

  Typically, drivers would call their driver specific variant of
  `ttm_bo_validate()` from within this callback.
- `sm_step_map`: called from [`drm_gpuvm_sm_map`](#c-drm_gpuvm_sm_map) to finally insert the
  mapping once all previous steps were completed

  The `priv` pointer matches the one the driver passed to
  [`drm_gpuvm_sm_map`](#c-drm_gpuvm_sm_map) or [`drm_gpuvm_sm_unmap`](#c-drm_gpuvm_sm_unmap), respectively.

  Can be NULL if [`drm_gpuvm_sm_map`](#c-drm_gpuvm_sm_map) is used.
- `sm_step_remap`: called from [`drm_gpuvm_sm_map`](#c-drm_gpuvm_sm_map) and
  [`drm_gpuvm_sm_unmap`](#c-drm_gpuvm_sm_unmap) to split up an existent mapping

  This callback is called when existent mapping needs to be split up.
  This is the case when either a newly requested mapping overlaps or
  is enclosed by an existent mapping or a partial unmap of an existent
  mapping is requested.

  The `priv` pointer matches the one the driver passed to
  [`drm_gpuvm_sm_map`](#c-drm_gpuvm_sm_map) or [`drm_gpuvm_sm_unmap`](#c-drm_gpuvm_sm_unmap), respectively.

  Can be NULL if neither [`drm_gpuvm_sm_map`](#c-drm_gpuvm_sm_map) nor [`drm_gpuvm_sm_unmap`](#c-drm_gpuvm_sm_unmap) is
  used.
- `sm_step_unmap`: called from [`drm_gpuvm_sm_map`](#c-drm_gpuvm_sm_map) and
  [`drm_gpuvm_sm_unmap`](#c-drm_gpuvm_sm_unmap) to unmap an existing mapping

  This callback is called when existing mapping needs to be unmapped.
  This is the case when either a newly requested mapping encloses an
  existing mapping or an unmap of an existing mapping is requested.

  The `priv` pointer matches the one the driver passed to
  [`drm_gpuvm_sm_map`](#c-drm_gpuvm_sm_map) or [`drm_gpuvm_sm_unmap`](#c-drm_gpuvm_sm_unmap), respectively.

  Can be NULL if neither [`drm_gpuvm_sm_map`](#c-drm_gpuvm_sm_map) nor [`drm_gpuvm_sm_unmap`](#c-drm_gpuvm_sm_unmap) is
  used.

**Description**

This structure defines the callbacks used by [`drm_gpuvm_sm_map`](#c-drm_gpuvm_sm_map) and
[`drm_gpuvm_sm_unmap`](#c-drm_gpuvm_sm_unmap) to provide the split/merge steps for map and unmap
operations to drivers.

#### <a id="c-drm_gpuva_op_remap_to_unmap_range"></a>`drm_gpuva_op_remap_to_unmap_range()`

```c
void drm_gpuva_op_remap_to_unmap_range(const struct drm_gpuva_op_remap *op, u64 *start_addr, u64 *range)
```

Helper to get the start and range of the unmap stage of a remap op.

**Parameters**

- `const struct drm_gpuva_op_remap *op`: Remap op.
- `u64 *start_addr`: Output pointer for the start of the required unmap.
- `u64 *range`: Output pointer for the length of the required unmap.

**Description**

The given start address and range will be set such that they represent the
range of the address space that was previously covered by the mapping being
re-mapped, but is now empty.



#### <a id="c-drm_gpuvm_range_valid"></a>`drm_gpuvm_range_valid()`

```c
bool drm_gpuvm_range_valid(struct drm_gpuvm *gpuvm, u64 addr, u64 range)
```

checks whether the given range is valid for the given [`drm_gpuvm`](#c-struct-drm_gpuvm)

**Parameters**

- `struct drm_gpuvm *gpuvm`: the GPUVM to check the range for
- `u64 addr`: the base address
- `u64 range`: the range starting from the base address

**Description**

Checks whether the range is within the GPUVM's managed boundaries.

**Return**

true for a valid range, false otherwise

#### <a id="c-drm_gpuvm_resv_object_alloc"></a>`drm_gpuvm_resv_object_alloc()`

```c
struct drm_gem_object * drm_gpuvm_resv_object_alloc(struct drm_device *drm)
```

allocate a dummy [`drm_gem_object`](#c-struct-drm_gem_object)

**Parameters**

- `struct drm_device *drm`: the drivers [`drm_device`](/kernel/hardware/gpu/drm-internals.md#c-struct-drm_device)

**Description**

Allocates a dummy [`drm_gem_object`](#c-struct-drm_gem_object) which can be passed to [`drm_gpuvm_init()`](#c-drm_gpuvm_init) in
order to serve as root GEM object providing the `drm_resv` shared across
`drm_gem_objects` local to a single GPUVM.

**Return**

the [`drm_gem_object`](#c-struct-drm_gem_object) on success, NULL on failure

#### <a id="c-drm_gpuvm_init"></a>`drm_gpuvm_init()`

```c
void drm_gpuvm_init(struct drm_gpuvm *gpuvm, const char *name, enum drm_gpuvm_flags flags, struct drm_device *drm, struct drm_gem_object *r_obj, u64 start_offset, u64 range, u64 reserve_offset, u64 reserve_range, const struct drm_gpuvm_ops *ops)
```

initialize a [`drm_gpuvm`](#c-struct-drm_gpuvm)

**Parameters**

- `struct drm_gpuvm *gpuvm`: pointer to the [`drm_gpuvm`](#c-struct-drm_gpuvm) to initialize
- `const char *name`: the name of the GPU VA space
- `enum drm_gpuvm_flags flags`: the [`drm_gpuvm_flags`](#c-enum-drm_gpuvm_flags) for this GPUVM
- `struct drm_device *drm`: the [`drm_device`](/kernel/hardware/gpu/drm-internals.md#c-struct-drm_device) this VM resides in
- `struct drm_gem_object *r_obj`: the resv [`drm_gem_object`](#c-struct-drm_gem_object) providing the GPUVM's common [`dma_resv`](/kernel/hardware/driver-api/io-and-dma/dma-buf.md#c-struct-dma_resv)
- `u64 start_offset`: the start offset of the GPU VA space
- `u64 range`: the size of the GPU VA space
- `u64 reserve_offset`: the start of the kernel reserved GPU VA area
- `u64 reserve_range`: the size of the kernel reserved GPU VA area
- `const struct drm_gpuvm_ops *ops`: [`drm_gpuvm_ops`](#c-struct-drm_gpuvm_ops) called on [`drm_gpuvm_sm_map`](#c-drm_gpuvm_sm_map) / [`drm_gpuvm_sm_unmap`](#c-drm_gpuvm_sm_unmap)

**Description**

The [`drm_gpuvm`](#c-struct-drm_gpuvm) must be initialized with this function before use.

Note that **gpuvm** must be cleared to 0 before calling this function. The given
`name` is expected to be managed by the surrounding driver structures.

#### <a id="c-drm_gpuvm_put"></a>`drm_gpuvm_put()`

```c
void drm_gpuvm_put(struct drm_gpuvm *gpuvm)
```

drop a struct drm_gpuvm reference

**Parameters**

- `struct drm_gpuvm *gpuvm`: the [`drm_gpuvm`](#c-struct-drm_gpuvm) to release the reference of

**Description**

This releases a reference to **gpuvm**.

This function may be called from atomic context.

#### <a id="c-drm_gpuvm_prepare_vm"></a>`drm_gpuvm_prepare_vm()`

```c
int drm_gpuvm_prepare_vm(struct drm_gpuvm *gpuvm, struct drm_exec *exec, unsigned int num_fences)
```

prepare the GPUVMs common dma-resv

**Parameters**

- `struct drm_gpuvm *gpuvm`: the [`drm_gpuvm`](#c-struct-drm_gpuvm)
- `struct drm_exec *exec`: the [`drm_exec`](#c-struct-drm_exec) context
- `unsigned int num_fences`: the amount of `dma_fences` to reserve

**Description**

Calls [`drm_exec_prepare_obj()`](#c-drm_exec_prepare_obj) for the GPUVMs dummy [`drm_gem_object`](#c-struct-drm_gem_object); if
**num_fences** is zero [`drm_exec_lock_obj()`](#c-drm_exec_lock_obj) is called instead.

Using this function directly, it is the drivers responsibility to call
[`drm_exec_init()`](#c-drm_exec_init) and [`drm_exec_fini()`](#c-drm_exec_fini) accordingly.

**Return**

0 on success, negative error code on failure.

#### <a id="c-drm_gpuvm_prepare_objects"></a>`drm_gpuvm_prepare_objects()`

```c
int drm_gpuvm_prepare_objects(struct drm_gpuvm *gpuvm, struct drm_exec *exec, unsigned int num_fences)
```

prepare all associated BOs

**Parameters**

- `struct drm_gpuvm *gpuvm`: the [`drm_gpuvm`](#c-struct-drm_gpuvm)
- `struct drm_exec *exec`: the [`drm_exec`](#c-struct-drm_exec) locking context
- `unsigned int num_fences`: the amount of `dma_fences` to reserve

**Description**

Calls [`drm_exec_prepare_obj()`](#c-drm_exec_prepare_obj) for all `drm_gem_objects` the given
[`drm_gpuvm`](#c-struct-drm_gpuvm) contains mappings of; if **num_fences** is zero [`drm_exec_lock_obj()`](#c-drm_exec_lock_obj)
is called instead.

Using this function directly, it is the drivers responsibility to call
[`drm_exec_init()`](#c-drm_exec_init) and [`drm_exec_fini()`](#c-drm_exec_fini) accordingly.

**Note**

This function is safe against concurrent insertion and removal of
external objects, however it is not safe against concurrent usage itself.

Drivers need to make sure to protect this case with either an outer VM lock
or by calling [`drm_gpuvm_prepare_vm()`](#c-drm_gpuvm_prepare_vm) before this function within the
[`drm_exec_until_all_locked()`](#c-drm_exec_until_all_locked) loop, such that the GPUVM's dma-resv lock ensures
mutual exclusion.

**Return**

0 on success, negative error code on failure.

#### <a id="c-drm_gpuvm_prepare_range"></a>`drm_gpuvm_prepare_range()`

```c
int drm_gpuvm_prepare_range(struct drm_gpuvm *gpuvm, struct drm_exec *exec, u64 addr, u64 range, unsigned int num_fences)
```

prepare all BOs mapped within a given range

**Parameters**

- `struct drm_gpuvm *gpuvm`: the [`drm_gpuvm`](#c-struct-drm_gpuvm)
- `struct drm_exec *exec`: the [`drm_exec`](#c-struct-drm_exec) locking context
- `u64 addr`: the start address within the VA space
- `u64 range`: the range to iterate within the VA space
- `unsigned int num_fences`: the amount of `dma_fences` to reserve

**Description**

Calls [`drm_exec_prepare_obj()`](#c-drm_exec_prepare_obj) for all `drm_gem_objects` mapped between **addr**
and **addr** + **range**; if **num_fences** is zero [`drm_exec_lock_obj()`](#c-drm_exec_lock_obj) is called
instead.

**Return**

0 on success, negative error code on failure.

#### <a id="c-drm_gpuvm_exec_lock"></a>`drm_gpuvm_exec_lock()`

```c
int drm_gpuvm_exec_lock(struct drm_gpuvm_exec *vm_exec)
```

lock all dma-resv of all associated BOs

**Parameters**

- `struct drm_gpuvm_exec *vm_exec`: the [`drm_gpuvm_exec`](#c-struct-drm_gpuvm_exec) wrapper

**Description**

Acquires all dma-resv locks of all `drm_gem_objects` the given
[`drm_gpuvm`](#c-struct-drm_gpuvm) contains mappings of.

Additionally, when calling this function with struct drm_gpuvm_exec::extra
being set the driver receives the given **fn** callback to lock additional
dma-resv in the context of the [`drm_gpuvm_exec`](#c-struct-drm_gpuvm_exec) instance. Typically, drivers
would call [`drm_exec_prepare_obj()`](#c-drm_exec_prepare_obj) from within this callback.

**Return**

0 on success, negative error code on failure.

#### <a id="c-drm_gpuvm_exec_lock_array"></a>`drm_gpuvm_exec_lock_array()`

```c
int drm_gpuvm_exec_lock_array(struct drm_gpuvm_exec *vm_exec, struct drm_gem_object **objs, unsigned int num_objs)
```

lock all dma-resv of all associated BOs

**Parameters**

- `struct drm_gpuvm_exec *vm_exec`: the [`drm_gpuvm_exec`](#c-struct-drm_gpuvm_exec) wrapper
- `struct drm_gem_object **objs`: additional `drm_gem_objects` to lock
- `unsigned int num_objs`: the number of additional `drm_gem_objects` to lock

**Description**

Acquires all dma-resv locks of all `drm_gem_objects` the given [`drm_gpuvm`](#c-struct-drm_gpuvm)
contains mappings of, plus the ones given through **objs**.

**Return**

0 on success, negative error code on failure.

#### <a id="c-drm_gpuvm_exec_lock_range"></a>`drm_gpuvm_exec_lock_range()`

```c
int drm_gpuvm_exec_lock_range(struct drm_gpuvm_exec *vm_exec, u64 addr, u64 range)
```

prepare all BOs mapped within a given range

**Parameters**

- `struct drm_gpuvm_exec *vm_exec`: the [`drm_gpuvm_exec`](#c-struct-drm_gpuvm_exec) wrapper
- `u64 addr`: the start address within the VA space
- `u64 range`: the range to iterate within the VA space

**Description**

Acquires all dma-resv locks of all `drm_gem_objects` mapped between **addr** and
**addr** + **range**.

**Return**

0 on success, negative error code on failure.

#### <a id="c-drm_gpuvm_validate"></a>`drm_gpuvm_validate()`

```c
int drm_gpuvm_validate(struct drm_gpuvm *gpuvm, struct drm_exec *exec)
```

validate all BOs marked as evicted

**Parameters**

- `struct drm_gpuvm *gpuvm`: the [`drm_gpuvm`](#c-struct-drm_gpuvm) to validate evicted BOs
- `struct drm_exec *exec`: the [`drm_exec`](#c-struct-drm_exec) instance used for locking the GPUVM

**Description**

Calls the [`drm_gpuvm_ops`](#c-struct-drm_gpuvm_ops)::vm_bo_validate callback for all evicted buffer
objects being mapped in the given [`drm_gpuvm`](#c-struct-drm_gpuvm).

**Return**

0 on success, negative error code on failure.

#### <a id="c-drm_gpuvm_resv_add_fence"></a>`drm_gpuvm_resv_add_fence()`

```c
void drm_gpuvm_resv_add_fence(struct drm_gpuvm *gpuvm, struct drm_exec *exec, struct dma_fence *fence, enum dma_resv_usage private_usage, enum dma_resv_usage extobj_usage)
```

add fence to private and all extobj dma-resv

**Parameters**

- `struct drm_gpuvm *gpuvm`: the [`drm_gpuvm`](#c-struct-drm_gpuvm) to add a fence to
- `struct drm_exec *exec`: the [`drm_exec`](#c-struct-drm_exec) locking context
- `struct dma_fence *fence`: fence to add
- `enum dma_resv_usage private_usage`: private dma-resv usage
- `enum dma_resv_usage extobj_usage`: extobj dma-resv usage

#### <a id="c-drm_gpuvm_bo_create"></a>`drm_gpuvm_bo_create()`

```c
struct drm_gpuvm_bo * drm_gpuvm_bo_create(struct drm_gpuvm *gpuvm, struct drm_gem_object *obj)
```

create a new instance of struct drm_gpuvm_bo

**Parameters**

- `struct drm_gpuvm *gpuvm`: The [`drm_gpuvm`](#c-struct-drm_gpuvm) the **obj** is mapped in.
- `struct drm_gem_object *obj`: The [`drm_gem_object`](#c-struct-drm_gem_object) being mapped in the **gpuvm**.

**Description**

If provided by the driver, this function uses the [`drm_gpuvm_ops`](#c-struct-drm_gpuvm_ops)
`vm_bo_alloc()` callback to allocate.

**Return**

a pointer to the [`drm_gpuvm_bo`](#c-struct-drm_gpuvm_bo) on success, NULL on failure

#### <a id="c-drm_gpuvm_bo_put"></a>`drm_gpuvm_bo_put()`

```c
bool drm_gpuvm_bo_put(struct drm_gpuvm_bo *vm_bo)
```

drop a struct drm_gpuvm_bo reference

**Parameters**

- `struct drm_gpuvm_bo *vm_bo`: the [`drm_gpuvm_bo`](#c-struct-drm_gpuvm_bo) to release the reference of

**Description**

This releases a reference to **vm_bo**.

If the reference count drops to zero, the `gpuvm_bo` is destroyed, which
includes removing it from the GEMs gpuva list. Hence, if a call to this
function can potentially let the reference count drop to zero the caller must
hold the lock that the GEM uses for its gpuva list (either the GEM's
dma-resv or gpuva.lock mutex).

This function may only be called from non-atomic context.

**Return**

true if vm_bo was destroyed, false otherwise.

#### <a id="c-drm_gpuvm_bo_put_deferred"></a>`drm_gpuvm_bo_put_deferred()`

```c
bool drm_gpuvm_bo_put_deferred(struct drm_gpuvm_bo *vm_bo)
```

drop a struct drm_gpuvm_bo reference with deferred cleanup

**Parameters**

- `struct drm_gpuvm_bo *vm_bo`: the [`drm_gpuvm_bo`](#c-struct-drm_gpuvm_bo) to release the reference of

**Description**

This releases a reference to **vm_bo**.

This might take and release the GEMs GPUVA lock. You should call
[`drm_gpuvm_bo_deferred_cleanup()`](#c-drm_gpuvm_bo_deferred_cleanup) later to complete the cleanup process.

**Return**

true if vm_bo is being destroyed, false otherwise.

#### <a id="c-drm_gpuvm_bo_deferred_cleanup"></a>`drm_gpuvm_bo_deferred_cleanup()`

```c
void drm_gpuvm_bo_deferred_cleanup(struct drm_gpuvm *gpuvm)
```

clean up BOs in the deferred list deferred cleanup

**Parameters**

- `struct drm_gpuvm *gpuvm`: the VM to clean up

**Description**

Cleans up [`drm_gpuvm_bo`](#c-struct-drm_gpuvm_bo) instances in the deferred cleanup list.

#### <a id="c-drm_gpuvm_bo_find"></a>`drm_gpuvm_bo_find()`

```c
struct drm_gpuvm_bo * drm_gpuvm_bo_find(struct drm_gpuvm *gpuvm, struct drm_gem_object *obj)
```

find the [`drm_gpuvm_bo`](#c-struct-drm_gpuvm_bo) for the given [`drm_gpuvm`](#c-struct-drm_gpuvm) and [`drm_gem_object`](#c-struct-drm_gem_object)

**Parameters**

- `struct drm_gpuvm *gpuvm`: The [`drm_gpuvm`](#c-struct-drm_gpuvm) the **obj** is mapped in.
- `struct drm_gem_object *obj`: The [`drm_gem_object`](#c-struct-drm_gem_object) being mapped in the **gpuvm**.

**Description**

Find the [`drm_gpuvm_bo`](#c-struct-drm_gpuvm_bo) representing the combination of the given
[`drm_gpuvm`](#c-struct-drm_gpuvm) and [`drm_gem_object`](#c-struct-drm_gem_object). If found, increases the reference
count of the [`drm_gpuvm_bo`](#c-struct-drm_gpuvm_bo) accordingly.

**Return**

a pointer to the [`drm_gpuvm_bo`](#c-struct-drm_gpuvm_bo) on success, NULL on failure

#### <a id="c-drm_gpuvm_bo_obtain_locked"></a>`drm_gpuvm_bo_obtain_locked()`

```c
struct drm_gpuvm_bo * drm_gpuvm_bo_obtain_locked(struct drm_gpuvm *gpuvm, struct drm_gem_object *obj)
```

obtains an instance of the [`drm_gpuvm_bo`](#c-struct-drm_gpuvm_bo) for the given [`drm_gpuvm`](#c-struct-drm_gpuvm) and [`drm_gem_object`](#c-struct-drm_gem_object)

**Parameters**

- `struct drm_gpuvm *gpuvm`: The [`drm_gpuvm`](#c-struct-drm_gpuvm) the **obj** is mapped in.
- `struct drm_gem_object *obj`: The [`drm_gem_object`](#c-struct-drm_gem_object) being mapped in the **gpuvm**.

**Description**

Find the [`drm_gpuvm_bo`](#c-struct-drm_gpuvm_bo) representing the combination of the given
[`drm_gpuvm`](#c-struct-drm_gpuvm) and [`drm_gem_object`](#c-struct-drm_gem_object). If found, increases the reference
count of the [`drm_gpuvm_bo`](#c-struct-drm_gpuvm_bo) accordingly. If not found, allocates a new
[`drm_gpuvm_bo`](#c-struct-drm_gpuvm_bo).

Requires the lock for the GEMs gpuva list.

A new [`drm_gpuvm_bo`](#c-struct-drm_gpuvm_bo) is added to the GEMs gpuva list.

**Return**

a pointer to the [`drm_gpuvm_bo`](#c-struct-drm_gpuvm_bo) on success, an ERR_PTR on failure

#### <a id="c-drm_gpuvm_bo_obtain_prealloc"></a>`drm_gpuvm_bo_obtain_prealloc()`

```c
struct drm_gpuvm_bo * drm_gpuvm_bo_obtain_prealloc(struct drm_gpuvm_bo *__vm_bo)
```

obtains an instance of the [`drm_gpuvm_bo`](#c-struct-drm_gpuvm_bo) for the given [`drm_gpuvm`](#c-struct-drm_gpuvm) and [`drm_gem_object`](#c-struct-drm_gem_object)

**Parameters**

- `struct drm_gpuvm_bo *__vm_bo`: A pre-allocated struct drm_gpuvm_bo.

**Description**

Find the [`drm_gpuvm_bo`](#c-struct-drm_gpuvm_bo) representing the combination of the given
[`drm_gpuvm`](#c-struct-drm_gpuvm) and [`drm_gem_object`](#c-struct-drm_gem_object). If found, increases the reference
count of the found [`drm_gpuvm_bo`](#c-struct-drm_gpuvm_bo) accordingly, while the **__vm_bo** reference
count is decreased. If not found **__vm_bo** is returned without further
increase of the reference count.

The provided **__vm_bo** must not already be in the gpuva, evict, or extobj
lists prior to calling this method.

A new [`drm_gpuvm_bo`](#c-struct-drm_gpuvm_bo) is added to the GEMs gpuva list.

**Return**

a pointer to the found [`drm_gpuvm_bo`](#c-struct-drm_gpuvm_bo) or **__vm_bo** if no existing
[`drm_gpuvm_bo`](#c-struct-drm_gpuvm_bo) was found

#### <a id="c-drm_gpuvm_bo_extobj_add"></a>`drm_gpuvm_bo_extobj_add()`

```c
void drm_gpuvm_bo_extobj_add(struct drm_gpuvm_bo *vm_bo)
```

adds the [`drm_gpuvm_bo`](#c-struct-drm_gpuvm_bo) to its [`drm_gpuvm`](#c-struct-drm_gpuvm)'s extobj list

**Parameters**

- `struct drm_gpuvm_bo *vm_bo`: The [`drm_gpuvm_bo`](#c-struct-drm_gpuvm_bo) to add to its [`drm_gpuvm`](#c-struct-drm_gpuvm)'s the extobj list.

**Description**

Adds the given **vm_bo** to its [`drm_gpuvm`](#c-struct-drm_gpuvm)'s extobj list if not on the list
already and if the corresponding [`drm_gem_object`](#c-struct-drm_gem_object) is an external object,
actually.

#### <a id="c-drm_gpuvm_bo_evict"></a>`drm_gpuvm_bo_evict()`

```c
void drm_gpuvm_bo_evict(struct drm_gpuvm_bo *vm_bo, bool evict)
```

add / remove a [`drm_gpuvm_bo`](#c-struct-drm_gpuvm_bo) to / from the `drm_gpuvms` evicted list

**Parameters**

- `struct drm_gpuvm_bo *vm_bo`: the [`drm_gpuvm_bo`](#c-struct-drm_gpuvm_bo) to add or remove
- `bool evict`: indicates whether the object is evicted

**Description**

Adds a [`drm_gpuvm_bo`](#c-struct-drm_gpuvm_bo) to or removes it from the [`drm_gpuvm`](#c-struct-drm_gpuvm)'s evicted list.

#### <a id="c-drm_gpuva_insert"></a>`drm_gpuva_insert()`

```c
int drm_gpuva_insert(struct drm_gpuvm *gpuvm, struct drm_gpuva *va)
```

insert a [`drm_gpuva`](#c-struct-drm_gpuva)

**Parameters**

- `struct drm_gpuvm *gpuvm`: the [`drm_gpuvm`](#c-struct-drm_gpuvm) to insert the [`drm_gpuva`](#c-struct-drm_gpuva) in
- `struct drm_gpuva *va`: the [`drm_gpuva`](#c-struct-drm_gpuva) to insert

**Description**

Insert a [`drm_gpuva`](#c-struct-drm_gpuva) with a given address and range into a
[`drm_gpuvm`](#c-struct-drm_gpuvm).

It is safe to use this function using the safe versions of iterating the GPU
VA space, such as [`drm_gpuvm_for_each_va_safe()`](#c-drm_gpuvm_for_each_va_safe) and
[`drm_gpuvm_for_each_va_range_safe()`](#c-drm_gpuvm_for_each_va_range_safe).

**Return**

0 on success, negative error code on failure.

#### <a id="c-drm_gpuva_remove"></a>`drm_gpuva_remove()`

```c
void drm_gpuva_remove(struct drm_gpuva *va)
```

remove a [`drm_gpuva`](#c-struct-drm_gpuva)

**Parameters**

- `struct drm_gpuva *va`: the [`drm_gpuva`](#c-struct-drm_gpuva) to remove

**Description**

This removes the given `va` from the underlying tree.

It is safe to use this function using the safe versions of iterating the GPU
VA space, such as [`drm_gpuvm_for_each_va_safe()`](#c-drm_gpuvm_for_each_va_safe) and
[`drm_gpuvm_for_each_va_range_safe()`](#c-drm_gpuvm_for_each_va_range_safe).

#### <a id="c-drm_gpuva_link"></a>`drm_gpuva_link()`

```c
void drm_gpuva_link(struct drm_gpuva *va, struct drm_gpuvm_bo *vm_bo)
```

link a [`drm_gpuva`](#c-struct-drm_gpuva)

**Parameters**

- `struct drm_gpuva *va`: the [`drm_gpuva`](#c-struct-drm_gpuva) to link
- `struct drm_gpuvm_bo *vm_bo`: the [`drm_gpuvm_bo`](#c-struct-drm_gpuvm_bo) to add the [`drm_gpuva`](#c-struct-drm_gpuva) to

**Description**

This adds the given `va` to the GPU VA list of the [`drm_gpuvm_bo`](#c-struct-drm_gpuvm_bo) and the
[`drm_gpuvm_bo`](#c-struct-drm_gpuvm_bo) to the [`drm_gem_object`](#c-struct-drm_gem_object) it is associated with.

For every [`drm_gpuva`](#c-struct-drm_gpuva) entry added to the [`drm_gpuvm_bo`](#c-struct-drm_gpuvm_bo) an additional
reference of the latter is taken.

This function expects the caller to protect the GEM's GPUVA list against
concurrent access using either the GEM's dma-resv or gpuva.lock mutex.

#### <a id="c-drm_gpuva_unlink"></a>`drm_gpuva_unlink()`

```c
void drm_gpuva_unlink(struct drm_gpuva *va)
```

unlink a [`drm_gpuva`](#c-struct-drm_gpuva)

**Parameters**

- `struct drm_gpuva *va`: the [`drm_gpuva`](#c-struct-drm_gpuva) to unlink

**Description**

This removes the given `va` from the GPU VA list of the [`drm_gem_object`](#c-struct-drm_gem_object) it is
associated with.

This removes the given `va` from the GPU VA list of the [`drm_gpuvm_bo`](#c-struct-drm_gpuvm_bo) and
the [`drm_gpuvm_bo`](#c-struct-drm_gpuvm_bo) from the [`drm_gem_object`](#c-struct-drm_gem_object) it is associated with in case
this call unlinks the last [`drm_gpuva`](#c-struct-drm_gpuva) from the [`drm_gpuvm_bo`](#c-struct-drm_gpuvm_bo).

For every [`drm_gpuva`](#c-struct-drm_gpuva) entry removed from the [`drm_gpuvm_bo`](#c-struct-drm_gpuvm_bo) a reference of
the latter is dropped.

This function expects the caller to protect the GEM's GPUVA list against
concurrent access using either the GEM's dma-resv or gpuva.lock mutex.

#### <a id="c-drm_gpuva_unlink_defer"></a>`drm_gpuva_unlink_defer()`

```c
void drm_gpuva_unlink_defer(struct drm_gpuva *va)
```

unlink a [`drm_gpuva`](#c-struct-drm_gpuva) with deferred vm_bo cleanup

**Parameters**

- `struct drm_gpuva *va`: the [`drm_gpuva`](#c-struct-drm_gpuva) to unlink

**Description**

Similar to [`drm_gpuva_unlink()`](#c-drm_gpuva_unlink), but uses [`drm_gpuvm_bo_put_deferred()`](#c-drm_gpuvm_bo_put_deferred) and takes
the lock for the caller.

#### <a id="c-drm_gpuva_find_first"></a>`drm_gpuva_find_first()`

```c
struct drm_gpuva * drm_gpuva_find_first(struct drm_gpuvm *gpuvm, u64 addr, u64 range)
```

find the first [`drm_gpuva`](#c-struct-drm_gpuva) in the given range

**Parameters**

- `struct drm_gpuvm *gpuvm`: the [`drm_gpuvm`](#c-struct-drm_gpuvm) to search in
- `u64 addr`: the `drm_gpuvas` address
- `u64 range`: the `drm_gpuvas` range

**Return**

the first [`drm_gpuva`](#c-struct-drm_gpuva) within the given range

#### <a id="c-drm_gpuva_find"></a>`drm_gpuva_find()`

```c
struct drm_gpuva * drm_gpuva_find(struct drm_gpuvm *gpuvm, u64 addr, u64 range)
```

find a [`drm_gpuva`](#c-struct-drm_gpuva)

**Parameters**

- `struct drm_gpuvm *gpuvm`: the [`drm_gpuvm`](#c-struct-drm_gpuvm) to search in
- `u64 addr`: the `drm_gpuvas` address
- `u64 range`: the `drm_gpuvas` range

**Return**

the [`drm_gpuva`](#c-struct-drm_gpuva) at a given `addr` and with a given `range`

#### <a id="c-drm_gpuva_find_prev"></a>`drm_gpuva_find_prev()`

```c
struct drm_gpuva * drm_gpuva_find_prev(struct drm_gpuvm *gpuvm, u64 start)
```

find the [`drm_gpuva`](#c-struct-drm_gpuva) before the given address

**Parameters**

- `struct drm_gpuvm *gpuvm`: the [`drm_gpuvm`](#c-struct-drm_gpuvm) to search in
- `u64 start`: the given GPU VA's start address

**Description**

Find the adjacent [`drm_gpuva`](#c-struct-drm_gpuva) before the GPU VA with given `start` address.

Note that if there is any free space between the GPU VA mappings no mapping
is returned.

**Return**

a pointer to the found [`drm_gpuva`](#c-struct-drm_gpuva) or NULL if none was found

#### <a id="c-drm_gpuva_find_next"></a>`drm_gpuva_find_next()`

```c
struct drm_gpuva * drm_gpuva_find_next(struct drm_gpuvm *gpuvm, u64 end)
```

find the [`drm_gpuva`](#c-struct-drm_gpuva) after the given address

**Parameters**

- `struct drm_gpuvm *gpuvm`: the [`drm_gpuvm`](#c-struct-drm_gpuvm) to search in
- `u64 end`: the given GPU VA's end address

**Description**

Find the adjacent [`drm_gpuva`](#c-struct-drm_gpuva) after the GPU VA with given `end` address.

Note that if there is any free space between the GPU VA mappings no mapping
is returned.

**Return**

a pointer to the found [`drm_gpuva`](#c-struct-drm_gpuva) or NULL if none was found

#### <a id="c-drm_gpuvm_interval_empty"></a>`drm_gpuvm_interval_empty()`

```c
bool drm_gpuvm_interval_empty(struct drm_gpuvm *gpuvm, u64 addr, u64 range)
```

indicate whether a given interval of the VA space is empty

**Parameters**

- `struct drm_gpuvm *gpuvm`: the [`drm_gpuvm`](#c-struct-drm_gpuvm) to check the range for
- `u64 addr`: the start address of the range
- `u64 range`: the range of the interval

**Return**

true if the interval is empty, false otherwise

#### <a id="c-drm_gpuva_map"></a>`drm_gpuva_map()`

```c
void drm_gpuva_map(struct drm_gpuvm *gpuvm, struct drm_gpuva *va, const struct drm_gpuva_op_map *op)
```

helper to insert a [`drm_gpuva`](#c-struct-drm_gpuva) according to a [`drm_gpuva_op_map`](#c-struct-drm_gpuva_op_map)

**Parameters**

- `struct drm_gpuvm *gpuvm`: the [`drm_gpuvm`](#c-struct-drm_gpuvm)
- `struct drm_gpuva *va`: the [`drm_gpuva`](#c-struct-drm_gpuva) to insert
- `const struct drm_gpuva_op_map *op`: the [`drm_gpuva_op_map`](#c-struct-drm_gpuva_op_map) to initialize **va** with

**Description**

Initializes the **va** from the **op** and inserts it into the given **gpuvm**.

#### <a id="c-drm_gpuva_remap"></a>`drm_gpuva_remap()`

```c
void drm_gpuva_remap(struct drm_gpuva *prev, struct drm_gpuva *next, const struct drm_gpuva_op_remap *op)
```

helper to remap a [`drm_gpuva`](#c-struct-drm_gpuva) according to a [`drm_gpuva_op_remap`](#c-struct-drm_gpuva_op_remap)

**Parameters**

- `struct drm_gpuva *prev`: the [`drm_gpuva`](#c-struct-drm_gpuva) to remap when keeping the start of a mapping
- `struct drm_gpuva *next`: the [`drm_gpuva`](#c-struct-drm_gpuva) to remap when keeping the end of a mapping
- `const struct drm_gpuva_op_remap *op`: the [`drm_gpuva_op_remap`](#c-struct-drm_gpuva_op_remap) to initialize **prev** and **next** with

**Description**

Removes the currently mapped [`drm_gpuva`](#c-struct-drm_gpuva) and remaps it using **prev** and/or
**next**.

#### <a id="c-drm_gpuva_unmap"></a>`drm_gpuva_unmap()`

```c
void drm_gpuva_unmap(const struct drm_gpuva_op_unmap *op)
```

helper to remove a [`drm_gpuva`](#c-struct-drm_gpuva) according to a [`drm_gpuva_op_unmap`](#c-struct-drm_gpuva_op_unmap)

**Parameters**

- `const struct drm_gpuva_op_unmap *op`: the [`drm_gpuva_op_unmap`](#c-struct-drm_gpuva_op_unmap) specifying the [`drm_gpuva`](#c-struct-drm_gpuva) to remove

**Description**

Removes the [`drm_gpuva`](#c-struct-drm_gpuva) associated with the [`drm_gpuva_op_unmap`](#c-struct-drm_gpuva_op_unmap).

#### <a id="c-drm_gpuvm_sm_map"></a>`drm_gpuvm_sm_map()`

```c
int drm_gpuvm_sm_map(struct drm_gpuvm *gpuvm, void *priv, const struct drm_gpuvm_map_req *req)
```

calls the [`drm_gpuva_op`](#c-struct-drm_gpuva_op) split/merge steps

**Parameters**

- `struct drm_gpuvm *gpuvm`: the [`drm_gpuvm`](#c-struct-drm_gpuvm) representing the GPU VA space
- `void *priv`: pointer to a driver private data structure
- `const struct drm_gpuvm_map_req *req`: ptr to struct drm_gpuvm_map_req

**Description**

This function iterates the given range of the GPU VA space. It utilizes the
[`drm_gpuvm_ops`](#c-struct-drm_gpuvm_ops) to call back into the driver providing the split and merge
steps.

Drivers may use these callbacks to update the GPU VA space right away within
the callback. In case the driver decides to copy and store the operations for
later processing neither this function nor [`drm_gpuvm_sm_unmap`](#c-drm_gpuvm_sm_unmap) is allowed to
be called before the [`drm_gpuvm`](#c-struct-drm_gpuvm)'s view of the GPU VA space was
updated with the previous set of operations. To update the
[`drm_gpuvm`](#c-struct-drm_gpuvm)'s view of the GPU VA space [`drm_gpuva_insert()`](#c-drm_gpuva_insert),
`drm_gpuva_destroy_locked()` and/or `drm_gpuva_destroy_unlocked()` should be
used.

A sequence of callbacks can contain map, unmap and remap operations, but
the sequence of callbacks might also be empty if no operation is required,
e.g. if the requested mapping already exists in the exact same way.

There can be an arbitrary amount of unmap operations, a maximum of two remap
operations and a single map operation. The latter one represents the original
map operation requested by the caller.

**Return**

0 on success or a negative error code

#### <a id="c-drm_gpuvm_sm_unmap"></a>`drm_gpuvm_sm_unmap()`

```c
int drm_gpuvm_sm_unmap(struct drm_gpuvm *gpuvm, void *priv, u64 req_addr, u64 req_range)
```

calls the [`drm_gpuva_ops`](#c-struct-drm_gpuva_ops) to split on unmap

**Parameters**

- `struct drm_gpuvm *gpuvm`: the [`drm_gpuvm`](#c-struct-drm_gpuvm) representing the GPU VA space
- `void *priv`: pointer to a driver private data structure
- `u64 req_addr`: the start address of the range to unmap
- `u64 req_range`: the range of the mappings to unmap

**Description**

This function iterates the given range of the GPU VA space. It utilizes the
[`drm_gpuvm_ops`](#c-struct-drm_gpuvm_ops) to call back into the driver providing the operations to
unmap and, if required, split existing mappings.

Drivers may use these callbacks to update the GPU VA space right away within
the callback. In case the driver decides to copy and store the operations for
later processing neither this function nor [`drm_gpuvm_sm_map`](#c-drm_gpuvm_sm_map) is allowed to be
called before the [`drm_gpuvm`](#c-struct-drm_gpuvm)'s view of the GPU VA space was updated
with the previous set of operations. To update the [`drm_gpuvm`](#c-struct-drm_gpuvm)'s view
of the GPU VA space [`drm_gpuva_insert()`](#c-drm_gpuva_insert), `drm_gpuva_destroy_locked()` and/or
`drm_gpuva_destroy_unlocked()` should be used.

A sequence of callbacks can contain unmap and remap operations, depending on
whether there are actual overlapping mappings to split.

There can be an arbitrary amount of unmap operations and a maximum of two
remap operations.

**Return**

0 on success or a negative error code

#### <a id="c-drm_gpuvm_sm_map_exec_lock"></a>`drm_gpuvm_sm_map_exec_lock()`

```c
int drm_gpuvm_sm_map_exec_lock(struct drm_gpuvm *gpuvm, struct drm_exec *exec, unsigned int num_fences, struct drm_gpuvm_map_req *req)
```

locks the objects touched by a [`drm_gpuvm_sm_map()`](#c-drm_gpuvm_sm_map)

**Parameters**

- `struct drm_gpuvm *gpuvm`: the [`drm_gpuvm`](#c-struct-drm_gpuvm) representing the GPU VA space
- `struct drm_exec *exec`: the [`drm_exec`](#c-struct-drm_exec) locking context
- `unsigned int num_fences`: for newly mapped objects, the # of fences to reserve
- `struct drm_gpuvm_map_req *req`: ptr to drm_gpuvm_map_req struct

**Description**

This function locks ([`drm_exec_lock_obj()`](#c-drm_exec_lock_obj)) objects that will be unmapped/
remapped, and locks+prepares (`drm_exec_prepare_object()`) objects that
will be newly mapped.

The expected usage is:

```text
vm_bind {
    struct drm_exec exec;

    // IGNORE_DUPLICATES is required, INTERRUPTIBLE_WAIT is recommended:
    drm_exec_init(&exec, IGNORE_DUPLICATES | INTERRUPTIBLE_WAIT, 0);

    drm_exec_until_all_locked (&exec) {
        for_each_vm_bind_operation {
            switch (op->op) {
            case DRIVER_OP_UNMAP:
                ret = drm_gpuvm_sm_unmap_exec_lock(gpuvm, &exec, op->addr, op->range);
                break;
            case DRIVER_OP_MAP:
                ret = drm_gpuvm_sm_map_exec_lock(gpuvm, &exec, num_fences, &req);
                break;
            }

            drm_exec_retry_on_contention(&exec);
            if (ret)
                return ret;
        }
    }
}
```

This enables all locking to be performed before the driver begins modifying
the VM.  This is safe to do in the case of overlapping DRIVER_VM_BIND_OPs,
where an earlier op can alter the sequence of steps generated for a later
op, because the later altered step will involve the same GEM object(s)
already seen in the earlier locking step.  For example:

1) An earlier driver DRIVER_OP_UNMAP op removes the need for a
   DRM_GPUVA_OP_REMAP/UNMAP step.  This is safe because we've already
   locked the GEM object in the earlier DRIVER_OP_UNMAP op.

2) An earlier DRIVER_OP_MAP op overlaps with a later DRIVER_OP_MAP/UNMAP
   op, introducing a DRM_GPUVA_OP_REMAP/UNMAP that wouldn't have been
   required without the earlier DRIVER_OP_MAP.  This is safe because we've
   already locked the GEM object in the earlier DRIVER_OP_MAP step.

**Return**

0 on success or a negative error code

#### <a id="c-drm_gpuvm_sm_unmap_exec_lock"></a>`drm_gpuvm_sm_unmap_exec_lock()`

```c
int drm_gpuvm_sm_unmap_exec_lock(struct drm_gpuvm *gpuvm, struct drm_exec *exec, u64 req_addr, u64 req_range)
```

locks the objects touched by [`drm_gpuvm_sm_unmap()`](#c-drm_gpuvm_sm_unmap)

**Parameters**

- `struct drm_gpuvm *gpuvm`: the [`drm_gpuvm`](#c-struct-drm_gpuvm) representing the GPU VA space
- `struct drm_exec *exec`: the [`drm_exec`](#c-struct-drm_exec) locking context
- `u64 req_addr`: the start address of the range to unmap
- `u64 req_range`: the range of the mappings to unmap

**Description**

This function locks ([`drm_exec_lock_obj()`](#c-drm_exec_lock_obj)) objects that will be unmapped/
remapped by [`drm_gpuvm_sm_unmap()`](#c-drm_gpuvm_sm_unmap).

See [`drm_gpuvm_sm_map_exec_lock()`](#c-drm_gpuvm_sm_map_exec_lock) for expected usage.

**Return**

0 on success or a negative error code

#### <a id="c-drm_gpuvm_sm_map_ops_create"></a>`drm_gpuvm_sm_map_ops_create()`

```c
struct drm_gpuva_ops * drm_gpuvm_sm_map_ops_create(struct drm_gpuvm *gpuvm, const struct drm_gpuvm_map_req *req)
```

creates the [`drm_gpuva_ops`](#c-struct-drm_gpuva_ops) to split and merge

**Parameters**

- `struct drm_gpuvm *gpuvm`: the [`drm_gpuvm`](#c-struct-drm_gpuvm) representing the GPU VA space
- `const struct drm_gpuvm_map_req *req`: map request arguments

**Description**

This function creates a list of operations to perform splitting and merging
of existing mapping(s) with the newly requested one.

The list can be iterated with [`drm_gpuva_for_each_op`](#c-drm_gpuva_for_each_op) and must be processed
in the given order. It can contain map, unmap and remap operations, but it
also can be empty if no operation is required, e.g. if the requested mapping
already exists in the exact same way.

There can be an arbitrary amount of unmap operations, a maximum of two remap
operations and a single map operation. The latter one represents the original
map operation requested by the caller.

Note that before calling this function again with another mapping request it
is necessary to update the [`drm_gpuvm`](#c-struct-drm_gpuvm)'s view of the GPU VA space. The
previously obtained operations must be either processed or abandoned. To
update the [`drm_gpuvm`](#c-struct-drm_gpuvm)'s view of the GPU VA space [`drm_gpuva_insert()`](#c-drm_gpuva_insert),
`drm_gpuva_destroy_locked()` and/or `drm_gpuva_destroy_unlocked()` should be
used.

After the caller finished processing the returned [`drm_gpuva_ops`](#c-struct-drm_gpuva_ops), they must
be freed with [`drm_gpuva_ops_free`](#c-drm_gpuva_ops_free).

**Return**

a pointer to the [`drm_gpuva_ops`](#c-struct-drm_gpuva_ops) on success, an ERR_PTR on failure

#### <a id="c-drm_gpuvm_madvise_ops_create"></a>`drm_gpuvm_madvise_ops_create()`

```c
struct drm_gpuva_ops * drm_gpuvm_madvise_ops_create(struct drm_gpuvm *gpuvm, const struct drm_gpuvm_map_req *req)
```

creates the [`drm_gpuva_ops`](#c-struct-drm_gpuva_ops) to split

**Parameters**

- `struct drm_gpuvm *gpuvm`: the [`drm_gpuvm`](#c-struct-drm_gpuvm) representing the GPU VA space
- `const struct drm_gpuvm_map_req *req`: map request arguments

**Description**

This function creates a list of operations to perform splitting
of existent mapping(s) at start or end, based on the request map.

The list can be iterated with [`drm_gpuva_for_each_op`](#c-drm_gpuva_for_each_op) and must be processed
in the given order. It can contain map and remap operations, but it
also can be empty if no operation is required, e.g. if the requested mapping
already exists is the exact same way.

There will be no unmap operations, a maximum of two remap operations and two
map operations. The two map operations correspond to: one from start to the
end of drm_gpuvaX, and another from the start of drm_gpuvaY to end.

Note that before calling this function again with another mapping request it
is necessary to update the [`drm_gpuvm`](#c-struct-drm_gpuvm)'s view of the GPU VA space. The
previously obtained operations must be either processed or abandoned. To
update the [`drm_gpuvm`](#c-struct-drm_gpuvm)'s view of the GPU VA space [`drm_gpuva_insert()`](#c-drm_gpuva_insert),
`drm_gpuva_destroy_locked()` and/or `drm_gpuva_destroy_unlocked()` should be
used.

After the caller finished processing the returned [`drm_gpuva_ops`](#c-struct-drm_gpuva_ops), they must
be freed with [`drm_gpuva_ops_free`](#c-drm_gpuva_ops_free).

**Return**

a pointer to the [`drm_gpuva_ops`](#c-struct-drm_gpuva_ops) on success, an ERR_PTR on failure

#### <a id="c-drm_gpuvm_sm_unmap_ops_create"></a>`drm_gpuvm_sm_unmap_ops_create()`

```c
struct drm_gpuva_ops * drm_gpuvm_sm_unmap_ops_create(struct drm_gpuvm *gpuvm, u64 req_addr, u64 req_range)
```

creates the [`drm_gpuva_ops`](#c-struct-drm_gpuva_ops) to split on unmap

**Parameters**

- `struct drm_gpuvm *gpuvm`: the [`drm_gpuvm`](#c-struct-drm_gpuvm) representing the GPU VA space
- `u64 req_addr`: the start address of the range to unmap
- `u64 req_range`: the range of the mappings to unmap

**Description**

This function creates a list of operations to perform unmapping and, if
required, splitting of the mappings overlapping the unmap range.

The list can be iterated with [`drm_gpuva_for_each_op`](#c-drm_gpuva_for_each_op) and must be processed
in the given order. It can contain unmap and remap operations, depending on
whether there are actual overlapping mappings to split.

There can be an arbitrary amount of unmap operations and a maximum of two
remap operations.

Note that before calling this function again with another range to unmap it
is necessary to update the [`drm_gpuvm`](#c-struct-drm_gpuvm)'s view of the GPU VA space. The
previously obtained operations must be processed or abandoned. To update the
[`drm_gpuvm`](#c-struct-drm_gpuvm)'s view of the GPU VA space [`drm_gpuva_insert()`](#c-drm_gpuva_insert),
`drm_gpuva_destroy_locked()` and/or `drm_gpuva_destroy_unlocked()` should be
used.

After the caller finished processing the returned [`drm_gpuva_ops`](#c-struct-drm_gpuva_ops), they must
be freed with [`drm_gpuva_ops_free`](#c-drm_gpuva_ops_free).

**Return**

a pointer to the [`drm_gpuva_ops`](#c-struct-drm_gpuva_ops) on success, an ERR_PTR on failure

#### <a id="c-drm_gpuvm_prefetch_ops_create"></a>`drm_gpuvm_prefetch_ops_create()`

```c
struct drm_gpuva_ops * drm_gpuvm_prefetch_ops_create(struct drm_gpuvm *gpuvm, u64 addr, u64 range)
```

creates the [`drm_gpuva_ops`](#c-struct-drm_gpuva_ops) to prefetch

**Parameters**

- `struct drm_gpuvm *gpuvm`: the [`drm_gpuvm`](#c-struct-drm_gpuvm) representing the GPU VA space
- `u64 addr`: the start address of the range to prefetch
- `u64 range`: the range of the mappings to prefetch

**Description**

This function creates a list of operations to perform prefetching.

The list can be iterated with [`drm_gpuva_for_each_op`](#c-drm_gpuva_for_each_op) and must be processed
in the given order. It can contain prefetch operations.

There can be an arbitrary amount of prefetch operations.

After the caller finished processing the returned [`drm_gpuva_ops`](#c-struct-drm_gpuva_ops), they must
be freed with [`drm_gpuva_ops_free`](#c-drm_gpuva_ops_free).

**Return**

a pointer to the [`drm_gpuva_ops`](#c-struct-drm_gpuva_ops) on success, an ERR_PTR on failure

#### <a id="c-drm_gpuvm_bo_unmap_ops_create"></a>`drm_gpuvm_bo_unmap_ops_create()`

```c
struct drm_gpuva_ops * drm_gpuvm_bo_unmap_ops_create(struct drm_gpuvm_bo *vm_bo)
```

creates the [`drm_gpuva_ops`](#c-struct-drm_gpuva_ops) to unmap a GEM

**Parameters**

- `struct drm_gpuvm_bo *vm_bo`: the [`drm_gpuvm_bo`](#c-struct-drm_gpuvm_bo) abstraction

**Description**

This function creates a list of operations to perform unmapping for every
GPUVA attached to a GEM.

The list can be iterated with [`drm_gpuva_for_each_op`](#c-drm_gpuva_for_each_op) and consists out of an
arbitrary amount of unmap operations.

After the caller finished processing the returned [`drm_gpuva_ops`](#c-struct-drm_gpuva_ops), they must
be freed with [`drm_gpuva_ops_free`](#c-drm_gpuva_ops_free).

This function expects the caller to protect the GEM's GPUVA list against
concurrent access using either the GEM's dma-resv or gpuva.lock mutex.

**Return**

a pointer to the [`drm_gpuva_ops`](#c-struct-drm_gpuva_ops) on success, an ERR_PTR on failure

#### <a id="c-drm_gpuva_ops_free"></a>`drm_gpuva_ops_free()`

```c
void drm_gpuva_ops_free(struct drm_gpuvm *gpuvm, struct drm_gpuva_ops *ops)
```

free the given [`drm_gpuva_ops`](#c-struct-drm_gpuva_ops)

**Parameters**

- `struct drm_gpuvm *gpuvm`: the [`drm_gpuvm`](#c-struct-drm_gpuvm) the ops were created for
- `struct drm_gpuva_ops *ops`: the [`drm_gpuva_ops`](#c-struct-drm_gpuva_ops) to free

**Description**

Frees the given [`drm_gpuva_ops`](#c-struct-drm_gpuva_ops) structure including all the ops associated
with it.


<a id="rst-drm-buddy-allocator"></a>

## DRM Buddy Allocator

<a id="rst-drm-buddy-function-references"></a>

### DRM Buddy Function References


#### <a id="c-drm_buddy_init"></a>`drm_buddy_init()`

```c
int drm_buddy_init(struct drm_buddy *mm, u64 size, u64 chunk_size)
```

init memory manager

**Parameters**

- `struct drm_buddy *mm`: DRM buddy manager to initialize
- `u64 size`: size in bytes to manage
- `u64 chunk_size`: minimum page size in bytes for our allocations

**Description**

Initializes the memory manager and its resources.

**Return**

0 on success, error code on failure.

#### <a id="c-drm_buddy_fini"></a>`drm_buddy_fini()`

```c
void drm_buddy_fini(struct drm_buddy *mm)
```

tear down the memory manager

**Parameters**

- `struct drm_buddy *mm`: DRM buddy manager to free

**Description**

Cleanup memory manager resources and the freetree

#### <a id="c-drm_get_buddy"></a>`drm_get_buddy()`

```c
struct drm_buddy_block * drm_get_buddy(struct drm_buddy_block *block)
```

get buddy address

**Parameters**

- `struct drm_buddy_block *block`: DRM buddy block

**Description**

Returns the corresponding buddy block for **block**, or NULL
if this is a root block and can't be merged further.
Requires some kind of locking to protect against
any concurrent allocate and free operations.

#### <a id="c-drm_buddy_reset_clear"></a>`drm_buddy_reset_clear()`

```c
void drm_buddy_reset_clear(struct drm_buddy *mm, bool is_clear)
```

reset blocks clear state

**Parameters**

- `struct drm_buddy *mm`: DRM buddy manager
- `bool is_clear`: blocks clear state

**Description**

Reset the clear state based on **is_clear** value for each block
in the freetree.

#### <a id="c-drm_buddy_free_block"></a>`drm_buddy_free_block()`

```c
void drm_buddy_free_block(struct drm_buddy *mm, struct drm_buddy_block *block)
```

free a block

**Parameters**

- `struct drm_buddy *mm`: DRM buddy manager
- `struct drm_buddy_block *block`: block to be freed

#### <a id="c-drm_buddy_free_list"></a>`drm_buddy_free_list()`

```c
void drm_buddy_free_list(struct drm_buddy *mm, struct list_head *objects, unsigned int flags)
```

free blocks

**Parameters**

- `struct drm_buddy *mm`: DRM buddy manager
- `struct list_head *objects`: input list head to free blocks
- `unsigned int flags`: optional flags like DRM_BUDDY_CLEARED

#### <a id="c-drm_buddy_block_trim"></a>`drm_buddy_block_trim()`

```c
int drm_buddy_block_trim(struct drm_buddy *mm, u64 *start, u64 new_size, struct list_head *blocks)
```

free unused pages

**Parameters**

- `struct drm_buddy *mm`: DRM buddy manager
- `u64 *start`: start address to begin the trimming.
- `u64 new_size`: original size requested
- `struct list_head *blocks`: Input and output list of allocated blocks.
  MUST contain single block as input to be trimmed.
  On success will contain the newly allocated blocks
  making up the **new_size**. Blocks always appear in
  ascending order

**Description**

For contiguous allocation, we round up the size to the nearest
power of two value, drivers consume *actual* size, so remaining
portions are unused and can be optionally freed with this function

**Return**

0 on success, error code on failure.

#### <a id="c-drm_buddy_alloc_blocks"></a>`drm_buddy_alloc_blocks()`

```c
int drm_buddy_alloc_blocks(struct drm_buddy *mm, u64 start, u64 end, u64 size, u64 min_block_size, struct list_head *blocks, unsigned long flags)
```

allocate power-of-two blocks

**Parameters**

- `struct drm_buddy *mm`: DRM buddy manager to allocate from
- `u64 start`: start of the allowed range for this block
- `u64 end`: end of the allowed range for this block
- `u64 size`: size of the allocation in bytes
- `u64 min_block_size`: alignment of the allocation
- `struct list_head *blocks`: output list head to add allocated blocks
- `unsigned long flags`: DRM_BUDDY_*_ALLOCATION flags

**Description**

`alloc_range_bias()` called on range limitations, which traverses
the tree and returns the desired block.

`alloc_from_freetree()` called when *no* range restrictions
are enforced, which picks the block from the freetree.

**Return**

0 on success, error code on failure.

#### <a id="c-drm_buddy_block_print"></a>`drm_buddy_block_print()`

```c
void drm_buddy_block_print(struct drm_buddy *mm, struct drm_buddy_block *block, struct drm_printer *p)
```

print block information

**Parameters**

- `struct drm_buddy *mm`: DRM buddy manager
- `struct drm_buddy_block *block`: DRM buddy block
- `struct drm_printer *p`: DRM printer to use

#### <a id="c-drm_buddy_print"></a>`drm_buddy_print()`

```c
void drm_buddy_print(struct drm_buddy *mm, struct drm_printer *p)
```

print allocator state

**Parameters**

- `struct drm_buddy *mm`: DRM buddy manager
- `struct drm_printer *p`: DRM printer to use


<a id="rst-drm-cache-handling-and-fast-wc-memcpy"></a>

## DRM Cache Handling and Fast WC memcpy()


#### <a id="c-drm_clflush_pages"></a>`drm_clflush_pages()`

```c
void drm_clflush_pages(struct page *pages[], unsigned long num_pages)
```

Flush dcache lines of a set of pages.

**Parameters**

- `struct page *pages[]`: List of pages to be flushed.
- `unsigned long num_pages`: Number of pages in the array.

**Description**

Flush every data cache line entry that points to an address belonging
to a page in the array.

#### <a id="c-drm_clflush_sg"></a>`drm_clflush_sg()`

```c
void drm_clflush_sg(struct sg_table *st)
```

Flush dcache lines pointing to a scather-gather.

**Parameters**

- `struct sg_table *st`: struct sg_table.

**Description**

Flush every data cache line entry that points to an address in the
sg.

#### <a id="c-drm_clflush_virt_range"></a>`drm_clflush_virt_range()`

```c
void drm_clflush_virt_range(void *addr, unsigned long length)
```

Flush dcache lines of a region

**Parameters**

- `void *addr`: Initial kernel memory address.
- `unsigned long length`: Region size.

**Description**

Flush every data cache line entry that points to an address in the
region requested.

#### <a id="c-drm_memcpy_from_wc"></a>`drm_memcpy_from_wc()`

```c
void drm_memcpy_from_wc(struct iosys_map *dst, const struct iosys_map *src, unsigned long len)
```

Perform the fastest available memcpy from a source that may be WC.

**Parameters**

- `struct iosys_map *dst`: The destination pointer
- `const struct iosys_map *src`: The source pointer
- `unsigned long len`: The size of the area o transfer in bytes

**Description**

Tries an arch optimized memcpy for prefetching reading out of a WC region,
and if no such beast is available, falls back to a normal memcpy.


<a id="rst-drm-sync-objects-1"></a>
<a id="rst-drm-sync-objects"></a>

## DRM Sync Objects


DRM synchronisation objects (syncobj, see struct [`drm_syncobj`](#c-struct-drm_syncobj)) provide a
container for a synchronization primitive which can be used by userspace
to explicitly synchronize GPU commands, can be shared between userspace
processes, and can be shared between different DRM drivers.
Their primary use-case is to implement Vulkan fences and semaphores.
The syncobj userspace API provides ioctls for several operations:

- Creation and destruction of syncobjs
- Import and export of syncobjs to/from a syncobj file descriptor
- Import and export a syncobj's underlying fence to/from a sync file
- Reset a syncobj (set its fence to NULL)
- Signal a syncobj (set a trivially signaled fence)
- Wait for a syncobj's fence to appear and be signaled

The syncobj userspace API also provides operations to manipulate a syncobj
in terms of a timeline of struct [`dma_fence_chain`](/kernel/hardware/driver-api/io-and-dma/dma-buf.md#c-struct-dma_fence_chain) rather than a single
struct [`dma_fence`](/kernel/hardware/driver-api/io-and-dma/dma-buf.md#c-struct-dma_fence), through the following operations:

- Signal a given point on the timeline
- Wait for a given point to appear and/or be signaled
- Import and export from/to a given point of a timeline

At it's core, a syncobj is simply a wrapper around a pointer to a struct
[`dma_fence`](/kernel/hardware/driver-api/io-and-dma/dma-buf.md#c-struct-dma_fence) which may be NULL.
When a syncobj is first created, its pointer is either NULL or a pointer
to an already signaled fence depending on whether the
`DRM_SYNCOBJ_CREATE_SIGNALED` flag is passed to
`DRM_IOCTL_SYNCOBJ_CREATE`.

If the syncobj is considered as a binary (its state is either signaled or
unsignaled) primitive, when GPU work is enqueued in a DRM driver to signal
the syncobj, the syncobj's fence is replaced with a fence which will be
signaled by the completion of that work.
If the syncobj is considered as a timeline primitive, when GPU work is
enqueued in a DRM driver to signal the a given point of the syncobj, a new
struct [`dma_fence_chain`](/kernel/hardware/driver-api/io-and-dma/dma-buf.md#c-struct-dma_fence_chain) pointing to the DRM driver's fence and also
pointing to the previous fence that was in the syncobj. The new struct
[`dma_fence_chain`](/kernel/hardware/driver-api/io-and-dma/dma-buf.md#c-struct-dma_fence_chain) fence replace the syncobj's fence and will be signaled by
completion of the DRM driver's work and also any work associated with the
fence previously in the syncobj.

When GPU work which waits on a syncobj is enqueued in a DRM driver, at the
time the work is enqueued, it waits on the syncobj's fence before
submitting the work to hardware. That fence is either :

- The syncobj's current fence if the syncobj is considered as a binary
  primitive.
- The struct [`dma_fence`](/kernel/hardware/driver-api/io-and-dma/dma-buf.md#c-struct-dma_fence) associated with a given point if the syncobj is
  considered as a timeline primitive.

If the syncobj's fence is NULL or not present in the syncobj's timeline,
the enqueue operation is expected to fail.

With binary syncobj, all manipulation of the syncobjs's fence happens in
terms of the current fence at the time the ioctl is called by userspace
regardless of whether that operation is an immediate host-side operation
(signal or reset) or or an operation which is enqueued in some driver
queue. `DRM_IOCTL_SYNCOBJ_RESET` and `DRM_IOCTL_SYNCOBJ_SIGNAL` can be used
to manipulate a syncobj from the host by resetting its pointer to NULL or
setting its pointer to a fence which is already signaled.

With a timeline syncobj, all manipulation of the synobj's fence happens in
terms of a u64 value referring to point in the timeline. See
[`dma_fence_chain_find_seqno()`](/kernel/hardware/driver-api/io-and-dma/dma-buf.md#c-dma_fence_chain_find_seqno) to see how a given point is found in the
timeline.

Note that applications should be careful to always use timeline set of
`ioctl()` when dealing with syncobj considered as timeline. Using a binary
set of `ioctl()` with a syncobj considered as timeline could result incorrect
synchronization. The use of binary syncobj is supported through the
timeline set of `ioctl()` by using a point value of 0, this will reproduce
the behavior of the binary set of `ioctl()` (for example replace the
syncobj's fence when signaling).

**Host-side wait on syncobjs**

`DRM_IOCTL_SYNCOBJ_WAIT` takes an array of syncobj handles and does a
host-side wait on all of the syncobj fences simultaneously.
If `DRM_SYNCOBJ_WAIT_FLAGS_WAIT_ALL` is set, the wait ioctl will wait on
all of the syncobj fences to be signaled before it returns.
Otherwise, it returns once at least one syncobj fence has been signaled
and the index of a signaled fence is written back to the client.

Unlike the enqueued GPU work dependencies which fail if they see a NULL
fence in a syncobj, if `DRM_SYNCOBJ_WAIT_FLAGS_WAIT_FOR_SUBMIT` is set,
the host-side wait will first wait for the syncobj to receive a non-NULL
fence and then wait on that fence.
If `DRM_SYNCOBJ_WAIT_FLAGS_WAIT_FOR_SUBMIT` is not set and any one of the
syncobjs in the array has a NULL fence, -EINVAL will be returned.
Assuming the syncobj starts off with a NULL fence, this allows a client
to do a host wait in one thread (or process) which waits on GPU work
submitted in another thread (or process) without having to manually
synchronize between the two.
This requirement is inherited from the Vulkan fence API.

If `DRM_SYNCOBJ_WAIT_FLAGS_WAIT_DEADLINE` is set, the ioctl will also set
a fence deadline hint on the backing fences before waiting, to provide the
fence signaler with an appropriate sense of urgency.  The deadline is
specified as an absolute `CLOCK_MONOTONIC` value in units of ns.

Similarly, `DRM_IOCTL_SYNCOBJ_TIMELINE_WAIT` takes an array of syncobj
handles as well as an array of u64 points and does a host-side wait on all
of syncobj fences at the given points simultaneously.

`DRM_IOCTL_SYNCOBJ_TIMELINE_WAIT` also adds the ability to wait for a given
fence to materialize on the timeline without waiting for the fence to be
signaled by using the `DRM_SYNCOBJ_WAIT_FLAGS_WAIT_AVAILABLE` flag. This
requirement is inherited from the wait-before-signal behavior required by
the Vulkan timeline semaphore API.

Alternatively, `DRM_IOCTL_SYNCOBJ_EVENTFD` can be used to wait without
blocking: an eventfd will be signaled when the syncobj is. This is useful to
integrate the wait in an event loop.

**Import/export of syncobjs**

`DRM_IOCTL_SYNCOBJ_FD_TO_HANDLE` and `DRM_IOCTL_SYNCOBJ_HANDLE_TO_FD`
provide two mechanisms for import/export of syncobjs.

The first lets the client import or export an entire syncobj to a file
descriptor.
These fd's are opaque and have no other use case, except passing the
syncobj between processes.
All exported file descriptors and any syncobj handles created as a
result of importing those file descriptors own a reference to the
same underlying struct [`drm_syncobj`](#c-struct-drm_syncobj) and the syncobj can be used
persistently across all the processes with which it is shared.
The syncobj is freed only once the last reference is dropped.
Unlike dma-buf, importing a syncobj creates a new handle (with its own
reference) for every import instead of de-duplicating.
The primary use-case of this persistent import/export is for shared
Vulkan fences and semaphores.

The second import/export mechanism, which is indicated by
`DRM_SYNCOBJ_FD_TO_HANDLE_FLAGS_IMPORT_SYNC_FILE` or
`DRM_SYNCOBJ_HANDLE_TO_FD_FLAGS_EXPORT_SYNC_FILE` lets the client
import/export the syncobj's current fence from/to a [`sync_file`](/kernel/hardware/driver-api/io-and-dma/dma-buf.md#c-struct-sync_file).
When a syncobj is exported to a sync file, that sync file wraps the
sycnobj's fence at the time of export and any later signal or reset
operations on the syncobj will not affect the exported sync file.
When a sync file is imported into a syncobj, the syncobj's fence is set
to the fence wrapped by that sync file.
Because sync files are immutable, resetting or signaling the syncobj
will not affect any sync files whose fences have been imported into the
syncobj.

**Import/export of timeline points in timeline syncobjs**

`DRM_IOCTL_SYNCOBJ_TRANSFER` provides a mechanism to transfer a struct
[`dma_fence_chain`](/kernel/hardware/driver-api/io-and-dma/dma-buf.md#c-struct-dma_fence_chain) of a syncobj at a given u64 point to another u64 point
into another syncobj.

Note that if you want to transfer a struct [`dma_fence_chain`](/kernel/hardware/driver-api/io-and-dma/dma-buf.md#c-struct-dma_fence_chain) from a given
point on a timeline syncobj from/into a binary syncobj, you can use the
point 0 to mean take/replace the fence in the syncobj.



#### <a id="c-struct-drm_syncobj"></a>`struct drm_syncobj`

sync object.

**Definition**

```c
struct drm_syncobj {
    struct kref refcount;
    struct dma_fence  *fence;
    struct list_head cb_list;
    struct list_head ev_fd_list;
    spinlock_t lock;
    struct file *file;
};
```

**Members**

- `refcount`: Reference count of this object.
- `fence`: NULL or a pointer to the fence bound to this object.

  This field should not be used directly. Use [`drm_syncobj_fence_get()`](#c-drm_syncobj_fence_get)
  and [`drm_syncobj_replace_fence()`](#c-drm_syncobj_replace_fence) instead.
- `cb_list`: List of callbacks to call when the `fence` gets replaced.
- `ev_fd_list`: List of registered eventfd.
- `lock`: Protects `cb_list` and `ev_fd_list`, and write-locks `fence`.
- `file`: A file backing for this syncobj.

**Description**

This structure defines a generic sync object which wraps a [`dma_fence`](/kernel/hardware/driver-api/io-and-dma/dma-buf.md#c-struct-dma_fence).

#### <a id="c-drm_syncobj_get"></a>`drm_syncobj_get()`

```c
void drm_syncobj_get(struct drm_syncobj *obj)
```

acquire a syncobj reference

**Parameters**

- `struct drm_syncobj *obj`: sync object

**Description**

This acquires an additional reference to **obj**. It is illegal to call this
without already holding a reference. No locks required.

#### <a id="c-drm_syncobj_put"></a>`drm_syncobj_put()`

```c
void drm_syncobj_put(struct drm_syncobj *obj)
```

release a reference to a sync object.

**Parameters**

- `struct drm_syncobj *obj`: sync object.

#### <a id="c-drm_syncobj_fence_get"></a>`drm_syncobj_fence_get()`

```c
struct dma_fence * drm_syncobj_fence_get(struct drm_syncobj *syncobj)
```

get a reference to a fence in a sync object

**Parameters**

- `struct drm_syncobj *syncobj`: sync object.

**Description**

This acquires additional reference to [`drm_syncobj.fence`](#c-struct-drm_syncobj) contained in **obj**,
if not NULL. It is illegal to call this without already holding a reference.
No locks required.

**Return**

Either the fence of **obj** or NULL if there's none.



#### <a id="c-drm_syncobj_find"></a>`drm_syncobj_find()`

```c
struct drm_syncobj * drm_syncobj_find(struct drm_file *file_private, u32 handle)
```

lookup and reference a sync object.

**Parameters**

- `struct drm_file *file_private`: drm file private pointer
- `u32 handle`: sync object handle to lookup.

**Description**

Returns a reference to the syncobj pointed to by handle or NULL. The
reference must be released by calling [`drm_syncobj_put()`](#c-drm_syncobj_put).

#### <a id="c-drm_syncobj_add_point"></a>`drm_syncobj_add_point()`

```c
void drm_syncobj_add_point(struct drm_syncobj *syncobj, struct dma_fence_chain *chain, struct dma_fence *fence, uint64_t point)
```

add new timeline point to the syncobj

**Parameters**

- `struct drm_syncobj *syncobj`: sync object to add timeline point do
- `struct dma_fence_chain *chain`: chain node to use to add the point
- `struct dma_fence *fence`: fence to encapsulate in the chain node
- `uint64_t point`: sequence number to use for the point

**Description**

Add the chain node as new timeline point to the syncobj.

#### <a id="c-drm_syncobj_replace_fence"></a>`drm_syncobj_replace_fence()`

```c
void drm_syncobj_replace_fence(struct drm_syncobj *syncobj, struct dma_fence *fence)
```

replace fence in a sync object.

**Parameters**

- `struct drm_syncobj *syncobj`: Sync object to replace fence in
- `struct dma_fence *fence`: fence to install in sync file.

**Description**

This replaces the fence on a sync object.

#### <a id="c-drm_syncobj_find_fence"></a>`drm_syncobj_find_fence()`

```c
int drm_syncobj_find_fence(struct drm_file *file_private, u32 handle, u64 point, u64 flags, struct dma_fence **fence)
```

lookup and reference the fence in a sync object

**Parameters**

- `struct drm_file *file_private`: drm file private pointer
- `u32 handle`: sync object handle to lookup.
- `u64 point`: timeline point
- `u64 flags`: DRM_SYNCOBJ_WAIT_FLAGS_WAIT_FOR_SUBMIT or not
- `struct dma_fence **fence`: out parameter for the fence

**Description**

This is just a convenience function that combines [`drm_syncobj_find()`](#c-drm_syncobj_find) and
[`drm_syncobj_fence_get()`](#c-drm_syncobj_fence_get).

Returns 0 on success or a negative error value on failure. On success **fence**
contains a reference to the fence, which must be released by calling
[`dma_fence_put()`](/kernel/hardware/driver-api/io-and-dma/dma-buf.md#c-dma_fence_put).

#### <a id="c-drm_syncobj_free"></a>`drm_syncobj_free()`

```c
void drm_syncobj_free(struct kref *kref)
```

free a sync object.

**Parameters**

- `struct kref *kref`: kref to free.

**Description**

Only to be called from kref_put in drm_syncobj_put.

#### <a id="c-drm_syncobj_create"></a>`drm_syncobj_create()`

```c
int drm_syncobj_create(struct drm_syncobj **out_syncobj, uint32_t flags, struct dma_fence *fence)
```

create a new syncobj

**Parameters**

- `struct drm_syncobj **out_syncobj`: returned syncobj
- `uint32_t flags`: DRM_SYNCOBJ_* flags
- `struct dma_fence *fence`: if non-NULL, the syncobj will represent this fence

**Description**

This is the first function to create a sync object. After creating, drivers
probably want to make it available to userspace, either through
[`drm_syncobj_get_handle()`](#c-drm_syncobj_get_handle) or [`drm_syncobj_get_fd()`](#c-drm_syncobj_get_fd).

Returns 0 on success or a negative error value on failure.

#### <a id="c-drm_syncobj_get_handle"></a>`drm_syncobj_get_handle()`

```c
int drm_syncobj_get_handle(struct drm_file *file_private, struct drm_syncobj *syncobj, u32 *handle)
```

get a handle from a syncobj

**Parameters**

- `struct drm_file *file_private`: drm file private pointer
- `struct drm_syncobj *syncobj`: Sync object to export
- `u32 *handle`: out parameter with the new handle

**Description**

Exports a sync object created with [`drm_syncobj_create()`](#c-drm_syncobj_create) as a handle on
**file_private** to userspace.

Returns 0 on success or a negative error value on failure.

#### <a id="c-drm_syncobj_get_fd"></a>`drm_syncobj_get_fd()`

```c
int drm_syncobj_get_fd(struct drm_syncobj *syncobj, int *p_fd)
```

get a file descriptor from a syncobj

**Parameters**

- `struct drm_syncobj *syncobj`: Sync object to export
- `int *p_fd`: out parameter with the new file descriptor

**Description**

Exports a sync object created with [`drm_syncobj_create()`](#c-drm_syncobj_create) as a file descriptor.

Returns 0 on success or a negative error value on failure.

#### <a id="c-drm_timeout_abs_to_jiffies"></a>`drm_timeout_abs_to_jiffies()`

```c
signed long drm_timeout_abs_to_jiffies(int64_t timeout_nsec)
```

calculate jiffies timeout from absolute value

**Parameters**

- `int64_t timeout_nsec`: timeout nsec component in ns, 0 for poll

**Description**

Calculate the timeout in jiffies from an absolute time in sec/nsec.


<a id="rst-drm-execution-context"></a>

## DRM Execution context


This component mainly abstracts the retry loop necessary for locking
multiple GEM objects while preparing hardware operations (e.g. command
submissions, page table updates etc..).

If a contention is detected while locking a GEM object the cleanup procedure
unlocks all previously locked GEM objects and locks the contended one first
before locking any further objects.

After an object is locked fences slots can optionally be reserved on the
dma_resv object inside the GEM object.

A typical usage pattern should look like this:

```text
struct drm_gem_object *obj;
struct drm_exec exec;
unsigned long index;
int ret;

drm_exec_init(&exec, DRM_EXEC_INTERRUPTIBLE_WAIT);
drm_exec_until_all_locked(&exec) {
        ret = drm_exec_prepare_obj(&exec, boA, 1);
        drm_exec_retry_on_contention(&exec);
        if (ret)
                goto error;

        ret = drm_exec_prepare_obj(&exec, boB, 1);
        drm_exec_retry_on_contention(&exec);
        if (ret)
                goto error;
}

drm_exec_for_each_locked_object(&exec, index, obj) {
        dma_resv_add_fence(obj->resv, fence, DMA_RESV_USAGE_READ);
        ...
}
drm_exec_fini(&exec);
```

See struct dma_exec for more details.



#### <a id="c-struct-drm_exec"></a>`struct drm_exec`

Execution context

**Definition**

```c
struct drm_exec {
    u32 flags;
    struct ww_acquire_ctx   ticket;
    unsigned int            num_objects;
    unsigned int            max_objects;
    struct drm_gem_object   **objects;
    struct drm_gem_object   *contended;
    struct drm_gem_object *prelocked;
};
```

**Members**

- `flags`: Flags to control locking behavior
- `ticket`: WW ticket used for acquiring locks
- `num_objects`: number of objects locked
- `max_objects`: maximum objects in array
- `objects`: array of the locked objects
- `contended`: contended GEM object we backed off for
- `prelocked`: already locked GEM object due to contention

#### <a id="c-drm_exec_obj"></a>`drm_exec_obj()`

```c
struct drm_gem_object * drm_exec_obj(struct drm_exec *exec, unsigned long index)
```

Return the object for a give drm_exec index

**Parameters**

- `struct drm_exec *exec`: Pointer to the drm_exec context
- `unsigned long index`: The index.

**Return**

Pointer to the locked object corresponding to **index** if
index is within the number of locked objects. NULL otherwise.

#### <a id="c-drm_exec_for_each_locked_object"></a>`drm_exec_for_each_locked_object()`

```c
drm_exec_for_each_locked_object(exec, index, obj)
```

iterate over all the locked objects

**Parameters**

- `exec`: drm_exec object
- `index`: unsigned long index for the iteration
- `obj`: the current GEM object

**Description**

Iterate over all the locked GEM objects inside the drm_exec object.

#### <a id="c-drm_exec_for_each_locked_object_reverse"></a>`drm_exec_for_each_locked_object_reverse()`

```c
drm_exec_for_each_locked_object_reverse(exec, index, obj)
```

iterate over all the locked objects in reverse locking order

**Parameters**

- `exec`: drm_exec object
- `index`: unsigned long index for the iteration
- `obj`: the current GEM object

**Description**

Iterate over all the locked GEM objects inside the drm_exec object in
reverse locking order. Note that **index** may go below zero and wrap,
but that will be caught by [`drm_exec_obj()`](#c-drm_exec_obj), returning a NULL object.

#### <a id="c-drm_exec_until_all_locked"></a>`drm_exec_until_all_locked()`

```c
drm_exec_until_all_locked(exec)
```

loop until all GEM objects are locked

**Parameters**

- `exec`: drm_exec object

**Description**

Core functionality of the drm_exec object. Loops until all GEM objects are
locked and no more contention exists. At the beginning of the loop it is
guaranteed that no GEM object is locked.

Since labels can't be defined local to the loops body we use a jump pointer
to make sure that the retry is only used from within the loops body.

#### <a id="c-drm_exec_retry_on_contention"></a>`drm_exec_retry_on_contention()`

```c
drm_exec_retry_on_contention(exec)
```

restart the loop to grap all locks

**Parameters**

- `exec`: drm_exec object

**Description**

Control flow helper to continue when a contention was detected and we need to
clean up and re-start the loop to prepare all GEM objects.

#### <a id="c-drm_exec_is_contended"></a>`drm_exec_is_contended()`

```c
bool drm_exec_is_contended(struct drm_exec *exec)
```

check for contention

**Parameters**

- `struct drm_exec *exec`: drm_exec object

**Description**

Returns true if the drm_exec object has run into some contention while
locking a GEM object and needs to clean up.



#### <a id="c-drm_exec_init"></a>`drm_exec_init()`

```c
void drm_exec_init(struct drm_exec *exec, u32 flags, unsigned nr)
```

initialize a drm_exec object

**Parameters**

- `struct drm_exec *exec`: the drm_exec object to initialize
- `u32 flags`: controls locking behavior, see DRM_EXEC_* defines
- `unsigned nr`: the initial # of objects

**Description**

Initialize the object and make sure that we can track locked objects.

If nr is non-zero then it is used as the initial objects table size.
In either case, the table will grow (be re-allocated) on demand.

#### <a id="c-drm_exec_fini"></a>`drm_exec_fini()`

```c
void drm_exec_fini(struct drm_exec *exec)
```

finalize a drm_exec object

**Parameters**

- `struct drm_exec *exec`: the drm_exec object to finalize

**Description**

Unlock all locked objects, drop the references to objects and free all memory
used for tracking the state.

#### <a id="c-drm_exec_cleanup"></a>`drm_exec_cleanup()`

```c
bool drm_exec_cleanup(struct drm_exec *exec)
```

cleanup when contention is detected

**Parameters**

- `struct drm_exec *exec`: the drm_exec object to cleanup

**Description**

Cleanup the current state and return true if we should stay inside the retry
loop, false if there wasn't any contention detected and we can keep the
objects locked.

#### <a id="c-drm_exec_lock_obj"></a>`drm_exec_lock_obj()`

```c
int drm_exec_lock_obj(struct drm_exec *exec, struct drm_gem_object *obj)
```

lock a GEM object for use

**Parameters**

- `struct drm_exec *exec`: the drm_exec object with the state
- `struct drm_gem_object *obj`: the GEM object to lock

**Description**

Lock a GEM object for use and grab a reference to it.

**Return**

-EDEADLK if a contention is detected, -EALREADY when object is
already locked (can be suppressed by setting the DRM_EXEC_IGNORE_DUPLICATES
flag), -ENOMEM when memory allocation failed and zero for success.

#### <a id="c-drm_exec_unlock_obj"></a>`drm_exec_unlock_obj()`

```c
void drm_exec_unlock_obj(struct drm_exec *exec, struct drm_gem_object *obj)
```

unlock a GEM object in this exec context

**Parameters**

- `struct drm_exec *exec`: the drm_exec object with the state
- `struct drm_gem_object *obj`: the GEM object to unlock

**Description**

Unlock the GEM object and remove it from the collection of locked objects.
Should only be used to unlock the most recently locked objects. It's not time
efficient to unlock objects locked long ago.

#### <a id="c-drm_exec_prepare_obj"></a>`drm_exec_prepare_obj()`

```c
int drm_exec_prepare_obj(struct drm_exec *exec, struct drm_gem_object *obj, unsigned int num_fences)
```

prepare a GEM object for use

**Parameters**

- `struct drm_exec *exec`: the drm_exec object with the state
- `struct drm_gem_object *obj`: the GEM object to prepare
- `unsigned int num_fences`: how many fences to reserve

**Description**

Prepare a GEM object for use by locking it and reserving fence slots.

**Return**

-EDEADLK if a contention is detected, -EALREADY when object is
already locked, -ENOMEM when memory allocation failed and zero for success.

#### <a id="c-drm_exec_prepare_array"></a>`drm_exec_prepare_array()`

```c
int drm_exec_prepare_array(struct drm_exec *exec, struct drm_gem_object **objects, unsigned int num_objects, unsigned int num_fences)
```

helper to prepare an array of objects

**Parameters**

- `struct drm_exec *exec`: the drm_exec object with the state
- `struct drm_gem_object **objects`: array of GEM object to prepare
- `unsigned int num_objects`: number of GEM objects in the array
- `unsigned int num_fences`: number of fences to reserve on each GEM object

**Description**

Prepares all GEM objects in an array, aborts on first error.
Reserves **num_fences** on each GEM object after locking it.

**Return**

-EDEADLOCK on contention, -EALREADY when object is already locked,
-ENOMEM when memory allocation failed and zero for success.


<a id="rst-gpu-scheduler"></a>

## GPU Scheduler

<a id="rst-overview-2"></a>

### Overview


The GPU scheduler provides entities which allow userspace to push jobs
into software queues which are then scheduled on a hardware run queue.
The software queues have a priority among them. The scheduler selects the entities
from the run queue using a FIFO. The scheduler provides dependency handling
features among jobs. The driver is supposed to provide callback functions for
backend operations to the scheduler like submitting a job to hardware run queue,
returning the dependencies of a job etc.

The organisation of the scheduler is the following:

1. Each hw run queue has one scheduler
2. Each scheduler has multiple run queues with different priorities
   (e.g., HIGH_HW,HIGH_SW, KERNEL, NORMAL)
3. Each scheduler run queue has a queue of entities to schedule
4. Entities themselves maintain a queue of jobs that will be scheduled on
   the hardware.

The jobs in an entity are always scheduled in the order in which they were pushed.

Note that once a job was taken from the entities queue and pushed to the
hardware, i.e. the pending queue, the entity must not be referenced anymore
through the jobs entity pointer.


<a id="rst-flow-control"></a>

### Flow Control


The DRM GPU scheduler provides a flow control mechanism to regulate the rate
in which the jobs fetched from scheduler entities are executed.

In this context the [`drm_gpu_scheduler`](#c-struct-drm_gpu_scheduler) keeps track of a driver specified
credit limit representing the capacity of this scheduler and a credit count;
every [`drm_sched_job`](#c-struct-drm_sched_job) carries a driver specified number of credits.

Once a job is executed (but not yet finished), the job's credits contribute
to the scheduler's credit count until the job is finished. If by executing
one more job the scheduler's credit count would exceed the scheduler's
credit limit, the job won't be executed. Instead, the scheduler will wait
until the credit count has decreased enough to not overflow its credit limit.
This implies waiting for previously executed jobs.


<a id="rst-scheduler-function-references"></a>

### Scheduler Function References


#### <a id="c-DRM_SCHED_FENCE_DONT_PIPELINE"></a>`DRM_SCHED_FENCE_DONT_PIPELINE`

```c
DRM_SCHED_FENCE_DONT_PIPELINE
```

Prevent dependency pipelining

**Description**

Setting this flag on a scheduler fence prevents pipelining of jobs depending
on this fence. In other words we always insert a full CPU round trip before
dependent jobs are pushed to the hw queue.

#### <a id="c-DRM_SCHED_FENCE_FLAG_HAS_DEADLINE_BIT"></a>`DRM_SCHED_FENCE_FLAG_HAS_DEADLINE_BIT`

```c
DRM_SCHED_FENCE_FLAG_HAS_DEADLINE_BIT
```

A fence deadline hint has been set

**Description**

Because we could have a deadline hint can be set before the backing hw
fence is created, we need to keep track of whether a deadline has already
been set.

#### <a id="c-struct-drm_sched_entity"></a>`struct drm_sched_entity`

A wrapper around a job queue (typically attached to the DRM file_priv).

**Definition**

```c
struct drm_sched_entity {
    struct list_head                list;
    spinlock_t lock;
    struct drm_sched_rq             *rq;
    struct drm_gpu_scheduler        **sched_list;
    unsigned int                    num_sched_list;
    enum drm_sched_priority         priority;
    struct spsc_queue               job_queue;
    atomic_t fence_seq;
    uint64_t fence_context;
    struct dma_fence                *dependency;
    struct dma_fence_cb             cb;
    atomic_t *guilty;
    struct dma_fence           *last_scheduled;
    struct task_struct              *last_user;
    bool stopped;
    struct completion               entity_idle;
    ktime_t oldest_job_waiting;
    struct rb_node                  rb_tree_node;
};
```

**Members**

- `list`: Used to append this struct to the list of entities in the runqueue
  **rq** under [`drm_sched_rq.entities`](#c-struct-drm_sched_rq).

  Protected by [`drm_sched_rq.lock`](#c-struct-drm_sched_rq) of **rq**.
- `lock`: Lock protecting the run-queue (**rq**) to which this entity belongs,
  **priority** and the list of schedulers (**sched_list**, **num_sched_list**).
- `rq`: Runqueue on which this entity is currently scheduled.

  FIXME: Locking is very unclear for this. Writers are protected by
  **lock**, but readers are generally lockless and seem to just race with
  not even a READ_ONCE.
- `sched_list`: A list of schedulers (struct drm_gpu_scheduler).  Jobs from this entity can
  be scheduled on any scheduler on this list.

  This can be modified by calling [`drm_sched_entity_modify_sched()`](#c-drm_sched_entity_modify_sched).
  Locking is entirely up to the driver, see the above function for more
  details.

  This will be set to NULL if `num_sched_list` equals 1 and **rq** has been
  set already.

  FIXME: This means priority changes through
  [`drm_sched_entity_set_priority()`](#c-drm_sched_entity_set_priority) will be lost henceforth in this case.
- `num_sched_list`: Number of drm_gpu_schedulers in the **sched_list**.
- `priority`: Priority of the entity. This can be modified by calling
  [`drm_sched_entity_set_priority()`](#c-drm_sched_entity_set_priority). Protected by **lock**.
- `job_queue`: the list of jobs of this entity.
- `fence_seq`: A linearly increasing seqno incremented with each new
  [`drm_sched_fence`](#c-struct-drm_sched_fence) which is part of the entity.

  FIXME: Callers of [`drm_sched_job_arm()`](#c-drm_sched_job_arm) need to ensure correct locking,
  this doesn't need to be atomic.
- `fence_context`: A unique context for all the fences which belong to this entity.  The
  [`drm_sched_fence.scheduled`](#c-struct-drm_sched_fence) uses the fence_context but
  [`drm_sched_fence.finished`](#c-struct-drm_sched_fence) uses fence_context + 1.
- `dependency`: The dependency fence of the job which is on the top of the job queue.
- `cb`: Callback for the dependency fence above.
- `guilty`: Points to entities' guilty.
- `last_scheduled`: Points to the finished fence of the last scheduled job. Only written
  by `drm_sched_entity_pop_job()`. Can be accessed locklessly from
  [`drm_sched_job_arm()`](#c-drm_sched_job_arm) if the queue is empty.
- `last_user`: last group leader pushing a job into the entity.
- `stopped`: Marks the enity as removed from rq and destined for
  termination. This is set by calling [`drm_sched_entity_flush()`](#c-drm_sched_entity_flush) and by
  [`drm_sched_fini()`](#c-drm_sched_fini).
- `entity_idle`: Signals when entity is not in use, used to sequence entity cleanup in
  [`drm_sched_entity_fini()`](#c-drm_sched_entity_fini).
- `oldest_job_waiting`: Marks earliest job waiting in SW queue
- `rb_tree_node`: The node used to insert this entity into time based priority queue

**Description**

Entities will emit jobs in order to their corresponding hardware
ring, and the scheduler will alternate between entities based on
scheduling policy.

#### <a id="c-struct-drm_sched_rq"></a>`struct drm_sched_rq`

queue of entities to be scheduled.

**Definition**

```c
struct drm_sched_rq {
    struct drm_gpu_scheduler        *sched;
    spinlock_t lock;
    struct drm_sched_entity         *current_entity;
    struct list_head                entities;
    struct rb_root_cached           rb_tree_root;
};
```

**Members**

- `sched`: the scheduler to which this rq belongs to.
- `lock`: protects **entities**, **rb_tree_root** and **current_entity**.
- `current_entity`: the entity which is to be scheduled.
- `entities`: list of the entities to be scheduled.
- `rb_tree_root`: root of time based priority queue of entities for FIFO scheduling

**Description**

Run queue is a set of entities scheduling command submissions for
one specific ring. It implements the scheduling policy that selects
the next entity to emit commands from.

#### <a id="c-struct-drm_sched_fence"></a>`struct drm_sched_fence`

fences corresponding to the scheduling of a job.

**Definition**

```c
struct drm_sched_fence {
    struct dma_fence                scheduled;
    struct dma_fence                finished;
    ktime_t deadline;
    struct dma_fence                *parent;
    struct drm_gpu_scheduler        *sched;
    spinlock_t lock;
    void *owner;
    uint64_t drm_client_id;
};
```

**Members**

- `scheduled`: this fence is what will be signaled by the scheduler
  when the job is scheduled.
- `finished`: this fence is what will be signaled by the scheduler
  when the job is completed.

  When setting up an out fence for the job, you should use
  this, since it's available immediately upon
  [`drm_sched_job_init()`](#c-drm_sched_job_init), and the fence returned by the driver
  from `run_job()` won't be created until the dependencies have
  resolved.
- `deadline`: deadline set on [`drm_sched_fence.finished`](#c-struct-drm_sched_fence) which
  potentially needs to be propagated to [`drm_sched_fence.parent`](#c-struct-drm_sched_fence)
- `parent`: the fence returned by [`drm_sched_backend_ops.run_job`](#c-struct-drm_sched_backend_ops)
  when scheduling the job on hardware. We signal the
  [`drm_sched_fence.finished`](#c-struct-drm_sched_fence) fence once parent is signalled.
- `sched`: the scheduler instance to which the job having this struct
  belongs to.
- `lock`: the lock used by the scheduled and the finished fences.
- `owner`: job owner for debugging
- `drm_client_id`: The client_id of the drm_file which owns the job.

#### <a id="c-struct-drm_sched_job"></a>`struct drm_sched_job`

A job to be run by an entity.

**Definition**

```c
struct drm_sched_job {
    ktime_t submit_ts;
    struct drm_gpu_scheduler        *sched;
    struct drm_sched_fence          *s_fence;
    struct drm_sched_entity         *entity;
    enum drm_sched_priority         s_priority;
    u32 credits;
    unsigned int                    last_dependency;
    atomic_t karma;
    struct spsc_node                queue_node;
    struct list_head                list;
    union {
        struct dma_fence_cb     finish_cb;
        struct work_struct      work;
    };
    struct dma_fence_cb             cb;
    struct xarray                   dependencies;
};
```

**Members**

- `submit_ts`: When the job was pushed into the entity queue.
- `sched`: The scheduler this job is or will be scheduled on. Gets set by
  [`drm_sched_job_arm()`](#c-drm_sched_job_arm). Valid until drm_sched_backend_ops.`free_job()`
  has finished.
- `s_fence`: contains the fences for the scheduling of job.
- `entity`: the entity to which this job belongs.
- `s_priority`: the priority of the job.
- `credits`: the number of credits this job contributes to the scheduler
- `last_dependency`: tracks **dependencies** as they signal
- `karma`: increment on every hang caused by this job. If this exceeds the hang
  limit of the scheduler then the job is marked guilty and will not
  be scheduled further.
- `queue_node`: used to append this struct to the queue of jobs in an entity.
- `list`: a job participates in a "pending" and "done" lists.
- `{unnamed_union}`: anonymous
- `finish_cb`: the callback for the finished fence.
- `work`: Helper to reschedule job kill to different context.
- `cb`: the callback for the parent fence in s_fence.
- `dependencies`: Contains the dependencies as struct dma_fence for this job, see
  [`drm_sched_job_add_dependency()`](#c-drm_sched_job_add_dependency) and
  [`drm_sched_job_add_implicit_dependencies()`](#c-drm_sched_job_add_implicit_dependencies).

**Description**

A job is created by the driver using [`drm_sched_job_init()`](#c-drm_sched_job_init), and
should call [`drm_sched_entity_push_job()`](#c-drm_sched_entity_push_job) once it wants the scheduler
to schedule the job.

#### <a id="c-enum-drm_gpu_sched_stat"></a>`enum drm_gpu_sched_stat`

the scheduler's status

**Constants**

- `DRM_GPU_SCHED_STAT_NONE`: Reserved. Do not use.
- `DRM_GPU_SCHED_STAT_RESET`: The GPU hung and successfully reset.
- `DRM_GPU_SCHED_STAT_ENODEV`: Error: Device is not available anymore.
- `DRM_GPU_SCHED_STAT_NO_HANG`: Contrary to scheduler's assumption, the GPU
  did not hang and is still running.

#### <a id="c-struct-drm_sched_backend_ops"></a>`struct drm_sched_backend_ops`

Define the backend operations called by the scheduler

**Definition**

```c
struct drm_sched_backend_ops {
    struct dma_fence *(*prepare_job)(struct drm_sched_job *sched_job, struct drm_sched_entity *s_entity);
    struct dma_fence *(*run_job)(struct drm_sched_job *sched_job);
    enum drm_gpu_sched_stat (*timedout_job)(struct drm_sched_job *sched_job);
    void (*free_job)(struct drm_sched_job *sched_job);
    void (*cancel_job)(struct drm_sched_job *sched_job);
};
```

**Members**

- `prepare_job`: Called when the scheduler is considering scheduling this job next, to
  get another struct dma_fence for this job to block on.  Once it
  returns NULL, `run_job()` may be called.

  Can be NULL if no additional preparation to the dependencies are
  necessary. Skipped when jobs are killed instead of run.
- `run_job`: Called to execute the job once all of the dependencies
  have been resolved.

  **sched_job**: the job to run

  The deprecated [`drm_sched_resubmit_jobs()`](#c-drm_sched_resubmit_jobs) (called by [`struct drm_sched_backend_ops`](#c-struct-drm_sched_backend_ops).timedout_job) can invoke this again with the
  same parameters. Using this is discouraged because it violates
  dma_fence rules, notably [`dma_fence_init()`](/kernel/hardware/driver-api/io-and-dma/dma-buf.md#c-dma_fence_init) has to be called on
  already initialized fences for a second time. Moreover, this is
  dangerous because attempts to allocate memory might deadlock with
  memory management code waiting for the reset to complete.

  TODO: Document what drivers should do / use instead.

  This method is called in a workqueue context - either from the
  submit_wq the driver passed through [`drm_sched_init()`](#c-drm_sched_init), or, if the
  driver passed NULL, a separate, ordered workqueue the scheduler
  allocated.

  Note that the scheduler expects to 'inherit' its own reference to
  this fence from the callback. It does not invoke an extra
  [`dma_fence_get()`](/kernel/hardware/driver-api/io-and-dma/dma-buf.md#c-dma_fence_get) on it. Consequently, this callback must take a
  reference for the scheduler, and additional ones for the driver's
  respective needs.

  Return:
  * On success: dma_fence the driver must signal once the hardware has
  completed the job ("hardware fence").
  * On failure: NULL or an ERR_PTR.
- `timedout_job`: Called when a job has taken too long to execute,
  to trigger GPU recovery.

  **sched_job**: The job that has timed out

  Drivers typically issue a reset to recover from GPU hangs.
  This procedure looks very different depending on whether a firmware
  or a hardware scheduler is being used.

  For a FIRMWARE SCHEDULER, each ring has one scheduler, and each
  scheduler has one entity. Hence, the steps taken typically look as
  follows:

  1. Stop the scheduler using [`drm_sched_stop()`](#c-drm_sched_stop). This will pause the
     scheduler workqueues and cancel the timeout work, guaranteeing
     that nothing is queued while the ring is being removed.
  2. Remove the ring. The firmware will make sure that the
     corresponding parts of the hardware are resetted, and that other
     rings are not impacted.
  3. Kill the entity and the associated scheduler.

  For a HARDWARE SCHEDULER, a scheduler instance schedules jobs from
  one or more entities to one ring. This implies that all entities
  associated with the affected scheduler cannot be torn down, because
  this would effectively also affect innocent userspace processes which
  did not submit faulty jobs (for example).

  Consequently, the procedure to recover with a hardware scheduler
  should look like this:

  1. Stop all schedulers impacted by the reset using [`drm_sched_stop()`](#c-drm_sched_stop).
  2. Kill the entity the faulty job stems from.
  3. Issue a GPU reset on all faulty rings (driver-specific).
  4. Re-submit jobs on all schedulers impacted by re-submitting them to
     the entities which are still alive.
  5. Restart all schedulers that were stopped in step #1 using
     [`drm_sched_start()`](#c-drm_sched_start).

  Note that some GPUs have distinct hardware queues but need to reset
  the GPU globally, which requires extra synchronization between the
  timeout handlers of different schedulers. One way to achieve this
  synchronization is to create an ordered workqueue (using
  [`alloc_ordered_workqueue()`](/kernel/internals/core-api/workqueue.md#c-alloc_ordered_workqueue)) at the driver level, and pass this queue
  as [`drm_sched_init()`](#c-drm_sched_init)'s **timeout_wq** parameter. This will guarantee
  that timeout handlers are executed sequentially.

  Return: The scheduler's status, defined by [`enum drm_gpu_sched_stat`](#c-enum-drm_gpu_sched_stat)
- `free_job`: Called once the job's finished fence has been signaled
  and it's time to clean it up.
- `cancel_job`: Used by the scheduler to guarantee remaining jobs' fences
  get signaled in [`drm_sched_fini()`](#c-drm_sched_fini).

  Used by the scheduler to cancel all jobs that have not been executed
  with [`struct drm_sched_backend_ops`](#c-struct-drm_sched_backend_ops).run_job by the time
  [`drm_sched_fini()`](#c-drm_sched_fini) gets invoked.

  Drivers need to signal the passed job's hardware fence with an
  appropriate error code (e.g., -ECANCELED) in this callback. They
  must not free the job.

  The scheduler will only call this callback once it stopped calling
  all other callbacks forever, with the exception of [`struct drm_sched_backend_ops`](#c-struct-drm_sched_backend_ops).free_job.

**Description**

These functions should be implemented in the driver side.

#### <a id="c-struct-drm_gpu_scheduler"></a>`struct drm_gpu_scheduler`

scheduler instance-specific data

**Definition**

```c
struct drm_gpu_scheduler {
    const struct drm_sched_backend_ops      *ops;
    u32 credit_limit;
    atomic_t credit_count;
    long timeout;
    const char                      *name;
    u32 num_rqs;
    struct drm_sched_rq             **sched_rq;
    wait_queue_head_t job_scheduled;
    atomic64_t job_id_count;
    struct workqueue_struct         *submit_wq;
    struct workqueue_struct         *timeout_wq;
    struct work_struct              work_run_job;
    struct work_struct              work_free_job;
    struct delayed_work             work_tdr;
    struct list_head                pending_list;
    spinlock_t job_list_lock;
    int hang_limit;
    atomic_t *score;
    atomic_t _score;
    bool ready;
    bool free_guilty;
    bool pause_submit;
    bool own_submit_wq;
    struct device                   *dev;
};
```

**Members**

- `ops`: backend operations provided by the driver.
- `credit_limit`: the credit limit of this scheduler
- `credit_count`: the current credit count of this scheduler
- `timeout`: the time after which a job is removed from the scheduler.
- `name`: name of the ring for which this scheduler is being used.
- `num_rqs`: Number of run-queues. This is at most DRM_SCHED_PRIORITY_COUNT,
  as there's usually one run-queue per priority, but could be less.
- `sched_rq`: An allocated array of run-queues of size **num_rqs**;
- `job_scheduled`: once [`drm_sched_entity_flush()`](#c-drm_sched_entity_flush) is called the scheduler
  waits on this wait queue until all the scheduled jobs are
  finished.
- `job_id_count`: used to assign unique id to the each job.
- `submit_wq`: workqueue used to queue **work_run_job** and **work_free_job**
- `timeout_wq`: workqueue used to queue **work_tdr**
- `work_run_job`: work which calls run_job op of each scheduler.
- `work_free_job`: work which calls free_job op of each scheduler.
- `work_tdr`: schedules a delayed call to **drm_sched_job_timedout** after the
  timeout interval is over.
- `pending_list`: the list of jobs which are currently in the job queue.
- `job_list_lock`: lock to protect the pending_list.
- `hang_limit`: once the hangs by a job crosses this limit then it is marked
  guilty and it will no longer be considered for scheduling.
- `score`: score to help loadbalancer pick a idle sched
- `_score`: score used when the driver doesn't provide one
- `ready`: marks if the underlying HW is ready to work
- `free_guilty`: A hit to time out handler to free the guilty job.
- `pause_submit`: pause queuing of **work_run_job** on **submit_wq**
- `own_submit_wq`: scheduler owns allocation of **submit_wq**
- `dev`: system [`struct device`](/kernel/hardware/driver-api/fundamentals/infrastructure.md#c-struct-device)

**Description**

One scheduler is implemented for each hardware ring.

#### <a id="c-struct-drm_sched_init_args"></a>`struct drm_sched_init_args`

parameters for initializing a DRM GPU scheduler

**Definition**

```c
struct drm_sched_init_args {
    const struct drm_sched_backend_ops *ops;
    struct workqueue_struct *submit_wq;
    struct workqueue_struct *timeout_wq;
    u32 num_rqs;
    u32 credit_limit;
    unsigned int hang_limit;
    long timeout;
    atomic_t *score;
    const char *name;
    struct device *dev;
};
```

**Members**

- `ops`: backend operations provided by the driver
- `submit_wq`: workqueue to use for submission. If NULL, an ordered wq is
  allocated and used.
- `timeout_wq`: workqueue to use for timeout work. If NULL, the system_wq is used.
- `num_rqs`: Number of run-queues. This may be at most DRM_SCHED_PRIORITY_COUNT,
  as there's usually one run-queue per priority, but may be less.
- `credit_limit`: the number of credits this scheduler can hold from all jobs
- `hang_limit`: number of times to allow a job to hang before dropping it.
  This mechanism is DEPRECATED. Set it to 0.
- `timeout`: timeout value in jiffies for submitted jobs.
- `score`: score atomic shared with other schedulers. May be NULL.
- `name`: name (typically the driver's name). Used for debugging
- `dev`: associated device. Used for debugging

#### <a id="c-struct-drm_sched_pending_job_iter"></a>`struct drm_sched_pending_job_iter`

DRM scheduler pending job iterator state

**Definition**

```c
struct drm_sched_pending_job_iter {
    struct drm_gpu_scheduler *sched;
};
```

**Members**

- `sched`: DRM scheduler associated with pending job iterator

#### <a id="c-drm_sched_for_each_pending_job"></a>`drm_sched_for_each_pending_job()`

```c
drm_sched_for_each_pending_job(__job, __sched, __entity)
```

Iterator for each pending job in scheduler

**Parameters**

- `__job`: Current pending job being iterated over
- `__sched`: DRM scheduler to iterate over pending jobs
- `__entity`: DRM scheduler entity to filter jobs, NULL indicates no filter

**Description**

Iterator for each pending job in scheduler, filtering on an entity, and
enforcing scheduler is fully stopped



#### <a id="c-drm_sched_tdr_queue_imm"></a>`drm_sched_tdr_queue_imm()`

```c
void drm_sched_tdr_queue_imm(struct drm_gpu_scheduler *sched)
```

- immediately start job timeout handler

**Parameters**

- `struct drm_gpu_scheduler *sched`: scheduler for which the timeout handling should be started.

**Description**

Start timeout handling immediately for the named scheduler.

#### <a id="c-drm_sched_fault"></a>`drm_sched_fault()`

```c
void drm_sched_fault(struct drm_gpu_scheduler *sched)
```

immediately start timeout handler

**Parameters**

- `struct drm_gpu_scheduler *sched`: scheduler where the timeout handling should be started.

**Description**

Start timeout handling immediately when the driver detects a hardware fault.

#### <a id="c-drm_sched_suspend_timeout"></a>`drm_sched_suspend_timeout()`

```c
unsigned long drm_sched_suspend_timeout(struct drm_gpu_scheduler *sched)
```

Suspend scheduler job timeout

**Parameters**

- `struct drm_gpu_scheduler *sched`: scheduler instance for which to suspend the timeout

**Description**

Suspend the delayed work timeout for the scheduler. This is done by
modifying the delayed work timeout to an arbitrary large value,
MAX_SCHEDULE_TIMEOUT in this case.

Returns the timeout remaining

#### <a id="c-drm_sched_resume_timeout"></a>`drm_sched_resume_timeout()`

```c
void drm_sched_resume_timeout(struct drm_gpu_scheduler *sched, unsigned long remaining)
```

Resume scheduler job timeout

**Parameters**

- `struct drm_gpu_scheduler *sched`: scheduler instance for which to resume the timeout
- `unsigned long remaining`: remaining timeout

**Description**

Resume the delayed work timeout for the scheduler.

#### <a id="c-drm_sched_stop"></a>`drm_sched_stop()`

```c
void drm_sched_stop(struct drm_gpu_scheduler *sched, struct drm_sched_job *bad)
```

stop the scheduler

**Parameters**

- `struct drm_gpu_scheduler *sched`: scheduler instance
- `struct drm_sched_job *bad`: job which caused the time out

**Description**

Stop the scheduler and also removes and frees all completed jobs.

**Note**

bad job will not be freed as it might be used later and so it's
callers responsibility to release it manually if it's not part of the
pending list any more.

This function is typically used for reset recovery (see the docu of
drm_sched_backend_ops.`timedout_job()` for details). Do not call it for
scheduler teardown, i.e., before calling [`drm_sched_fini()`](#c-drm_sched_fini).

As it's only used for reset recovery, drivers must not call this function
in their [`struct drm_sched_backend_ops`](#c-struct-drm_sched_backend_ops).timedout_job callback when they
skip a reset using [`enum drm_gpu_sched_stat`](#c-enum-drm_gpu_sched_stat).DRM_GPU_SCHED_STAT_NO_HANG.

#### <a id="c-drm_sched_start"></a>`drm_sched_start()`

```c
void drm_sched_start(struct drm_gpu_scheduler *sched, int errno)
```

recover jobs after a reset

**Parameters**

- `struct drm_gpu_scheduler *sched`: scheduler instance
- `int errno`: error to set on the pending fences

**Description**

This function is typically used for reset recovery (see the docu of
drm_sched_backend_ops.`timedout_job()` for details). Do not call it for
scheduler startup. The scheduler itself is fully operational after
[`drm_sched_init()`](#c-drm_sched_init) succeeded.

As it's only used for reset recovery, drivers must not call this function
in their [`struct drm_sched_backend_ops`](#c-struct-drm_sched_backend_ops).timedout_job callback when they
skip a reset using [`enum drm_gpu_sched_stat`](#c-enum-drm_gpu_sched_stat).DRM_GPU_SCHED_STAT_NO_HANG.

#### <a id="c-drm_sched_resubmit_jobs"></a>`drm_sched_resubmit_jobs()`

```c
void drm_sched_resubmit_jobs(struct drm_gpu_scheduler *sched)
```

Deprecated, don't use in new code!

**Parameters**

- `struct drm_gpu_scheduler *sched`: scheduler instance

**Description**

Re-submitting jobs was a concept AMD came up as cheap way to implement
recovery after a job timeout.

This turned out to be not working very well. First of all there are many
problem with the dma_fence implementation and requirements. Either the
implementation is risking deadlocks with core memory management or violating
documented implementation details of the dma_fence object.

Drivers can still save and restore their state for recovery operations, but
we shouldn't make this a general scheduler feature around the dma_fence
interface. The suggested driver-side replacement is to use
[`drm_sched_for_each_pending_job()`](#c-drm_sched_for_each_pending_job) after stopping the scheduler and implement
their own recovery operations.

#### <a id="c-drm_sched_job_init"></a>`drm_sched_job_init()`

```c
int drm_sched_job_init(struct drm_sched_job *job, struct drm_sched_entity *entity, u32 credits, void *owner, uint64_t drm_client_id)
```

init a scheduler job

**Parameters**

- `struct drm_sched_job *job`: scheduler job to init
- `struct drm_sched_entity *entity`: scheduler entity to use
- `u32 credits`: the number of credits this job contributes to the schedulers
  credit limit
- `void *owner`: job owner for debugging
- `uint64_t drm_client_id`: [`struct drm_file`](/kernel/hardware/gpu/drm-internals.md#c-struct-drm_file).client_id of the owner (used by trace
  events)

**Description**

Refer to [`drm_sched_entity_push_job()`](#c-drm_sched_entity_push_job) documentation
for locking considerations.

Drivers must make sure [`drm_sched_job_cleanup()`](#c-drm_sched_job_cleanup) if this function returns
successfully, even when **job** is aborted before [`drm_sched_job_arm()`](#c-drm_sched_job_arm) is called.

Note that this function does not assign a valid value to each struct member
of struct drm_sched_job. Take a look at that struct's documentation to see
who sets which struct member with what lifetime.

WARNING: amdgpu abuses `drm_sched.ready` to signal when the hardware
has died, which can mean that there's no valid runqueue for a **entity**.
This function returns -ENOENT in this case (which probably should be -EIO as
a more meanigful return value).

Returns 0 for success, negative error code otherwise.

#### <a id="c-drm_sched_job_arm"></a>`drm_sched_job_arm()`

```c
void drm_sched_job_arm(struct drm_sched_job *job)
```

arm a scheduler job for execution

**Parameters**

- `struct drm_sched_job *job`: scheduler job to arm

**Description**

This arms a scheduler job for execution. Specifically it initializes the
[`drm_sched_job.s_fence`](#c-struct-drm_sched_job) of **job**, so that it can be attached to struct dma_resv
or other places that need to track the completion of this job. It also
initializes sequence numbers, which are fundamental for fence ordering.

Refer to [`drm_sched_entity_push_job()`](#c-drm_sched_entity_push_job) documentation for locking
considerations.

Once this function was called, you *must* submit **job** with
[`drm_sched_entity_push_job()`](#c-drm_sched_entity_push_job).

This can only be called if [`drm_sched_job_init()`](#c-drm_sched_job_init) succeeded.

#### <a id="c-drm_sched_job_add_dependency"></a>`drm_sched_job_add_dependency()`

```c
int drm_sched_job_add_dependency(struct drm_sched_job *job, struct dma_fence *fence)
```

adds the fence as a job dependency

**Parameters**

- `struct drm_sched_job *job`: scheduler job to add the dependencies to
- `struct dma_fence *fence`: the dma_fence to add to the list of dependencies.

**Description**

Note that **fence** is consumed in both the success and error cases.

**Return**

0 on success, or an error on failing to expand the array.

#### <a id="c-drm_sched_job_add_syncobj_dependency"></a>`drm_sched_job_add_syncobj_dependency()`

```c
int drm_sched_job_add_syncobj_dependency(struct drm_sched_job *job, struct drm_file *file, u32 handle, u32 point)
```

adds a syncobj's fence as a job dependency

**Parameters**

- `struct drm_sched_job *job`: scheduler job to add the dependencies to
- `struct drm_file *file`: drm file private pointer
- `u32 handle`: syncobj handle to lookup
- `u32 point`: timeline point

**Description**

This adds the fence matching the given syncobj to **job**.

**Return**

0 on success, or an error on failing to expand the array.

#### <a id="c-drm_sched_job_add_resv_dependencies"></a>`drm_sched_job_add_resv_dependencies()`

```c
int drm_sched_job_add_resv_dependencies(struct drm_sched_job *job, struct dma_resv *resv, enum dma_resv_usage usage)
```

add all fences from the resv to the job

**Parameters**

- `struct drm_sched_job *job`: scheduler job to add the dependencies to
- `struct dma_resv *resv`: the dma_resv object to get the fences from
- `enum dma_resv_usage usage`: the dma_resv_usage to use to filter the fences

**Description**

This adds all fences matching the given usage from **resv** to **job**.
Must be called with the **resv** lock held.

**Return**

0 on success, or an error on failing to expand the array.

#### <a id="c-drm_sched_job_add_implicit_dependencies"></a>`drm_sched_job_add_implicit_dependencies()`

```c
int drm_sched_job_add_implicit_dependencies(struct drm_sched_job *job, struct drm_gem_object *obj, bool write)
```

adds implicit dependencies as job dependencies

**Parameters**

- `struct drm_sched_job *job`: scheduler job to add the dependencies to
- `struct drm_gem_object *obj`: the gem object to add new dependencies from.
- `bool write`: whether the job might write the object (so we need to depend on
  shared fences in the reservation object).

**Description**

This should be called after [`drm_gem_lock_reservations()`](#c-drm_gem_lock_reservations) on your array of
GEM objects used in the job but before updating the reservations with your
own fences.

**Return**

0 on success, or an error on failing to expand the array.

#### <a id="c-drm_sched_job_has_dependency"></a>`drm_sched_job_has_dependency()`

```c
bool drm_sched_job_has_dependency(struct drm_sched_job *job, struct dma_fence *fence)
```

check whether fence is the job's dependency

**Parameters**

- `struct drm_sched_job *job`: scheduler job to check
- `struct dma_fence *fence`: fence to look for

**Return**

True if **fence** is found within the job's dependencies, or otherwise false.

#### <a id="c-drm_sched_job_cleanup"></a>`drm_sched_job_cleanup()`

```c
void drm_sched_job_cleanup(struct drm_sched_job *job)
```

clean up scheduler job resources

**Parameters**

- `struct drm_sched_job *job`: scheduler job to clean up

**Description**

Cleans up the resources allocated with [`drm_sched_job_init()`](#c-drm_sched_job_init).

Drivers should call this from their error unwind code if **job** is aborted
before [`drm_sched_job_arm()`](#c-drm_sched_job_arm) is called.

[`drm_sched_job_arm()`](#c-drm_sched_job_arm) is a point of no return since it initializes the fences
and their sequence number etc. Once that function has been called, you *must*
submit it with [`drm_sched_entity_push_job()`](#c-drm_sched_entity_push_job) and cannot simply abort it by
calling [`drm_sched_job_cleanup()`](#c-drm_sched_job_cleanup).

This function should be called in the [`drm_sched_backend_ops.free_job`](#c-struct-drm_sched_backend_ops) callback.

#### <a id="c-drm_sched_pick_best"></a>`drm_sched_pick_best()`

```c
struct drm_gpu_scheduler * drm_sched_pick_best(struct drm_gpu_scheduler **sched_list, unsigned int num_sched_list)
```

Get a drm sched from a sched_list with the least load

**Parameters**

- `struct drm_gpu_scheduler **sched_list`: list of drm_gpu_schedulers
- `unsigned int num_sched_list`: number of drm_gpu_schedulers in the sched_list

**Description**

Returns pointer of the sched with the least load or NULL if none of the
drm_gpu_schedulers are ready

#### <a id="c-drm_sched_init"></a>`drm_sched_init()`

```c
int drm_sched_init(struct drm_gpu_scheduler *sched, const struct drm_sched_init_args *args)
```

Init a gpu scheduler instance

**Parameters**

- `struct drm_gpu_scheduler *sched`: scheduler instance
- `const struct drm_sched_init_args *args`: scheduler initialization arguments

**Description**

Return 0 on success, otherwise error code.

#### <a id="c-drm_sched_fini"></a>`drm_sched_fini()`

```c
void drm_sched_fini(struct drm_gpu_scheduler *sched)
```

Destroy a gpu scheduler

**Parameters**

- `struct drm_gpu_scheduler *sched`: scheduler instance

**Description**

Tears down and cleans up the scheduler.

This stops submission of new jobs to the hardware through [`struct drm_sched_backend_ops`](#c-struct-drm_sched_backend_ops).run_job. If [`struct drm_sched_backend_ops`](#c-struct-drm_sched_backend_ops).cancel_job
is implemented, all jobs will be canceled through it and afterwards cleaned
up through [`struct drm_sched_backend_ops`](#c-struct-drm_sched_backend_ops).free_job. If cancel_job is not
implemented, memory could leak.

#### <a id="c-drm_sched_increase_karma"></a>`drm_sched_increase_karma()`

```c
void drm_sched_increase_karma(struct drm_sched_job *bad)
```

Update sched_entity guilty flag

**Parameters**

- `struct drm_sched_job *bad`: The job guilty of time out

**Description**

Increment on every hang caused by the 'bad' job. If this exceeds the hang
limit of the scheduler then the respective sched entity is marked guilty and
jobs from it will not be scheduled further

#### <a id="c-drm_sched_wqueue_ready"></a>`drm_sched_wqueue_ready()`

```c
bool drm_sched_wqueue_ready(struct drm_gpu_scheduler *sched)
```

Is the scheduler ready for submission

**Parameters**

- `struct drm_gpu_scheduler *sched`: scheduler instance

**Description**

Returns true if submission is ready

#### <a id="c-drm_sched_wqueue_stop"></a>`drm_sched_wqueue_stop()`

```c
void drm_sched_wqueue_stop(struct drm_gpu_scheduler *sched)
```

stop scheduler submission

**Parameters**

- `struct drm_gpu_scheduler *sched`: scheduler instance

**Description**

Stops the scheduler from pulling new jobs from entities. It also stops
freeing jobs automatically through drm_sched_backend_ops.`free_job()`.

#### <a id="c-drm_sched_wqueue_start"></a>`drm_sched_wqueue_start()`

```c
void drm_sched_wqueue_start(struct drm_gpu_scheduler *sched)
```

start scheduler submission

**Parameters**

- `struct drm_gpu_scheduler *sched`: scheduler instance

**Description**

Restarts the scheduler after [`drm_sched_wqueue_stop()`](#c-drm_sched_wqueue_stop) has stopped it.

This function is not necessary for 'conventional' startup. The scheduler is
fully operational after [`drm_sched_init()`](#c-drm_sched_init) succeeded.

#### <a id="c-drm_sched_is_stopped"></a>`drm_sched_is_stopped()`

```c
bool drm_sched_is_stopped(struct drm_gpu_scheduler *sched)
```

Checks whether drm_sched is stopped

**Parameters**

- `struct drm_gpu_scheduler *sched`: DRM scheduler

**Return**

true if sched is stopped, false otherwise

#### <a id="c-drm_sched_job_is_signaled"></a>`drm_sched_job_is_signaled()`

```c
bool drm_sched_job_is_signaled(struct drm_sched_job *job)
```

DRM scheduler job is signaled

**Parameters**

- `struct drm_sched_job *job`: DRM scheduler job

**Description**

Determine if DRM scheduler job is signaled. DRM scheduler should be stopped
to obtain a stable snapshot of state. Both parent fence (hardware fence) and
finished fence (software fence) are checked to determine signaling state.

**Return**

true if job is signaled, false otherwise



#### <a id="c-drm_sched_entity_init"></a>`drm_sched_entity_init()`

```c
int drm_sched_entity_init(struct drm_sched_entity *entity, enum drm_sched_priority priority, struct drm_gpu_scheduler **sched_list, unsigned int num_sched_list, atomic_t *guilty)
```

Init a context entity used by scheduler when submit to HW ring.

**Parameters**

- `struct drm_sched_entity *entity`: scheduler entity to init
- `enum drm_sched_priority priority`: priority of the entity
- `struct drm_gpu_scheduler **sched_list`: the list of drm scheds on which jobs from this
  entity can be submitted
- `unsigned int num_sched_list`: number of drm sched in sched_list
- `atomic_t *guilty`: atomic_t set to 1 when a job on this queue
  is found to be guilty causing a timeout

**Description**

Note that the `sched_list` must have at least one element to schedule the entity.

For changing **priority** later on at runtime see
[`drm_sched_entity_set_priority()`](#c-drm_sched_entity_set_priority). For changing the set of schedulers
**sched_list** at runtime see [`drm_sched_entity_modify_sched()`](#c-drm_sched_entity_modify_sched).

An entity is cleaned up by calling [`drm_sched_entity_fini()`](#c-drm_sched_entity_fini). See also
[`drm_sched_entity_destroy()`](#c-drm_sched_entity_destroy).

Returns 0 on success or a negative error code on failure.

#### <a id="c-drm_sched_entity_modify_sched"></a>`drm_sched_entity_modify_sched()`

```c
void drm_sched_entity_modify_sched(struct drm_sched_entity *entity, struct drm_gpu_scheduler **sched_list, unsigned int num_sched_list)
```

Modify sched of an entity

**Parameters**

- `struct drm_sched_entity *entity`: scheduler entity to init
- `struct drm_gpu_scheduler **sched_list`: the list of new drm scheds which will replace
  existing entity->sched_list
- `unsigned int num_sched_list`: number of drm sched in sched_list

**Description**

Note that this must be called under the same common lock for **entity** as
[`drm_sched_job_arm()`](#c-drm_sched_job_arm) and [`drm_sched_entity_push_job()`](#c-drm_sched_entity_push_job), or the driver needs to
guarantee through some other means that this is never called while new jobs
can be pushed to **entity**.

#### <a id="c-drm_sched_entity_error"></a>`drm_sched_entity_error()`

```c
int drm_sched_entity_error(struct drm_sched_entity *entity)
```

return error of last scheduled job

**Parameters**

- `struct drm_sched_entity *entity`: scheduler entity to check

**Description**

Opportunistically return the error of the last scheduled job. Result can
change any time when new jobs are pushed to the hw.

#### <a id="c-drm_sched_entity_flush"></a>`drm_sched_entity_flush()`

```c
long drm_sched_entity_flush(struct drm_sched_entity *entity, long timeout)
```

Flush a context entity

**Parameters**

- `struct drm_sched_entity *entity`: scheduler entity
- `long timeout`: time to wait in for Q to become empty in jiffies.

**Description**

Splitting [`drm_sched_entity_fini()`](#c-drm_sched_entity_fini) into two functions, The first one does the
waiting, removes the entity from the runqueue and returns an error when the
process was killed.

Returns the remaining time in jiffies left from the input timeout

#### <a id="c-drm_sched_entity_fini"></a>`drm_sched_entity_fini()`

```c
void drm_sched_entity_fini(struct drm_sched_entity *entity)
```

Destroy a context entity

**Parameters**

- `struct drm_sched_entity *entity`: scheduler entity

**Description**

Cleanups up **entity** which has been initialized by [`drm_sched_entity_init()`](#c-drm_sched_entity_init).

If there are potentially job still in flight or getting newly queued
[`drm_sched_entity_flush()`](#c-drm_sched_entity_flush) must be called first. This function then goes over
the entity and signals all jobs with an error code if the process was killed.

#### <a id="c-drm_sched_entity_destroy"></a>`drm_sched_entity_destroy()`

```c
void drm_sched_entity_destroy(struct drm_sched_entity *entity)
```

Destroy a context entity

**Parameters**

- `struct drm_sched_entity *entity`: scheduler entity

**Description**

Calls [`drm_sched_entity_flush()`](#c-drm_sched_entity_flush) and [`drm_sched_entity_fini()`](#c-drm_sched_entity_fini) as a
convenience wrapper.

#### <a id="c-drm_sched_entity_set_priority"></a>`drm_sched_entity_set_priority()`

```c
void drm_sched_entity_set_priority(struct drm_sched_entity *entity, enum drm_sched_priority priority)
```

Sets priority of the entity

**Parameters**

- `struct drm_sched_entity *entity`: scheduler entity
- `enum drm_sched_priority priority`: scheduler priority

**Description**

Update the priority of runqueues used for the entity.

#### <a id="c-drm_sched_entity_push_job"></a>`drm_sched_entity_push_job()`

```c
void drm_sched_entity_push_job(struct drm_sched_job *sched_job)
```

Submit a job to the entity's job queue

**Parameters**

- `struct drm_sched_job *sched_job`: job to submit

**Note**

To guarantee that the order of insertion to queue matches the job's
fence sequence number this function should be called with [`drm_sched_job_arm()`](#c-drm_sched_job_arm)
under common lock for the struct drm_sched_entity that was set up for
**sched_job** in [`drm_sched_job_init()`](#c-drm_sched_job_init).

---

# Userland interfaces

_Peios Kernel / Hardware and drivers / Graphics_

> The DRM core exports several interfaces to applications, generally intended to be used through corresponding libdrm wrapper functions. In addition, drivers export device-specific interfaces for use by userspace drivers & device-aware…

> **Peios:** References to Unix root and file modes below describe the inherited interface conventions. They are not sufficient Peios authorization: native descriptor/handle checks, the separate sysfs write gate, and mapped native privileges apply as appropriate. Debugfs additionally remains subject to integrity lockdown. See [Peios kernel behaviour](</kernel/introduction/peios-behaviour.md>).


<a id="rst-userland-interfaces"></a>

<!-- Copyright 2020 DisplayLink (UK) Ltd. -->

The DRM core exports several interfaces to applications, generally intended to be used through corresponding libdrm wrapper functions. In addition, drivers export device-specific interfaces for use by userspace drivers &amp; device-aware applications through ioctls and sysfs files.

External interfaces include: memory mapping, context management, DMA operations, AGP management, vblank control, fence management, memory management, and output management.

Cover generic ioctls and sysfs layout here. We only need high-level info, since man pages should cover the rest.

<a id="rst-libdrm-device-lookup"></a>

## libdrm Device Lookup


BEWARE THE DRAGONS! MIND THE TRAPDOORS!

In an attempt to warn anyone else who's trying to figure out what's going
on here, I'll try to summarize the story. First things first, let's clear up
the names, because the kernel internals, libdrm and the ioctls are all named
differently:

- GET_UNIQUE ioctl, implemented by drm_getunique is wrapped up in libdrm
  through the drmGetBusid function.
- The libdrm drmSetBusid function is backed by the SET_UNIQUE ioctl. All
  that code is nerved in the kernel with [`drm_invalid_op()`](#c-drm_invalid_op).
- The internal set_busid kernel functions and driver callbacks are
  exclusively use by the SET_VERSION ioctl, because only drm 1.0 (which is
  nerved) allowed userspace to set the busid through the above ioctl.
- Other ioctls and functions involved are named consistently.

For anyone wondering what's the difference between drm 1.1 and 1.4: Correctly
handling pci domains in the busid on ppc. Doing this correctly was only
implemented in libdrm in 2010, hence can't be nerved yet. No one knows what's
special with drm 1.2 and 1.3.

Now the actual horror story of how device lookup in drm works. At large,
there's 2 different ways, either by busid, or by device driver name.

Opening by busid is fairly simple:

1. First call SET_VERSION to make sure pci domains are handled properly. As a
   side-effect this fills out the unique name in the master structure.
2. Call GET_UNIQUE to read out the unique name from the master structure,
   which matches the busid thanks to step 1. If it doesn't, proceed to try
   the next device node.

Opening by name is slightly different:

1. Directly call VERSION to get the version and to match against the driver
   name returned by that ioctl. Note that SET_VERSION is not called, which
   means the unique name for the master node just opening is _not_ filled
   out. This despite that with current drm device nodes are always bound to
   one device, and can't be runtime assigned like with drm 1.0.
2. Match driver name. If it mismatches, proceed to the next device node.
3. Call GET_UNIQUE, and check whether the unique name has length zero (by
   checking that the first byte in the string is 0). If that's not the case
   libdrm skips and proceeds to the next device node. Probably this is just
   copypasta from drm 1.0 times where a set unique name meant that the driver
   was in use already, but that's just conjecture.

Long story short: To keep the open by name logic working, GET_UNIQUE must
_not_ return a unique string when SET_VERSION hasn't been called yet,
otherwise libdrm breaks. Even when that unique string can't ever change, and
is totally irrelevant for actually opening the device because runtime
assignable device instances were only support in drm 1.0, which is long dead.
But the libdrm code in drmOpenByName somehow survived, hence this can't be
broken.


<a id="rst-primary-nodes-drm-master-and-authentication"></a>
<a id="rst-drm-primary-node"></a>

## Primary Nodes, DRM Master and Authentication


[`struct drm_master`](#c-struct-drm_master) is used to track groups of clients with open
primary device nodes. For every [`struct drm_file`](/kernel/hardware/gpu/drm-internals.md#c-struct-drm_file) which has had at
least once successfully became the device master (either through the
SET_MASTER IOCTL, or implicitly through opening the primary device node when
no one else is the current master that time) there exists one [`drm_master`](#c-struct-drm_master).
This is noted in [`drm_file.is_master`](/kernel/hardware/gpu/drm-internals.md#c-struct-drm_file). All other clients have just a pointer
to the [`drm_master`](#c-struct-drm_master) they are associated with.

In addition only one [`drm_master`](#c-struct-drm_master) can be the current master for a [`drm_device`](/kernel/hardware/gpu/drm-internals.md#c-struct-drm_device).
It can be switched through the DROP_MASTER and SET_MASTER IOCTL, or
implicitly through closing/opening the primary device node. See also
[`drm_is_current_master()`](#c-drm_is_current_master).

Clients can authenticate against the current master (if it matches their own)
using the GETMAGIC and AUTHMAGIC IOCTLs. Together with exchanging masters,
this allows controlled access to the device for an entire group of mutually
trusted clients.



#### <a id="c-drm_is_current_master"></a>`drm_is_current_master()`

```c
bool drm_is_current_master(struct drm_file *fpriv)
```

checks whether **priv** is the current master

**Parameters**

- `struct drm_file *fpriv`: DRM file private

**Description**

Checks whether **fpriv** is current master on its device. This decides whether a
client is allowed to run DRM_MASTER IOCTLs.

Most of the modern IOCTL which require DRM_MASTER are for kernel modesetting
- the current master is assumed to own the non-shareable display hardware.

#### <a id="c-drm_master_get"></a>`drm_master_get()`

```c
struct drm_master * drm_master_get(struct drm_master *master)
```

reference a master pointer

**Parameters**

- `struct drm_master *master`: [`struct drm_master`](#c-struct-drm_master)

**Description**

Increments the reference count of **master** and returns a pointer to **master**.

#### <a id="c-drm_file_get_master"></a>`drm_file_get_master()`

```c
struct drm_master * drm_file_get_master(struct drm_file *file_priv)
```

reference [`drm_file.master`](/kernel/hardware/gpu/drm-internals.md#c-struct-drm_file) of **file_priv**

**Parameters**

- `struct drm_file *file_priv`: DRM file private

**Description**

Increments the reference count of **file_priv**'s [`drm_file.master`](/kernel/hardware/gpu/drm-internals.md#c-struct-drm_file) and returns
the [`drm_file.master`](/kernel/hardware/gpu/drm-internals.md#c-struct-drm_file). If **file_priv** has no [`drm_file.master`](/kernel/hardware/gpu/drm-internals.md#c-struct-drm_file), returns NULL.

Master pointers returned from this function should be unreferenced using
[`drm_master_put()`](#c-drm_master_put).

#### <a id="c-drm_master_put"></a>`drm_master_put()`

```c
void drm_master_put(struct drm_master **master)
```

unreference and clear a master pointer

**Parameters**

- `struct drm_master **master`: pointer to a pointer of [`struct drm_master`](#c-struct-drm_master)

**Description**

This decrements the [`drm_master`](#c-struct-drm_master) behind **master** and sets it to NULL.



#### <a id="c-struct-drm_master"></a>`struct drm_master`

drm master structure

**Definition**

```c
struct drm_master {
    struct kref refcount;
    struct drm_device *dev;
    char *unique;
    int unique_len;
    struct idr magic_map;
    void *driver_priv;
    struct drm_master *lessor;
    int lessee_id;
    struct list_head lessee_list;
    struct list_head lessees;
    struct idr leases;
    struct idr lessee_idr;
};
```

**Members**

- `refcount`: Refcount for this master object.
- `dev`: Link back to the DRM device
- `unique`: Unique identifier: e.g. busid. Protected by
  [`drm_device.master_mutex`](/kernel/hardware/gpu/drm-internals.md#c-struct-drm_device).
- `unique_len`: Length of unique field. Protected by
  [`drm_device.master_mutex`](/kernel/hardware/gpu/drm-internals.md#c-struct-drm_device).
- `magic_map`: Map of used authentication tokens. Protected by
  [`drm_device.master_mutex`](/kernel/hardware/gpu/drm-internals.md#c-struct-drm_device).
- `driver_priv`: Pointer to driver-private information.
- `lessor`: Lease grantor, only set if this [`struct drm_master`](#c-struct-drm_master) represents a
  lessee holding a lease of objects from **lessor**. Full owners of the
  device have this set to NULL.

  The lessor does not change once it's set in `drm_lease_create()`, and
  each lessee holds a reference to its lessor that it releases upon
  being destroyed in `drm_lease_destroy()`.

  See also the section on display resource leasing.
- `lessee_id`: ID for lessees. Owners (i.e. **lessor** is NULL) always have ID 0.
  Protected by [`drm_device.mode_config`](/kernel/hardware/gpu/drm-internals.md#c-struct-drm_device)'s [`drm_mode_config.idr_mutex`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_mode_config).
- `lessee_list`: List entry of lessees of **lessor**, where they are linked to **lessees**.
  Not used for owners. Protected by [`drm_device.mode_config`](/kernel/hardware/gpu/drm-internals.md#c-struct-drm_device)'s
  [`drm_mode_config.idr_mutex`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_mode_config).
- `lessees`: List of drm_masters leasing from this one. Protected by
  [`drm_device.mode_config`](/kernel/hardware/gpu/drm-internals.md#c-struct-drm_device)'s [`drm_mode_config.idr_mutex`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_mode_config).

  This list is empty if no leases have been granted, or if all lessees
  have been destroyed. Since lessors are referenced by all their
  lessees, this master cannot be destroyed unless the list is empty.
- `leases`: Objects leased to this drm_master. Protected by
  [`drm_device.mode_config`](/kernel/hardware/gpu/drm-internals.md#c-struct-drm_device)'s [`drm_mode_config.idr_mutex`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_mode_config).

  Objects are leased all together in `drm_lease_create()`, and are
  removed all together when the lease is revoked.
- `lessee_idr`: All lessees under this owner (only used where **lessor** is NULL).
  Protected by [`drm_device.mode_config`](/kernel/hardware/gpu/drm-internals.md#c-struct-drm_device)'s [`drm_mode_config.idr_mutex`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_mode_config).

**Description**

Note that master structures are only relevant for the legacy/primary device
nodes, hence there can only be one per device, not one per drm_minor.


<a id="rst-drm-display-resource-leasing"></a>
<a id="rst-drm-leasing"></a>

## DRM Display Resource Leasing


DRM leases provide information about whether a DRM master may control a DRM
mode setting object. This enables the creation of multiple DRM masters that
manage subsets of display resources.

The original DRM master of a device 'owns' the available drm resources. It
may create additional DRM masters and 'lease' resources which it controls
to the new DRM master. This gives the new DRM master control over the
leased resources until the owner revokes the lease, or the new DRM master
is closed. Some helpful terminology:

- An 'owner' is a [`struct drm_master`](#c-struct-drm_master) that is not leasing objects from
  another [`struct drm_master`](#c-struct-drm_master), and hence 'owns' the objects. The owner can be
  identified as the [`struct drm_master`](#c-struct-drm_master) for which [`drm_master.lessor`](#c-struct-drm_master) is NULL.

- A 'lessor' is a [`struct drm_master`](#c-struct-drm_master) which is leasing objects to one or more
  other [`struct drm_master`](#c-struct-drm_master). Currently, lessees are not allowed to
  create sub-leases, hence the lessor is the same as the owner.

- A 'lessee' is a [`struct drm_master`](#c-struct-drm_master) which is leasing objects from some
  other [`struct drm_master`](#c-struct-drm_master). Each lessee only leases resources from a single
  lessor recorded in [`drm_master.lessor`](#c-struct-drm_master), and holds the set of objects that
  it is leasing in [`drm_master.leases`](#c-struct-drm_master).

- A 'lease' is a contract between the lessor and lessee that identifies
  which resources may be controlled by the lessee. All of the resources
  that are leased must be owned by or leased to the lessor, and lessors are
  not permitted to lease the same object to multiple lessees.

The set of objects any [`struct drm_master`](#c-struct-drm_master) 'controls' is limited to the set
of objects it leases (for lessees) or all objects (for owners).

Objects not controlled by a [`struct drm_master`](#c-struct-drm_master) cannot be modified through
the various state manipulating ioctls, and any state reported back to user
space will be edited to make them appear idle and/or unusable. For
instance, connectors always report 'disconnected', while encoders
report no possible crtcs or clones.

Since each lessee may lease objects from a single lessor, display resource
leases form a tree of [`struct drm_master`](#c-struct-drm_master). As lessees are currently not
allowed to create sub-leases, the tree depth is limited to 1. All of
these get activated simultaneously when the top level device owner changes
through the SETMASTER or DROPMASTER IOCTL, so [`drm_device.master`](/kernel/hardware/gpu/drm-internals.md#c-struct-drm_device) points to
the owner at the top of the lease tree (i.e. the [`struct drm_master`](#c-struct-drm_master) for which
[`drm_master.lessor`](#c-struct-drm_master) is NULL). The full list of lessees that are leasing
objects from the owner can be searched via the owner's
[`drm_master.lessee_idr`](#c-struct-drm_master).


<a id="rst-open-source-userspace-requirements"></a>

## Open-Source Userspace Requirements

The DRM subsystem has stricter requirements than most other kernel subsystems on what the userspace side for new uAPI needs to look like. This section here explains what exactly those requirements are, and why they exist.

The short summary is that any addition of DRM uAPI requires corresponding open-sourced userspace patches, and those patches must be reviewed and ready for merging into a suitable and canonical upstream project.

GFX devices (both display and render/GPU side) are really complex bits of hardware, with userspace and kernel by necessity having to work together really closely.  The interfaces, for rendering and modesetting, must be extremely wide and flexible, and therefore it is almost always impossible to precisely define them for every possible corner case. This in turn makes it really practically infeasible to differentiate between behaviour that's required by userspace, and which must not be changed to avoid regressions, and behaviour which is only an accidental artifact of the current implementation.

Without access to the full source code of all userspace users that means it becomes impossible to change the implementation details, since userspace could depend upon the accidental behaviour of the current implementation in minute details. And debugging such regressions without access to source code is pretty much impossible. As a consequence this means:

- The Linux kernel's "no regression" policy holds in practice only for open-source userspace of the DRM subsystem. DRM developers are perfectly fine if closed-source blob drivers in userspace use the same uAPI as the open drivers, but they must do so in the exact same way as the open drivers. Creative (ab)use of the interfaces will, and in the past routinely has, lead to breakage.

- Any new userspace interface must have an open-source implementation as demonstration vehicle.

The other reason for requiring open-source userspace is uAPI review. Since the kernel and userspace parts of a GFX stack must work together so closely, code review can only assess whether a new interface achieves its goals by looking at both sides. Making sure that the interface indeed covers the use-case fully leads to a few additional requirements:

- The open-source userspace must not be a toy/test application, but the real thing. Specifically it needs to handle all the usual error and corner cases. These are often the places where new uAPI falls apart and hence essential to assess the fitness of a proposed interface.

- The userspace side must be fully reviewed and tested to the standards of that userspace project. For e.g. mesa this means piglit testcases and review on the mailing list. This is again to ensure that the new interface actually gets the job done.  The userspace-side reviewer should also provide an Acked-by on the kernel uAPI patch indicating that they believe the proposed uAPI is sound and sufficiently documented and validated for userspace's consumption.

- The userspace patches must be against the canonical upstream, not some vendor fork. This is to make sure that no one cheats on the review and testing requirements by doing a quick fork.

- The kernel patch can only be merged after all the above requirements are met, but it **must** be merged to either drm-next or drm-misc-next **before** the userspace patches land. uAPI always flows from the kernel, doing things the other way round risks divergence of the uAPI definitions and header files.

These are fairly steep requirements, but have grown out from years of shared pain and experience with uAPI added hastily, and almost always regretted about just as fast. GFX devices change really fast, requiring a paradigm shift and entire new set of uAPI interfaces every few years at least. Together with the Linux kernel's guarantee to keep existing userspace running for 10+ years this is already rather painful for the DRM subsystem, with multiple different uAPIs for the same thing co-existing. If we add a few more complete mistakes into the mix every year it would be entirely unmanageable.

<a id="rst-render-nodes"></a>
<a id="rst-drm-render-node"></a>

## Render nodes

DRM core provides multiple character-devices for user-space to use. Depending on which device is opened, user-space can perform a different set of operations (mainly ioctls). The primary node is always created and called card&lt;num&gt;. Additionally, a currently unused control node, called controlD&lt;num&gt; is also created. The primary node provides all legacy operations and historically was the only interface used by userspace. With KMS, the control node was introduced. However, the planned KMS control interface has never been written and so the control node stays unused to date.

With the increased use of offscreen renderers and GPGPU applications, clients no longer require running compositors or graphics servers to make use of a GPU. But the DRM API required unprivileged clients to authenticate to a DRM-Master prior to getting GPU access. To avoid this step and to grant clients GPU access without authenticating, render nodes were introduced. Render nodes solely serve render clients, that is, no modesetting or privileged ioctls can be issued on render nodes. Only non-global rendering commands are allowed. If a driver supports render nodes, it must advertise it via the DRIVER_RENDER DRM driver capability. If not supported, the primary node must be used for render clients together with the legacy drmAuth authentication procedure.

If a driver advertises render node support, DRM core will create a separate render node called renderD&lt;num&gt;. There will be one render node per device. No ioctls except PRIME-related ioctls will be allowed on this node. Especially GEM_OPEN will be explicitly prohibited. For a complete list of driver-independent ioctls that can be used on render nodes, see the ioctls marked DRM_RENDER_ALLOW in drm_ioctl.c  Render nodes are designed to avoid the buffer-leaks, which occur if clients guess the flink names or mmap offsets on the legacy interface. Additionally to this basic interface, drivers must mark their driver-dependent render-only ioctls as DRM_RENDER_ALLOW so render clients can use them. Driver authors must be careful not to allow any privileged ioctls on render nodes.

With render nodes, user-space can now control access to the render node via basic file-system access-modes. A running graphics server which authenticates clients on the privileged primary/legacy node is no longer required. Instead, a client can open the render node and is immediately granted GPU access. Communication between clients (or servers) is done via PRIME. FLINK from render node to legacy node is not supported. New clients must not use the insecure FLINK interface.

Besides dropping all modeset/global ioctls, render nodes also drop the DRM-Master concept. There is no reason to associate render clients with a DRM-Master as they are independent of any graphics server. Besides, they must work without any running master, anyway. Drivers must be able to run without a master object if they support render nodes. If, on the other hand, a driver requires shared state between clients which is visible to user-space and accessible beyond open-file boundaries, they cannot support render nodes.

<a id="rst-device-hot-unplug"></a>

## Device Hot-Unplug

> [!NOTE]
>
> The following is the plan. Implementation is not there yet (2020 May).

Graphics devices (display and/or render) may be connected via USB (e.g. display adapters or docking stations) or Thunderbolt (e.g. eGPU). An end user is able to hot-unplug this kind of devices while they are being used, and expects that the very least the machine does not crash. Any damage from hot-unplugging a DRM device needs to be limited as much as possible and userspace must be given the chance to handle it if it wants to. Ideally, unplugging a DRM device still lets a desktop continue to run, but that is going to need explicit support throughout the whole graphics stack: from kernel and userspace drivers, through display servers, via window system protocols, and in applications and libraries.

Other scenarios that should lead to the same are: unrecoverable GPU crash, PCI device disappearing off the bus, or forced unbind of a driver from the physical device.

In other words, from userspace perspective everything needs to keep on working more or less, until userspace stops using the disappeared DRM device and closes it completely. Userspace will learn of the device disappearance from the device removed uevent, ioctls returning ENODEV (or driver-specific ioctls returning driver-specific things), or open() returning ENXIO.

Only after userspace has closed all relevant DRM device and dmabuf file descriptors and removed all mmaps, the DRM driver can tear down its instance for the device that no longer exists. If the same physical device somehow comes back in the mean time, it shall be a new DRM device.

Similar to PIDs, chardev minor numbers are not recycled immediately. A new DRM device always picks the next free minor number compared to the previous one allocated, and wraps around when minor numbers are exhausted.

The goal raises at least the following requirements for the kernel and drivers.

<a id="rst-requirements-for-kms-uapi"></a>

### Requirements for KMS UAPI

- KMS connectors must change their status to disconnected.

- Legacy modesets and pageflips, and atomic commits, both real and TEST_ONLY, and any other ioctls either fail with ENODEV or fake success.

- Pending non-blocking KMS operations deliver the DRM events userspace is expecting. This applies also to ioctls that faked success.

- open() on a device node whose underlying device has disappeared will fail with ENXIO.

- Attempting to create a DRM lease on a disappeared DRM device will fail with ENODEV. Existing DRM leases remain and work as listed above.

<a id="rst-requirements-for-render-and-cross-device-uapi"></a>

### Requirements for Render and Cross-Device UAPI

- All GPU jobs that can no longer run must have their fences force-signalled to avoid inflicting hangs on userspace. The associated error code is ENODEV.

- Some userspace APIs already define what should happen when the device disappears (OpenGL, GL ES: [GL_KHR_robustness](<https://www.khronos.org/registry/OpenGL/extensions/KHR/KHR_robustness.txt>); [Vulkan](<https://www.khronos.org/vulkan/>): VK_ERROR_DEVICE_LOST; etc.). DRM drivers are free to implement this behaviour the way they see best, e.g. returning failures in driver-specific ioctls and handling those in userspace drivers, or rely on uevents, and so on.

- dmabuf which point to memory that has disappeared will either fail to import with ENODEV or continue to be successfully imported if it would have succeeded before the disappearance. See also about memory maps below for already imported dmabufs.

- Attempting to import a dmabuf to a disappeared device will either fail with ENODEV or succeed if it would have succeeded without the disappearance.

- open() on a device node whose underlying device has disappeared will fail with ENXIO.

<a id="rst-gl-khr-robustness"></a>



<a id="rst-vulkan"></a>



<a id="rst-requirements-for-memory-maps"></a>

### Requirements for Memory Maps

Memory maps have further requirements that apply to both existing maps and maps created after the device has disappeared. If the underlying memory disappears, the map is created or modified such that reads and writes will still complete successfully but the result is undefined. This applies to both userspace mmap()'d memory and memory pointed to by dmabuf which might be mapped to other devices (cross-device dmabuf imports).

Raising SIGBUS is not an option, because userspace cannot realistically handle it. Signal handlers are global, which makes them extremely difficult to use correctly from libraries like those that Mesa produces. Signal handlers are not composable, you can't have different handlers for GPU1 and GPU2 from different vendors, and a third handler for mmapped regular files. Threads cause additional pain with signal handling as well.

<a id="rst-device-reset"></a>

## Device reset

The GPU stack is really complex and is prone to errors, from hardware bugs, faulty applications and everything in between the many layers. Some errors require resetting the device in order to make the device usable again. This section describes the expectations for DRM and usermode drivers when a device resets and how to propagate the reset status.

Device resets can not be disabled without tainting the kernel, which can lead to hanging the entire kernel through shrinkers/mmu_notifiers. Userspace role in device resets is to propagate the message to the application and apply any special policy for blocking guilty applications, if any. Corollary is that debugging a hung GPU context require hardware support to be able to preempt such a GPU context while it's stopped.

<a id="rst-kernel-mode-driver"></a>

### Kernel Mode Driver

The KMD is responsible for checking if the device needs a reset, and to perform it as needed. Usually a hang is detected when a job gets stuck executing.

Propagation of errors to userspace has proven to be tricky since it goes in the opposite direction of the usual flow of commands. Because of this vendor independent error handling was added to the &amp;dma_fence object, this way drivers can add an error code to their fences before signaling them. See function dma_fence_set_error() on how to do this and for examples of error codes to use.

The DRM scheduler also allows setting error codes on all pending fences when hardware submissions are restarted after an reset. Error codes are also forwarded from the hardware fence to the scheduler fence to bubble up errors to the higher levels of the stack and eventually userspace.

Fence errors can be queried by userspace through the generic SYNC_IOC_FILE_INFO IOCTL as well as through driver specific interfaces.

Additional to setting fence errors drivers should also keep track of resets per context, the DRM scheduler provides the drm_sched_entity_error() function as helper for this use case. After a reset, KMD should reject new command submissions for affected contexts.

<a id="rst-user-mode-driver"></a>

### User Mode Driver

After command submission, UMD should check if the submission was accepted or rejected. After a reset, KMD should reject submissions, and UMD can issue an ioctl to the KMD to check the reset status, and this can be checked more often if the UMD requires it. After detecting a reset, UMD will then proceed to report it to the application using the appropriate API error code, as explained in the section below about robustness.

<a id="rst-robustness"></a>

### Robustness

The only way to try to keep a graphical API context working after a reset is if it complies with the robustness aspects of the graphical API that it is using.

Graphical APIs provide ways to applications to deal with device resets. However, there is no guarantee that the app will use such features correctly, and a userspace that doesn't support robust interfaces (like a non-robust OpenGL context or API without any robustness support like libva) leave the robustness handling entirely to the userspace driver. There is no strong community consensus on what the userspace driver should do in that case, since all reasonable approaches have some clear downsides.

<a id="rst-opengl"></a>

#### OpenGL

Apps using OpenGL should use the available robust interfaces, like the extension `GL_ARB_robustness` (or `GL_EXT_robustness` for OpenGL ES). This interface tells if a reset has happened, and if so, all the context state is considered lost and the app proceeds by creating new ones. There's no consensus on what to do to if robustness is not in use.

<a id="rst-vulkan-1"></a>

#### Vulkan

Apps using Vulkan should check for `VK_ERROR_DEVICE_LOST` for submissions. This error code means, among other things, that a device reset has happened and it needs to recreate the contexts to keep going.

<a id="rst-reporting-causes-of-resets"></a>

### Reporting causes of resets

Apart from propagating the reset through the stack so apps can recover, it's really useful for driver developers to learn more about what caused the reset in the first place. For this, drivers can make use of devcoredump to store relevant information about the reset and send device wedged event with `none` recovery method (as explained in "Device Wedging" chapter) to notify userspace, so this information can be collected and added to user bug reports.

<a id="rst-device-wedging"></a>

## Device Wedging

Drivers can optionally make use of device wedged event (implemented as drm_dev_wedged_event() in DRM subsystem), which notifies userspace of 'wedged' (hanged/unusable) state of the DRM device through a uevent. This is useful especially in cases where the device is no longer operating as expected and has become unrecoverable from driver context. Purpose of this implementation is to provide drivers a generic way to recover the device with the help of userspace intervention, without taking any drastic measures (like resetting or re-enumerating the full bus, on which the underlying physical device is sitting) in the driver.

A 'wedged' device is basically a device that is declared dead by the driver after exhausting all possible attempts to recover it from driver context. The uevent is the notification that is sent to userspace along with a hint about what could possibly be attempted to recover the device from userspace and bring it back to usable state. Different drivers may have different ideas of a 'wedged' device depending on hardware implementation of the underlying physical device, and hence the vendor agnostic nature of the event. It is up to the drivers to decide when they see the need for device recovery and how they want to recover from the available methods.

<a id="rst-driver-prerequisites"></a>

### Driver prerequisites

The driver, before opting for recovery, needs to make sure that the 'wedged' device doesn't harm the system as a whole by taking care of the prerequisites. Necessary actions must include disabling DMA to system memory as well as any communication channels with other devices. Further, the driver must ensure that all dma_fences are signalled and any device state that the core kernel might depend on is cleaned up. All existing mmaps should be invalidated and page faults should be redirected to a dummy page. Once the event is sent, the device must be kept in 'wedged' state until the recovery is performed. New accesses to the device (IOCTLs) should be rejected, preferably with an error code that resembles the type of failure the device has encountered. This will signify the reason for wedging, which can be reported to the application if needed.

<a id="rst-recovery"></a>

### Recovery

Current implementation defines four recovery methods, out of which, drivers can use any one, multiple or none. Method(s) of choice will be sent in the uevent environment as `WEDGED=<method1>[,..,<methodN>]` in order of less to more side-effects. See the section [Vendor Specific Recovery](<#rst-vendor-specific-recovery>) for `WEDGED=vendor-specific`. If driver is unsure about recovery or method is unknown, `WEDGED=unknown` will be sent instead.

Userspace consumers can parse this event and attempt recovery as per the following expectations.

>
> <table>
> <thead>
> <tr>
> <th>
>
>
> Recovery method
>
> </th>
> <th>
>
>
> Consumer expectations
>
> </th>
> </tr>
> </thead>
> <tbody>
> <tr>
> <td>
>
>
> none
>
> </td>
> <td>
>
>
> optional telemetry collection
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> rebind
>
> </td>
> <td>
>
>
> unbind + bind driver
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> bus-reset
>
> </td>
> <td>
>
>
> unbind + bus reset/re-enumeration + bind
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> vendor-specific
>
> </td>
> <td>
>
>
> vendor specific recovery method
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> unknown
>
> </td>
> <td>
>
>
> consumer policy
>
> </td>
> </tr>
> </tbody>
> </table>

The only exception to this is `WEDGED=none`, which signifies that the device was temporarily 'wedged' at some point but was recovered from driver context using device specific methods like reset. No explicit recovery is expected from the consumer in this case, but it can still take additional steps like gathering telemetry information (devcoredump, syslog). This is useful because the first hang is usually the most critical one which can result in consequential hangs or complete wedging.

<a id="rst-vendor-specific-recovery"></a>

### Vendor Specific Recovery

When `WEDGED=vendor-specific` is sent, it indicates that the device requires a recovery procedure specific to the hardware vendor and is not one of the standardized approaches.

`WEDGED=vendor-specific` may be used to indicate different cases within a single vendor driver, each requiring a distinct recovery procedure. In such scenarios, the vendor driver must provide comprehensive documentation that describes each case, include additional hints to identify specific case and outline the corresponding recovery procedure. The documentation includes:

Case - A list of all cases that sends the `WEDGED=vendor-specific` recovery method.

Hints - Additional Information to assist the userspace consumer in identifying and differentiating between different cases. This can be exposed through sysfs, debugfs, traces, dmesg etc.

Recovery Procedure - Clear instructions and guidance for recovering each case. This may include userspace scripts, tools needed for the recovery procedure.

It is the responsibility of the admin/userspace consumer to identify the case and verify additional identification hints before attempting a recovery procedure.

Example: If the device uses the Xe driver, then userspace consumer should refer to [Xe Device Wedging](</kernel/hardware/gpu/xe/xe-device.md#rst-xe-device-wedging>) for the detailed documentation.

<a id="rst-task-information"></a>

### Task information

The information about which application (if any) was involved in the device wedging is useful for userspace if they want to notify the user about what happened (e.g. the compositor display a message to the user "The &lt;task name&gt; caused a graphical error and the system recovered") or to implement policies (e.g. the daemon may "ban" an task that keeps resetting the device). If the task information is available, the uevent will display as `PID=<pid>` and `TASK=<task name>`. Otherwise, `PID` and `TASK` will not appear in the event string.

The reliability of this information is driver and hardware specific, and should be taken with a caution regarding it's precision. To have a big picture of what really happened, the devcoredump file provides much more detailed information about the device state and about the event.

<a id="rst-consumer-prerequisites"></a>

### Consumer prerequisites

It is the responsibility of the consumer to make sure that the device or its resources are not in use by any process before attempting recovery. With IOCTLs erroring out, all device memory should be unmapped and file descriptors should be closed to prevent leaks or undefined behaviour. The idea here is to clear the device of all user context beforehand and set the stage for a clean recovery.

For `WEDGED=vendor-specific` recovery method, it is the responsibility of the consumer to check the driver documentation and the usecase before attempting a recovery.

<a id="rst-example-rebind"></a>

### Example - rebind

Udev rule:



```text
SUBSYSTEM=="drm", ENV{WEDGED}=="rebind", DEVPATH=="*/drm/card[0-9]",
RUN+="/path/to/rebind.sh $env{DEVPATH}"
```

Recovery script:



```text
#!/bin/sh

DEVPATH=$(readlink -f /sys/$1/device)
DEVICE=$(basename $DEVPATH)
DRIVER=$(readlink -f $DEVPATH/driver)

echo -n $DEVICE > $DRIVER/unbind
echo -n $DEVICE > $DRIVER/bind
```

<a id="rst-customization"></a>

### Customization

Although basic recovery is possible with a simple script, consumers can define custom policies around recovery. For example, if the driver supports multiple recovery methods, consumers can opt for the suitable one depending on scenarios like repeat offences or vendor specific failures. Consumers can also choose to have the device available for debugging or telemetry collection and base their recovery decision on the findings. This is useful especially when the driver is unsure about recovery or method is unknown.

<a id="rst-ioctl-support-on-device-nodes"></a>
<a id="rst-drm-driver-ioctl"></a>

## IOCTL Support on Device Nodes


First things first, driver private IOCTLs should only be needed for drivers
supporting rendering. Kernel modesetting is all standardized, and extended
through properties. There are a few exceptions in some existing drivers,
which define IOCTL for use by the display DRM master, but they all predate
properties.

Now if you do have a render driver you always have to support it through
driver private properties. There's a few steps needed to wire all the things
up.

First you need to define the structure for your IOCTL in your driver private
UAPI header in `include/uapi/drm/my_driver_drm.h`:

```text
struct my_driver_operation {
        u32 some_thing;
        u32 another_thing;
};
```

Please make sure that you follow all the best practices from
`Documentation/process/botching-up-ioctls.rst`. Note that [`drm_ioctl()`](#c-drm_ioctl)
automatically zero-extends structures, hence make sure you can add more stuff
at the end, i.e. don't put a variable sized array there.

Then you need to define your IOCTL number, using one of `DRM_IO()`, `DRM_IOR()`,
`DRM_IOW()` or `DRM_IOWR()`. It must start with the DRM_IOCTL\_ prefix:

```text
##define DRM_IOCTL_MY_DRIVER_OPERATION \
    DRM_IOW(DRM_COMMAND_BASE, struct my_driver_operation)
```

DRM driver private IOCTL must be in the range from DRM_COMMAND_BASE to
DRM_COMMAND_END. Finally you need an array of [`struct drm_ioctl_desc`](#c-struct-drm_ioctl_desc) to wire
up the handlers and set the access rights:

```text
static const struct drm_ioctl_desc my_driver_ioctls[] = {
    DRM_IOCTL_DEF_DRV(MY_DRIVER_OPERATION, my_driver_operation,
            DRM_AUTH|DRM_RENDER_ALLOW),
};
```

And then assign this to the [`drm_driver.ioctls`](/kernel/hardware/gpu/drm-internals.md#c-struct-drm_driver) field in your driver
structure.

See the separate chapter on file operations for how
the driver-specific IOCTLs are wired up.


<a id="rst-recommended-ioctl-return-values"></a>

### Recommended IOCTL Return Values

In theory a driver's IOCTL callback is only allowed to return very few error codes. In practice it's good to abuse a few more. This section documents common practice within the DRM subsystem:

- **ENOENT:**

  Strictly this should only be used when a file doesn't exist e.g. when calling the open() syscall. We reuse that to signal any kind of object lookup failure, e.g. for unknown GEM buffer object handles, unknown KMS object handles and similar cases.

- **ENOSPC:**

  Some drivers use this to differentiate "out of kernel memory" from "out of VRAM". Sometimes also applies to other limited gpu resources used for rendering (e.g. when you have a special limited compression buffer). Sometimes resource allocation/reservation issues in command submission IOCTLs are also signalled through EDEADLK.

  Simply running out of kernel/system memory is signalled through ENOMEM.

- **EPERM/EACCES:**

  Returned for an operation that is valid, but needs more privileges. E.g. root-only or much more common, DRM master-only operations return this when called by unpriviledged clients. There's no clear difference between EACCES and EPERM.

- **ENODEV:**

  The device is not present anymore or is not yet fully initialized.

- **EOPNOTSUPP:**

  Feature (like PRIME, modesetting, GEM) is not supported by the driver.

- **ENXIO:**

  Remote failure, either a hardware transaction (like i2c), but also used when the exporting driver of a shared dma-buf or fence doesn't support a feature needed.

- **EINTR:**

  DRM drivers assume that userspace restarts all IOCTLs. Any DRM IOCTL can return EINTR and in such a case should be restarted with the IOCTL parameters left unchanged.

- **EIO:**

  The GPU died and couldn't be resurrected through a reset. Modesetting hardware failures are signalled through the "link status" connector property.

- **EINVAL:**

  Catch-all for anything that is an invalid argument combination which cannot work.

IOCTL also use other error codes like ETIME, EFAULT, EBUSY, ENOTTY but their usage is in line with the common meanings. The above list tries to just document DRM specific patterns. Note that ENOTTY has the slightly unintuitive meaning of "this IOCTL does not exist", and is used exactly as such in DRM.


#### <a id="c-drm_ioctl_t"></a>`drm_ioctl_t()`

```c
typedef typedef int drm_ioctl_t(struct drm_device *dev, void *data, struct drm_file *file_priv)
```

DRM ioctl function type.

**Parameters**

- `struct drm_device *dev`: DRM device inode
- `void *data`: private pointer of the ioctl call
- `struct drm_file *file_priv`: DRM file this ioctl was made on

**Description**

This is the DRM ioctl typedef. Note that [`drm_ioctl()`](#c-drm_ioctl) has alrady copied **data**
into kernel-space, and will also copy it back, depending upon the read/write
settings in the ioctl command code.

#### <a id="c-drm_ioctl_compat_t"></a>`drm_ioctl_compat_t()`

```c
typedef typedef int drm_ioctl_compat_t(struct file *filp, unsigned int cmd, unsigned long arg)
```

compatibility DRM ioctl function type.

**Parameters**

- `struct file *filp`: file pointer
- `unsigned int cmd`: ioctl command code
- `unsigned long arg`: DRM file this ioctl was made on

**Description**

Just a typedef to make declaring an array of compatibility handlers easier.
New drivers shouldn't screw up the structure layout for their ioctl
structures and hence never need this.

#### <a id="c-enum-drm_ioctl_flags"></a>`enum drm_ioctl_flags`

DRM ioctl flags

**Constants**

- `DRM_AUTH`: This is for ioctl which are used for rendering, and require that the
  file descriptor is either for a render node, or if it's a
  legacy/primary node, then it must be authenticated.
- `DRM_MASTER`: This must be set for any ioctl which can change the modeset or
  display state. Userspace must call the ioctl through a primary node,
  while it is the active master.

  Note that read-only modeset ioctl can also be called by
  unauthenticated clients, or when a master is not the currently active
  one.
- `DRM_ROOT_ONLY`: Anything that could potentially wreak a master file descriptor needs
  to have this flag set. Current that's only for the SETMASTER and
  DROPMASTER ioctl, which e.g. logind can call to force a non-behaving
  master (display compositor) into compliance.

  This is equivalent to callers with the SYSADMIN capability.
- `DRM_RENDER_ALLOW`: This is used for all ioctl needed for rendering only, for drivers
  which support render nodes. This should be all new render drivers,
  and hence it should be always set for any ioctl with DRM_AUTH set.
  Note though that read-only query ioctl might have this set, but have
  not set DRM_AUTH because they do not require authentication.

**Description**

Various flags that can be set in [`drm_ioctl_desc.flags`](#c-struct-drm_ioctl_desc) to control how
userspace can use a given ioctl.

#### <a id="c-struct-drm_ioctl_desc"></a>`struct drm_ioctl_desc`

DRM driver ioctl entry

**Definition**

```c
struct drm_ioctl_desc {
    unsigned int cmd;
    enum drm_ioctl_flags flags;
    drm_ioctl_t *func;
    const char *name;
};
```

**Members**

- `cmd`: ioctl command number, without flags
- `flags`: a bitmask of [`enum drm_ioctl_flags`](#c-enum-drm_ioctl_flags)
- `func`: handler for this ioctl
- `name`: user-readable name for debug output

**Description**

For convenience it's easier to create these using the [`DRM_IOCTL_DEF_DRV()`](#c-DRM_IOCTL_DEF_DRV)
macro.

#### <a id="c-DRM_IOCTL_DEF_DRV"></a>`DRM_IOCTL_DEF_DRV()`

```c
DRM_IOCTL_DEF_DRV(ioctl, _func, _flags)
```

helper macro to fill out a [`struct drm_ioctl_desc`](#c-struct-drm_ioctl_desc)

**Parameters**

- `ioctl`: ioctl command suffix
- `_func`: handler for the ioctl
- `_flags`: a bitmask of [`enum drm_ioctl_flags`](#c-enum-drm_ioctl_flags)

**Description**

Small helper macro to create a [`struct drm_ioctl_desc`](#c-struct-drm_ioctl_desc) entry. The ioctl
command number is constructed by prepending `DRM_IOCTL\_` and passing that
to `DRM_IOCTL_NR()`.



#### <a id="c-drm_noop"></a>`drm_noop()`

```c
int drm_noop(struct drm_device *dev, void *data, struct drm_file *file_priv)
```

DRM no-op ioctl implementation

**Parameters**

- `struct drm_device *dev`: DRM device for the ioctl
- `void *data`: data pointer for the ioctl
- `struct drm_file *file_priv`: DRM file for the ioctl call

**Description**

This no-op implementation for drm ioctls is useful for deprecated
functionality where we can't return a failure code because existing userspace
checks the result of the ioctl, but doesn't care about the action.

Always returns successfully with 0.

#### <a id="c-drm_invalid_op"></a>`drm_invalid_op()`

```c
int drm_invalid_op(struct drm_device *dev, void *data, struct drm_file *file_priv)
```

DRM invalid ioctl implementation

**Parameters**

- `struct drm_device *dev`: DRM device for the ioctl
- `void *data`: data pointer for the ioctl
- `struct drm_file *file_priv`: DRM file for the ioctl call

**Description**

This no-op implementation for drm ioctls is useful for deprecated
functionality where we really don't want to allow userspace to call the ioctl
any more. This is the case for old ums interfaces for drivers that
transitioned to kms gradually and so kept the old legacy tables around. This
only applies to radeon and i915 kms drivers, other drivers shouldn't need to
use this function.

Always fails with a return value of -EINVAL.

#### <a id="c-drm_ioctl"></a>`drm_ioctl()`

```c
long drm_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
```

ioctl callback implementation for DRM drivers

**Parameters**

- `struct file *filp`: file this ioctl is called on
- `unsigned int cmd`: ioctl cmd number
- `unsigned long arg`: user argument

**Description**

Looks up the ioctl function in the DRM core and the driver dispatch table,
stored in [`drm_driver.ioctls`](/kernel/hardware/gpu/drm-internals.md#c-struct-drm_driver). It checks for necessary permission by calling
`drm_ioctl_permit()`, and dispatches to the respective function.

**Return**

Zero on success, negative error code on failure.

#### <a id="c-drm_ioctl_flags"></a>`drm_ioctl_flags()`

```c
bool drm_ioctl_flags(unsigned int nr, unsigned int *flags)
```

Check for core ioctl and return ioctl permission flags

**Parameters**

- `unsigned int nr`: ioctl number
- `unsigned int *flags`: where to return the ioctl permission flags

**Description**

This ioctl is only used by the vmwgfx driver to augment the access checks
done by the drm core and insofar a pretty decent layering violation. This
shouldn't be used by any drivers.

**Return**

True if the **nr** corresponds to a DRM core ioctl number, false otherwise.



#### <a id="c-drm_compat_ioctl"></a>`drm_compat_ioctl()`

```c
long drm_compat_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
```

32bit IOCTL compatibility handler for DRM drivers

**Parameters**

- `struct file *filp`: file this ioctl is called on
- `unsigned int cmd`: ioctl cmd number
- `unsigned long arg`: user argument

**Description**

Compatibility handler for 32 bit userspace running on 64 kernels. All actual
IOCTL handling is forwarded to [`drm_ioctl()`](#c-drm_ioctl), while marshalling structures as
appropriate. Note that this only handles DRM core IOCTLs, if the driver has
botched IOCTL itself, it must handle those by wrapping this function.

**Return**

Zero on success, negative error code on failure.


<a id="rst-testing-and-validation"></a>

## Testing and validation

<a id="rst-testing-requirements-for-userspace-api"></a>

### Testing Requirements for userspace API

New cross-driver userspace interface extensions, like new IOCTL, new KMS properties, new files in sysfs or anything else that constitutes an API change should have driver-agnostic testcases in IGT for that feature, if such a test can be reasonably made using IGT for the target hardware.

<a id="rst-validating-changes-with-igt"></a>

### Validating changes with IGT

There's a collection of tests that aims to cover the whole functionality of DRM drivers and that can be used to check that changes to DRM drivers or the core don't regress existing functionality. This test suite is called IGT and its code and instructions to build and run can be found in [https://gitlab.freedesktop.org/drm/igt-gpu-tools/](<https://gitlab.freedesktop.org/drm/igt-gpu-tools/>).

<a id="rst-using-vkms-to-test-drm-api"></a>

### Using VKMS to test DRM API

VKMS is a software-only model of a KMS driver that is useful for testing and for running compositors. VKMS aims to enable a virtual display without the need for a hardware display capability. These characteristics made VKMS a perfect tool for validating the DRM core behavior and also support the compositor developer. VKMS makes it possible to test DRM functions in a virtual machine without display, simplifying the validation of some of the core changes.

To Validate changes in DRM API with VKMS, start setting the kernel: make sure to enable VKMS module; compile the kernel with the VKMS enabled and install it in the target machine. VKMS can be run in a Virtual Machine (QEMU, virtme or similar). It's recommended the use of KVM with the minimum of 1GB of RAM and four cores.

It's possible to run the IGT-tests in a VM in two ways:

> 1. Use IGT inside a VM
>
> 2. Use IGT from the host machine and write the results in a shared directory.

Following is an example of using a VM with a shared directory with the host machine to run igt-tests. This example uses virtme:



```text
$ virtme-run --rwdir /path/for/shared_dir --kdir=path/for/kernel/directory --mods=auto
```

Run the igt-tests in the guest machine. This example runs the 'kms_flip' tests:



```text
$ /path/for/igt-gpu-tools/scripts/run-tests.sh -p -s -t "kms_flip.*" -v
```

In this example, instead of building the igt_runner, Piglit is used (-p option). It creates an HTML summary of the test results and saves them in the folder "igt-gpu-tools/results". It executes only the igt-tests matching the -t option.

<a id="rst-display-crc-support"></a>

### Display CRC Support


DRM device drivers can provide to userspace CRC information of each frame as
it reached a given hardware component (a CRC sampling "source").

Userspace can control generation of CRCs in a given CRTC by writing to the
file dri/0/crtc-N/crc/control in debugfs, with N being the index of
the CRTC. Accepted values are source names (which are
driver-specific) and the "auto" keyword, which will let the driver select a
default source of frame CRCs for this CRTC.

Once frame CRC generation is enabled, userspace can capture them by reading
the dri/0/crtc-N/crc/data file. Each line in that file contains the frame
number in the first field and then a number of unsigned integer fields
containing the CRC data. Fields are separated by a single space and the number
of CRC fields is source-specific.

Note that though in some cases the CRC is computed in a specified way and on
the frame contents as supplied by userspace (eDP 1.3), in general the CRC
computation is performed in an unspecified way and on frame contents that have
been already processed in also an unspecified way and thus userspace cannot
rely on being able to generate matching CRC values for the frame contents that
it submits. In this general case, the maximum userspace can do is to compare
the reported CRCs of frames that should have the same contents.

On the driver side the implementation effort is minimal, drivers only need to
implement [`drm_crtc_funcs.set_crc_source`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_crtc_funcs) and [`drm_crtc_funcs.verify_crc_source`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_crtc_funcs).
The debugfs files are automatically set up if those vfuncs are set. CRC samples
need to be captured in the driver by calling [`drm_crtc_add_crc_entry()`](#c-drm_crtc_add_crc_entry).
Depending on the driver and HW requirements, [`drm_crtc_funcs.set_crc_source`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_crtc_funcs)
may result in a commit (even a full modeset).

CRC results must be reliable across non-full-modeset atomic commits, so if a
commit via DRM_IOCTL_MODE_ATOMIC would disable or otherwise interfere with
CRC generation, then the driver must mark that commit as a full modeset
([`drm_atomic_crtc_needs_modeset()`](/kernel/hardware/gpu/drm-kms.md#c-drm_atomic_crtc_needs_modeset) should return true). As a result, to ensure
consistent results, generic userspace must re-setup CRC generation after a
legacy SETCRTC or an atomic commit with DRM_MODE_ATOMIC_ALLOW_MODESET.



#### <a id="c-drm_crtc_add_crc_entry"></a>`drm_crtc_add_crc_entry()`

```c
int drm_crtc_add_crc_entry(struct drm_crtc *crtc, bool has_frame, uint32_t frame, uint32_t *crcs)
```

Add entry with CRC information for a frame

**Parameters**

- `struct drm_crtc *crtc`: CRTC to which the frame belongs
- `bool has_frame`: whether this entry has a frame number to go with
- `uint32_t frame`: number of the frame these CRCs are about
- `uint32_t *crcs`: array of CRC values, with length matching #drm_crtc_crc.values_cnt

**Description**

For each frame, the driver polls the source of CRCs for new data and calls
this function to add them to the buffer from where userspace reads.


<a id="rst-debugfs-support"></a>

### Debugfs Support


#### <a id="c-DRM_DEBUGFS_GPUVA_INFO"></a>`DRM_DEBUGFS_GPUVA_INFO()`

```c
DRM_DEBUGFS_GPUVA_INFO(show, data)
```

[`drm_info_list`](#c-struct-drm_info_list) entry to dump a GPU VA space

**Parameters**

- `show`: the [`drm_info_list`](#c-struct-drm_info_list)'s show callback
- `data`: driver private data

**Description**

Drivers should use this macro to define a [`drm_info_list`](#c-struct-drm_info_list) entry to provide a
debugfs file for dumping the GPU VA space regions and mappings.

For each DRM GPU VA space drivers should call [`drm_debugfs_gpuva_info()`](#c-drm_debugfs_gpuva_info) from
their **show** callback.

#### <a id="c-struct-drm_info_list"></a>`struct drm_info_list`

debugfs info list entry

**Definition**

```c
struct drm_info_list {
    const char *name;
    int (*show)(struct seq_file*, void*);
    u32 driver_features;
    void *data;
};
```

**Members**

- `name`: file name
- `show`: Show callback. `seq_file->private` will be set to the [`struct drm_info_node`](#c-struct-drm_info_node) corresponding to the instance of this info on a given
  [`struct drm_minor`](/kernel/hardware/gpu/drm-internals.md#c-struct-drm_minor).
- `driver_features`: Required driver features for this entry
- `data`: Driver-private data, should not be device-specific.

**Description**

This structure represents a debugfs file to be created by the drm
core.

#### <a id="c-struct-drm_info_node"></a>`struct drm_info_node`

Per-minor debugfs node structure

**Definition**

```c
struct drm_info_node {
    struct drm_minor *minor;
    const struct drm_info_list *info_ent;
};
```

**Members**

- `minor`: [`struct drm_minor`](/kernel/hardware/gpu/drm-internals.md#c-struct-drm_minor) for this node.
- `info_ent`: template for this node.

**Description**

This structure represents a debugfs file, as an instantiation of a [`struct drm_info_list`](#c-struct-drm_info_list) on a [`struct drm_minor`](/kernel/hardware/gpu/drm-internals.md#c-struct-drm_minor).

FIXME:

No it doesn't make a hole lot of sense that we duplicate debugfs entries for
both the render and the primary nodes, but that's how this has organically
grown. It should probably be fixed, with a compatibility link, if needed.

#### <a id="c-struct-drm_debugfs_info"></a>`struct drm_debugfs_info`

debugfs info list entry

**Definition**

```c
struct drm_debugfs_info {
    const char *name;
    int (*show)(struct seq_file*, void*);
    u32 driver_features;
    void *data;
};
```

**Members**

- `name`: File name
- `show`: Show callback. `seq_file->private` will be set to the [`struct drm_debugfs_entry`](#c-struct-drm_debugfs_entry) corresponding to the instance of this info
  on a given [`struct drm_device`](/kernel/hardware/gpu/drm-internals.md#c-struct-drm_device).
- `driver_features`: Required driver features for this entry.
- `data`: Driver-private data, should not be device-specific.

**Description**

This structure represents a debugfs file to be created by the drm
core.

#### <a id="c-struct-drm_debugfs_entry"></a>`struct drm_debugfs_entry`

Per-device debugfs node structure

**Definition**

```c
struct drm_debugfs_entry {
    struct drm_device *dev;
    struct drm_debugfs_info file;
    struct list_head list;
};
```

**Members**

- `dev`: [`struct drm_device`](/kernel/hardware/gpu/drm-internals.md#c-struct-drm_device) for this node.
- `file`: Template for this node.
- `list`: Linked list of all device nodes.

**Description**

This structure represents a debugfs file, as an instantiation of a [`struct drm_debugfs_info`](#c-struct-drm_debugfs_info) on a [`struct drm_device`](/kernel/hardware/gpu/drm-internals.md#c-struct-drm_device).



#### <a id="c-drm_debugfs_gpuva_info"></a>`drm_debugfs_gpuva_info()`

```c
int drm_debugfs_gpuva_info(struct seq_file *m, struct drm_gpuvm *gpuvm)
```

dump the given DRM GPU VA space

**Parameters**

- `struct seq_file *m`: pointer to the `seq_file` to write
- `struct drm_gpuvm *gpuvm`: the [`drm_gpuvm`](/kernel/hardware/gpu/drm-mm.md#c-struct-drm_gpuvm) representing the GPU VA space

**Description**

Dumps the GPU VA mappings of a given DRM GPU VA manager.

For each DRM GPU VA space drivers should call this function from their
[`drm_info_list`](#c-struct-drm_info_list)'s show callback.

**Return**

0 on success, -ENODEV if the `gpuvm` is not initialized

#### <a id="c-drm_debugfs_create_files"></a>`drm_debugfs_create_files()`

```c
void drm_debugfs_create_files(const struct drm_info_list *files, int count, struct dentry *root, struct drm_minor *minor)
```

Initialize a given set of debugfs files for DRM minor

**Parameters**

- `const struct drm_info_list *files`: The array of files to create
- `int count`: The number of files given
- `struct dentry *root`: DRI debugfs dir entry.
- `struct drm_minor *minor`: device minor number

**Description**

Create a given set of debugfs files represented by an array of
[`struct drm_info_list`](#c-struct-drm_info_list) in the given root directory. These files will be removed
automatically on `drm_debugfs_dev_fini()`.

#### <a id="c-drm_debugfs_add_file"></a>`drm_debugfs_add_file()`

```c
void drm_debugfs_add_file(struct drm_device *dev, const char *name, int (*show)(struct seq_file*, void*), void *data)
```

Add a given file to the DRM device debugfs file list

**Parameters**

- `struct drm_device *dev`: drm device for the ioctl
- `const char *name`: debugfs file name
- `int (*show)(struct seq_file*, void*)`: show callback
- `void *data`: driver-private data, should not be device-specific

**Description**

Add a given file entry to the DRM device debugfs file list to be created on
drm_debugfs_init.

#### <a id="c-drm_debugfs_add_files"></a>`drm_debugfs_add_files()`

```c
void drm_debugfs_add_files(struct drm_device *dev, const struct drm_debugfs_info *files, int count)
```

Add an array of files to the DRM device debugfs file list

**Parameters**

- `struct drm_device *dev`: drm device for the ioctl
- `const struct drm_debugfs_info *files`: The array of files to create
- `int count`: The number of files given

**Description**

Add a given set of debugfs files represented by an array of
[`struct drm_debugfs_info`](#c-struct-drm_debugfs_info) in the DRM device debugfs file list.


<a id="rst-sysfs-support"></a>

## Sysfs Support


DRM provides very little additional support to drivers for sysfs
interactions, beyond just all the standard stuff. Drivers who want to expose
additional sysfs properties and property groups can attach them at either
[`drm_device.dev`](/kernel/hardware/gpu/drm-internals.md#c-struct-drm_device) or [`drm_connector.kdev`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_connector).

Registration is automatically handled when calling [`drm_dev_register()`](/kernel/hardware/gpu/drm-internals.md#c-drm_dev_register), or
[`drm_connector_register()`](/kernel/hardware/gpu/drm-kms.md#c-drm_connector_register) in case of hot-plugged connectors. Unregistration is
also automatically handled by [`drm_dev_unregister()`](/kernel/hardware/gpu/drm-internals.md#c-drm_dev_unregister) and
[`drm_connector_unregister()`](/kernel/hardware/gpu/drm-kms.md#c-drm_connector_unregister).



#### <a id="c-drm_sysfs_hotplug_event"></a>`drm_sysfs_hotplug_event()`

```c
void drm_sysfs_hotplug_event(struct drm_device *dev)
```

generate a DRM uevent

**Parameters**

- `struct drm_device *dev`: DRM device

**Description**

Send a uevent for the DRM device specified by **dev**.  Currently we only
set HOTPLUG=1 in the uevent environment, but this could be expanded to
deal with other types of events.

Any new uapi should be using the `drm_sysfs_connector_status_event()`
for uevents on connector status change.

#### <a id="c-drm_sysfs_connector_hotplug_event"></a>`drm_sysfs_connector_hotplug_event()`

```c
void drm_sysfs_connector_hotplug_event(struct drm_connector *connector)
```

generate a DRM uevent for any connector change

**Parameters**

- `struct drm_connector *connector`: connector which has changed

**Description**

Send a uevent for the DRM connector specified by **connector**. This will send
a uevent with the properties HOTPLUG=1 and CONNECTOR.

#### <a id="c-drm_sysfs_connector_property_event"></a>`drm_sysfs_connector_property_event()`

```c
void drm_sysfs_connector_property_event(struct drm_connector *connector, struct drm_property *property)
```

generate a DRM uevent for connector property change

**Parameters**

- `struct drm_connector *connector`: connector on which property changed
- `struct drm_property *property`: connector property which has changed.

**Description**

Send a uevent for the specified DRM connector and property.  Currently we
set HOTPLUG=1 and connector id along with the attached property id
related to the change.

#### <a id="c-drm_class_device_register"></a>`drm_class_device_register()`

```c
int drm_class_device_register(struct device *dev)
```

register new device with the DRM sysfs class

**Parameters**

- `struct device *dev`: device to register

**Description**

Registers a new [`struct device`](/kernel/hardware/driver-api/fundamentals/infrastructure.md#c-struct-device) within the DRM sysfs class. Essentially only
used by ttm to have a place for its global settings. Drivers should never use
this.

#### <a id="c-drm_class_device_unregister"></a>`drm_class_device_unregister()`

```c
void drm_class_device_unregister(struct device *dev)
```

unregister device with the DRM sysfs class

**Parameters**

- `struct device *dev`: device to unregister

**Description**

Unregisters a [`struct device`](/kernel/hardware/driver-api/fundamentals/infrastructure.md#c-struct-device) from the DRM sysfs class. Essentially only used
by ttm to have a place for its global settings. Drivers should never use
this.


<a id="rst-vblank-event-handling"></a>

## VBlank event handling

The DRM core exposes two vertical blank related ioctls:

- **`DRM_IOCTL_WAIT_VBLANK`**

  This takes a struct drm_wait_vblank structure as its argument, and it is used to block or request a signal when a specified vblank event occurs.

- **`DRM_IOCTL_MODESET_CTL`**

  This was only used for user-mode-settind drivers around modesetting changes to allow the kernel to update the vblank interrupt after mode setting, since on many devices the vertical blank counter is reset to 0 at some point during modeset. Modern drivers should not call this any more since with kernel mode setting it is a no-op.

<a id="rst-userspace-api-structures"></a>

## Userspace API Structures


DRM exposes many UAPI and structure definitions to have a consistent
and standardized interface with users.
Userspace can refer to these structure definitions and UAPI formats
to communicate to drivers.


<a id="rst-crtc-index-1"></a>
<a id="rst-crtc-index"></a>

### CRTC index

CRTC's have both an object ID and an index, and they are not the same thing. The index is used in cases where a densely packed identifier for a CRTC is needed, for instance a bitmask of CRTC's. The member possible_crtcs of struct drm_mode_get_plane is an example.

`DRM_IOCTL_MODE_GETRESOURCES` populates a structure with an array of CRTC ID's, and the CRTC index is its position in this array.


#### <a id="c-struct-drm_gem_close"></a>`struct drm_gem_close`

Argument for [`DRM_IOCTL_GEM_CLOSE`](#c-DRM_IOCTL_GEM_CLOSE) ioctl.

**Definition**

```c
struct drm_gem_close {
    __u32 handle;
    __u32 pad;
};
```

**Members**

- `handle`: Handle of the object to be closed.
- `pad`: Padding.

**Description**

Releases the handle to an mm object.

#### <a id="c-struct-drm_gem_flink"></a>`struct drm_gem_flink`

Argument for `DRM_IOCTL_GEM_FLINK` ioctl.

**Definition**

```c
struct drm_gem_flink {
    __u32 handle;
    __u32 name;
};
```

**Members**

- `handle`: Handle for the object being named.
- `name`: Returned global name.

**Description**

Create a global name for an object, returning the name.

Note that the name does not hold a reference; when the object
is freed, the name goes away.

#### <a id="c-struct-drm_gem_open"></a>`struct drm_gem_open`

Argument for `DRM_IOCTL_GEM_OPEN` ioctl.

**Definition**

```c
struct drm_gem_open {
    __u32 name;
    __u32 handle;
    __u64 size;
};
```

**Members**

- `name`: Name of object being opened.
- `handle`: Returned handle for the object.
- `size`: Returned size of the object

**Description**

Open an object using the global name, returning a handle and the size.

This handle (of course) holds a reference to the object, so the object
will not go away until the handle is deleted.

#### <a id="c-struct-drm_gem_change_handle"></a>`struct drm_gem_change_handle`

Argument for [`DRM_IOCTL_GEM_CHANGE_HANDLE`](#c-DRM_IOCTL_GEM_CHANGE_HANDLE) ioctl.

**Definition**

```c
struct drm_gem_change_handle {
    __u32 handle;
    __u32 new_handle;
};
```

**Members**

- `handle`: The handle of a gem object.
- `new_handle`: An available gem handle.

**Description**

This ioctl changes the handle of a GEM object to the specified one.
The new handle must be unused. On success the old handle is closed
and all further IOCTL should refer to the new handle only.
Calls to DRM_IOCTL_PRIME_FD_TO_HANDLE will return the new handle.

#### <a id="c-DRM_CAP_DUMB_BUFFER"></a>`DRM_CAP_DUMB_BUFFER`

```c
DRM_CAP_DUMB_BUFFER
```

**Description**

If set to 1, the driver supports creating dumb buffers via the
[`DRM_IOCTL_MODE_CREATE_DUMB`](#c-DRM_IOCTL_MODE_CREATE_DUMB) ioctl.

#### <a id="c-DRM_CAP_VBLANK_HIGH_CRTC"></a>`DRM_CAP_VBLANK_HIGH_CRTC`

```c
DRM_CAP_VBLANK_HIGH_CRTC
```

**Description**

If set to 1, the kernel supports specifying a CRTC index
in the high bits of `drm_wait_vblank_request.type`.

Starting kernel version 2.6.39, this capability is always set to 1.

#### <a id="c-DRM_CAP_DUMB_PREFERRED_DEPTH"></a>`DRM_CAP_DUMB_PREFERRED_DEPTH`

```c
DRM_CAP_DUMB_PREFERRED_DEPTH
```

**Description**

The preferred bit depth for dumb buffers.

The bit depth is the number of bits used to indicate the color of a single
pixel excluding any padding. This is different from the number of bits per
pixel. For instance, XRGB8888 has a bit depth of 24 but has 32 bits per
pixel.

Note that this preference only applies to dumb buffers, it's irrelevant for
other types of buffers.

#### <a id="c-DRM_CAP_DUMB_PREFER_SHADOW"></a>`DRM_CAP_DUMB_PREFER_SHADOW`

```c
DRM_CAP_DUMB_PREFER_SHADOW
```

**Description**

If set to 1, the driver prefers userspace to render to a shadow buffer
instead of directly rendering to a dumb buffer. For best speed, userspace
should do streaming ordered memory copies into the dumb buffer and never
read from it.

Note that this preference only applies to dumb buffers, it's irrelevant for
other types of buffers.

#### <a id="c-DRM_CAP_PRIME"></a>`DRM_CAP_PRIME`

```c
DRM_CAP_PRIME
```

**Description**

Bitfield of supported PRIME sharing capabilities. See [`DRM_PRIME_CAP_IMPORT`](#c-DRM_PRIME_CAP_IMPORT)
and [`DRM_PRIME_CAP_EXPORT`](#c-DRM_PRIME_CAP_EXPORT).

Starting from kernel version 6.6, both [`DRM_PRIME_CAP_IMPORT`](#c-DRM_PRIME_CAP_IMPORT) and
[`DRM_PRIME_CAP_EXPORT`](#c-DRM_PRIME_CAP_EXPORT) are always advertised.

PRIME buffers are exposed as dma-buf file descriptors.
See prime_buffer_sharing.

#### <a id="c-DRM_PRIME_CAP_IMPORT"></a>`DRM_PRIME_CAP_IMPORT`

```c
DRM_PRIME_CAP_IMPORT
```

**Description**

If this bit is set in [`DRM_CAP_PRIME`](#c-DRM_CAP_PRIME), the driver supports importing PRIME
buffers via the [`DRM_IOCTL_PRIME_FD_TO_HANDLE`](#c-DRM_IOCTL_PRIME_FD_TO_HANDLE) ioctl.

Starting from kernel version 6.6, this bit is always set in [`DRM_CAP_PRIME`](#c-DRM_CAP_PRIME).

#### <a id="c-DRM_PRIME_CAP_EXPORT"></a>`DRM_PRIME_CAP_EXPORT`

```c
DRM_PRIME_CAP_EXPORT
```

**Description**

If this bit is set in [`DRM_CAP_PRIME`](#c-DRM_CAP_PRIME), the driver supports exporting PRIME
buffers via the [`DRM_IOCTL_PRIME_HANDLE_TO_FD`](#c-DRM_IOCTL_PRIME_HANDLE_TO_FD) ioctl.

Starting from kernel version 6.6, this bit is always set in [`DRM_CAP_PRIME`](#c-DRM_CAP_PRIME).

#### <a id="c-DRM_CAP_TIMESTAMP_MONOTONIC"></a>`DRM_CAP_TIMESTAMP_MONOTONIC`

```c
DRM_CAP_TIMESTAMP_MONOTONIC
```

**Description**

If set to 0, the kernel will report timestamps with `CLOCK_REALTIME` in
struct drm_event_vblank. If set to 1, the kernel will report timestamps with
`CLOCK_MONOTONIC`. See `clock_gettime(2)` for the definition of these
clocks.

Starting from kernel version 2.6.39, the default value for this capability
is 1. Starting kernel version 4.15, this capability is always set to 1.

#### <a id="c-DRM_CAP_ASYNC_PAGE_FLIP"></a>`DRM_CAP_ASYNC_PAGE_FLIP`

```c
DRM_CAP_ASYNC_PAGE_FLIP
```

**Description**

If set to 1, the driver supports [`DRM_MODE_PAGE_FLIP_ASYNC`](#c-DRM_MODE_PAGE_FLIP_ASYNC) for legacy
page-flips.

#### <a id="c-DRM_CAP_CURSOR_WIDTH"></a>`DRM_CAP_CURSOR_WIDTH`

```c
DRM_CAP_CURSOR_WIDTH
```

**Description**

The `CURSOR_WIDTH` and `CURSOR_HEIGHT` capabilities return a valid
width x height combination for the hardware cursor. The intention is that a
hardware agnostic userspace can query a cursor plane size to use.

Note that the cross-driver contract is to merely return a valid size;
drivers are free to attach another meaning on top, eg. i915 returns the
maximum plane size.

#### <a id="c-DRM_CAP_CURSOR_HEIGHT"></a>`DRM_CAP_CURSOR_HEIGHT`

```c
DRM_CAP_CURSOR_HEIGHT
```

**Description**

See [`DRM_CAP_CURSOR_WIDTH`](#c-DRM_CAP_CURSOR_WIDTH).

#### <a id="c-DRM_CAP_ADDFB2_MODIFIERS"></a>`DRM_CAP_ADDFB2_MODIFIERS`

```c
DRM_CAP_ADDFB2_MODIFIERS
```

**Description**

If set to 1, the driver supports supplying modifiers in the
`DRM_IOCTL_MODE_ADDFB2` ioctl.

#### <a id="c-DRM_CAP_PAGE_FLIP_TARGET"></a>`DRM_CAP_PAGE_FLIP_TARGET`

```c
DRM_CAP_PAGE_FLIP_TARGET
```

**Description**

If set to 1, the driver supports the `DRM_MODE_PAGE_FLIP_TARGET_ABSOLUTE` and
`DRM_MODE_PAGE_FLIP_TARGET_RELATIVE` flags in
`drm_mode_crtc_page_flip_target.flags` for the `DRM_IOCTL_MODE_PAGE_FLIP`
ioctl.

#### <a id="c-DRM_CAP_CRTC_IN_VBLANK_EVENT"></a>`DRM_CAP_CRTC_IN_VBLANK_EVENT`

```c
DRM_CAP_CRTC_IN_VBLANK_EVENT
```

**Description**

If set to 1, the kernel supports reporting the CRTC ID in
`drm_event_vblank.crtc_id` for the [`DRM_EVENT_VBLANK`](#c-DRM_EVENT_VBLANK) and
[`DRM_EVENT_FLIP_COMPLETE`](#c-DRM_EVENT_FLIP_COMPLETE) events.

Starting kernel version 4.12, this capability is always set to 1.

#### <a id="c-DRM_CAP_SYNCOBJ"></a>`DRM_CAP_SYNCOBJ`

```c
DRM_CAP_SYNCOBJ
```

**Description**

If set to 1, the driver supports sync objects. See drm_sync_objects.

#### <a id="c-DRM_CAP_SYNCOBJ_TIMELINE"></a>`DRM_CAP_SYNCOBJ_TIMELINE`

```c
DRM_CAP_SYNCOBJ_TIMELINE
```

**Description**

If set to 1, the driver supports timeline operations on sync objects. See
drm_sync_objects.

#### <a id="c-DRM_CAP_ATOMIC_ASYNC_PAGE_FLIP"></a>`DRM_CAP_ATOMIC_ASYNC_PAGE_FLIP`

```c
DRM_CAP_ATOMIC_ASYNC_PAGE_FLIP
```

**Description**

If set to 1, the driver supports [`DRM_MODE_PAGE_FLIP_ASYNC`](#c-DRM_MODE_PAGE_FLIP_ASYNC) for atomic
commits.

#### <a id="c-DRM_CLIENT_CAP_STEREO_3D"></a>`DRM_CLIENT_CAP_STEREO_3D`

```c
DRM_CLIENT_CAP_STEREO_3D
```

**Description**

If set to 1, the DRM core will expose the stereo 3D capabilities of the
monitor by advertising the supported 3D layouts in the flags of struct
drm_mode_modeinfo. See `DRM_MODE_FLAG_3D_*`.

This capability is always supported for all drivers starting from kernel
version 3.13.

#### <a id="c-DRM_CLIENT_CAP_UNIVERSAL_PLANES"></a>`DRM_CLIENT_CAP_UNIVERSAL_PLANES`

```c
DRM_CLIENT_CAP_UNIVERSAL_PLANES
```

**Description**

If set to 1, the DRM core will expose all planes (overlay, primary, and
cursor) to userspace.

This capability has been introduced in kernel version 3.15. Starting from
kernel version 3.17, this capability is always supported for all drivers.

#### <a id="c-DRM_CLIENT_CAP_ATOMIC"></a>`DRM_CLIENT_CAP_ATOMIC`

```c
DRM_CLIENT_CAP_ATOMIC
```

**Description**

If set to 1, the DRM core will expose atomic properties to userspace. This
implicitly enables [`DRM_CLIENT_CAP_UNIVERSAL_PLANES`](#c-DRM_CLIENT_CAP_UNIVERSAL_PLANES) and
[`DRM_CLIENT_CAP_ASPECT_RATIO`](#c-DRM_CLIENT_CAP_ASPECT_RATIO).

If the driver doesn't support atomic mode-setting, enabling this capability
will fail with -EOPNOTSUPP.

This capability has been introduced in kernel version 4.0. Starting from
kernel version 4.2, this capability is always supported for atomic-capable
drivers.

#### <a id="c-DRM_CLIENT_CAP_ASPECT_RATIO"></a>`DRM_CLIENT_CAP_ASPECT_RATIO`

```c
DRM_CLIENT_CAP_ASPECT_RATIO
```

**Description**

If set to 1, the DRM core will provide aspect ratio information in modes.
See `DRM_MODE_FLAG_PIC_AR_*`.

This capability is always supported for all drivers starting from kernel
version 4.18.

#### <a id="c-DRM_CLIENT_CAP_WRITEBACK_CONNECTORS"></a>`DRM_CLIENT_CAP_WRITEBACK_CONNECTORS`

```c
DRM_CLIENT_CAP_WRITEBACK_CONNECTORS
```

**Description**

If set to 1, the DRM core will expose special connectors to be used for
writing back to memory the scene setup in the commit. The client must enable
[`DRM_CLIENT_CAP_ATOMIC`](#c-DRM_CLIENT_CAP_ATOMIC) first.

This capability is always supported for atomic-capable drivers starting from
kernel version 4.19.

#### <a id="c-DRM_CLIENT_CAP_CURSOR_PLANE_HOTSPOT"></a>`DRM_CLIENT_CAP_CURSOR_PLANE_HOTSPOT`

```c
DRM_CLIENT_CAP_CURSOR_PLANE_HOTSPOT
```

**Description**

Drivers for para-virtualized hardware (e.g. vmwgfx, qxl, virtio and
virtualbox) have additional restrictions for cursor planes (thus
making cursor planes on those drivers not truly universal,) e.g.
they need cursor planes to act like one would expect from a mouse
cursor and have correctly set hotspot properties.
If this client cap is not set the DRM core will hide cursor plane on
those virtualized drivers because not setting it implies that the
client is not capable of dealing with those extra restictions.
Clients which do set cursor hotspot and treat the cursor plane
like a mouse cursor should set this property.
The client must enable [`DRM_CLIENT_CAP_ATOMIC`](#c-DRM_CLIENT_CAP_ATOMIC) first.

Setting this property on drivers which do not special case
cursor planes (i.e. non-virtualized drivers) will return
EOPNOTSUPP, which can be used by userspace to gauge
requirements of the hardware/drivers they're running on.

This capability is always supported for atomic-capable virtualized
drivers starting from kernel version 6.6.

#### <a id="c-DRM_CLIENT_CAP_PLANE_COLOR_PIPELINE"></a>`DRM_CLIENT_CAP_PLANE_COLOR_PIPELINE`

```c
DRM_CLIENT_CAP_PLANE_COLOR_PIPELINE
```

**Description**

If set to 1 the DRM core will allow setting the COLOR_PIPELINE
property on a [`drm_plane`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_plane), as well as drm_colorop properties.

Setting of these plane properties will be rejected when this client
cap is set:
- COLOR_ENCODING
- COLOR_RANGE

The client must enable [`DRM_CLIENT_CAP_ATOMIC`](#c-DRM_CLIENT_CAP_ATOMIC) first.

#### <a id="c-struct-drm_syncobj_eventfd"></a>`struct drm_syncobj_eventfd`

**Definition**

```c
struct drm_syncobj_eventfd {
    __u32 handle;
    __u32 flags;
    __u64 point;
    __s32 fd;
    __u32 pad;
};
```

**Members**

- `handle`: syncobj handle.
- `flags`: Zero to wait for the point to be signalled, or
  `DRM_SYNCOBJ_WAIT_FLAGS_WAIT_AVAILABLE` to wait for a fence to be
  available for the point.
- `point`: syncobj timeline point (set to zero for binary syncobjs).
- `fd`: Existing eventfd to sent events to.
- `pad`: Must be zero.

**Description**

Register an eventfd to be signalled by a syncobj. The eventfd counter will
be incremented by one.

#### <a id="c-DRM_IOCTL_GEM_CLOSE"></a>`DRM_IOCTL_GEM_CLOSE`

```c
DRM_IOCTL_GEM_CLOSE
```

Close a GEM handle.

**Description**

GEM handles are not reference-counted by the kernel. User-space is
responsible for managing their lifetime. For example, if user-space imports
the same memory object twice on the same DRM file description, the same GEM
handle is returned by both imports, and user-space needs to ensure
[`DRM_IOCTL_GEM_CLOSE`](#c-DRM_IOCTL_GEM_CLOSE) is performed once only. The same situation can happen
when a memory object is allocated, then exported and imported again on the
same DRM file description. The [`DRM_IOCTL_MODE_GETFB2`](#c-DRM_IOCTL_MODE_GETFB2) IOCTL is an exception
and always returns fresh new GEM handles even if an existing GEM handle
already refers to the same memory object before the IOCTL is performed.

#### <a id="c-DRM_IOCTL_PRIME_HANDLE_TO_FD"></a>`DRM_IOCTL_PRIME_HANDLE_TO_FD`

```c
DRM_IOCTL_PRIME_HANDLE_TO_FD
```

Convert a GEM handle to a DMA-BUF FD.

**Description**

User-space sets `drm_prime_handle.handle` with the GEM handle to export and
`drm_prime_handle.flags`, and gets back a DMA-BUF file descriptor in
`drm_prime_handle.fd`.

The export can fail for any driver-specific reason, e.g. because export is
not supported for this specific GEM handle (but might be for others).

Support for exporting DMA-BUFs is advertised via [`DRM_PRIME_CAP_EXPORT`](#c-DRM_PRIME_CAP_EXPORT).

#### <a id="c-DRM_IOCTL_PRIME_FD_TO_HANDLE"></a>`DRM_IOCTL_PRIME_FD_TO_HANDLE`

```c
DRM_IOCTL_PRIME_FD_TO_HANDLE
```

Convert a DMA-BUF FD to a GEM handle.

**Description**

User-space sets `drm_prime_handle.fd` with a DMA-BUF file descriptor to
import, and gets back a GEM handle in `drm_prime_handle.handle`.
`drm_prime_handle.flags` is unused.

If an existing GEM handle refers to the memory object backing the DMA-BUF,
that GEM handle is returned. Therefore user-space which needs to handle
arbitrary DMA-BUFs must have a user-space lookup data structure to manually
reference-count duplicated GEM handles. For more information see
[`DRM_IOCTL_GEM_CLOSE`](#c-DRM_IOCTL_GEM_CLOSE).

The import can fail for any driver-specific reason, e.g. because import is
only supported for DMA-BUFs allocated on this DRM device.

Support for importing DMA-BUFs is advertised via [`DRM_PRIME_CAP_IMPORT`](#c-DRM_PRIME_CAP_IMPORT).

#### <a id="c-DRM_IOCTL_MODE_RMFB"></a>`DRM_IOCTL_MODE_RMFB`

```c
DRM_IOCTL_MODE_RMFB
```

Remove a framebuffer.

**Description**

This removes a framebuffer previously added via ADDFB/ADDFB2. The IOCTL
argument is a framebuffer object ID.

Warning: removing a framebuffer currently in-use on an enabled plane will
disable that plane. The CRTC the plane is linked to may also be disabled
(depending on driver capabilities).

#### <a id="c-DRM_IOCTL_MODE_CREATE_DUMB"></a>`DRM_IOCTL_MODE_CREATE_DUMB`

```c
DRM_IOCTL_MODE_CREATE_DUMB
```

Create a new dumb buffer object.

**Description**

KMS dumb buffers provide a very primitive way to allocate a buffer object
suitable for scanout and map it for software rendering. KMS dumb buffers are
not suitable for hardware-accelerated rendering nor video decoding. KMS dumb
buffers are not suitable to be displayed on any other device than the KMS
device where they were allocated from. Also see
kms_dumb_buffer_objects.

The IOCTL argument is a struct drm_mode_create_dumb.

User-space is expected to create a KMS dumb buffer via this IOCTL, then add
it as a KMS framebuffer via `DRM_IOCTL_MODE_ADDFB` and map it via
`DRM_IOCTL_MODE_MAP_DUMB`.

[`DRM_CAP_DUMB_BUFFER`](#c-DRM_CAP_DUMB_BUFFER) indicates whether this IOCTL is supported.
[`DRM_CAP_DUMB_PREFERRED_DEPTH`](#c-DRM_CAP_DUMB_PREFERRED_DEPTH) and [`DRM_CAP_DUMB_PREFER_SHADOW`](#c-DRM_CAP_DUMB_PREFER_SHADOW) indicate
driver preferences for dumb buffers.

#### <a id="c-DRM_IOCTL_MODE_GETFB2"></a>`DRM_IOCTL_MODE_GETFB2`

```c
DRM_IOCTL_MODE_GETFB2
```

Get framebuffer metadata.

**Description**

This queries metadata about a framebuffer. User-space fills
[`drm_mode_fb_cmd2.fb_id`](#c-struct-drm_mode_fb_cmd2) as the input, and the kernels fills the rest of the
struct as the output.

If the client is DRM master or has `CAP_SYS_ADMIN`, [`drm_mode_fb_cmd2.handles`](#c-struct-drm_mode_fb_cmd2)
will be filled with GEM buffer handles. Fresh new GEM handles are always
returned, even if another GEM handle referring to the same memory object
already exists on the DRM file description. The caller is responsible for
removing the new handles, e.g. via the [`DRM_IOCTL_GEM_CLOSE`](#c-DRM_IOCTL_GEM_CLOSE) IOCTL. The same
new handle will be returned for multiple planes in case they use the same
memory object. Planes are valid until one has a zero handle -- this can be
used to compute the number of planes.

Otherwise, [`drm_mode_fb_cmd2.handles`](#c-struct-drm_mode_fb_cmd2) will be zeroed and planes are valid
until one has a zero [`drm_mode_fb_cmd2.pitches`](#c-struct-drm_mode_fb_cmd2).

If the framebuffer has a format modifier, `DRM_MODE_FB_MODIFIERS` will be set
in [`drm_mode_fb_cmd2.flags`](#c-struct-drm_mode_fb_cmd2) and [`drm_mode_fb_cmd2.modifier`](#c-struct-drm_mode_fb_cmd2) will contain the
modifier. Otherwise, user-space must ignore [`drm_mode_fb_cmd2.modifier`](#c-struct-drm_mode_fb_cmd2).

To obtain DMA-BUF FDs for each plane without leaking GEM handles, user-space
can export each handle via [`DRM_IOCTL_PRIME_HANDLE_TO_FD`](#c-DRM_IOCTL_PRIME_HANDLE_TO_FD), then immediately
close each unique handle via [`DRM_IOCTL_GEM_CLOSE`](#c-DRM_IOCTL_GEM_CLOSE), making sure to not
double-close handles which are specified multiple times in the array.

#### <a id="c-DRM_IOCTL_MODE_CLOSEFB"></a>`DRM_IOCTL_MODE_CLOSEFB`

```c
DRM_IOCTL_MODE_CLOSEFB
```

Close a framebuffer.

**Description**

This closes a framebuffer previously added via ADDFB/ADDFB2. The IOCTL
argument is a framebuffer object ID.

This IOCTL is similar to [`DRM_IOCTL_MODE_RMFB`](#c-DRM_IOCTL_MODE_RMFB), except it doesn't disable
planes and CRTCs. As long as the framebuffer is used by a plane, it's kept
alive. When the plane no longer uses the framebuffer (because the
framebuffer is replaced with another one, or the plane is disabled), the
framebuffer is cleaned up.

This is useful to implement flicker-free transitions between two processes.

Depending on the threat model, user-space may want to ensure that the
framebuffer doesn't expose any sensitive user information: closed
framebuffers attached to a plane can be read back by the next DRM master.

#### <a id="c-DRM_IOCTL_SET_CLIENT_NAME"></a>`DRM_IOCTL_SET_CLIENT_NAME`

```c
DRM_IOCTL_SET_CLIENT_NAME
```

Attach a name to a drm_file

**Description**

Having a name allows for easier tracking and debugging.
The length of the name (without null ending char) must be
\<= DRM_CLIENT_NAME_MAX_LEN.
The call will fail if the name contains whitespaces or non-printable chars.

#### <a id="c-DRM_IOCTL_GEM_CHANGE_HANDLE"></a>`DRM_IOCTL_GEM_CHANGE_HANDLE`

```c
DRM_IOCTL_GEM_CHANGE_HANDLE
```

Move an object to a different handle

**Description**

Some applications (notably CRIU) need objects to have specific gem handles.
This ioctl changes the object at one gem handle to use a new gem handle.

#### <a id="c-struct-drm_event"></a>`struct drm_event`

Header for DRM events

**Definition**

```c
struct drm_event {
    __u32 type;
    __u32 length;
};
```

**Members**

- `type`: event type.
- `length`: total number of payload bytes (including header).

**Description**

This struct is a header for events written back to user-space on the DRM FD.
A read on the DRM FD will always only return complete events: e.g. if the
read buffer is 100 bytes large and there are two 64 byte events pending,
only one will be returned.

Event types 0 - 0x7fffffff are generic DRM events, 0x80000000 and
up are chipset specific. Generic DRM events include [`DRM_EVENT_VBLANK`](#c-DRM_EVENT_VBLANK),
[`DRM_EVENT_FLIP_COMPLETE`](#c-DRM_EVENT_FLIP_COMPLETE) and [`DRM_EVENT_CRTC_SEQUENCE`](#c-DRM_EVENT_CRTC_SEQUENCE).

#### <a id="c-DRM_EVENT_VBLANK"></a>`DRM_EVENT_VBLANK`

```c
DRM_EVENT_VBLANK
```

vertical blanking event

**Description**

This event is sent in response to `DRM_IOCTL_WAIT_VBLANK` with the
`_DRM_VBLANK_EVENT` flag set.

The event payload is a struct drm_event_vblank.

#### <a id="c-DRM_EVENT_FLIP_COMPLETE"></a>`DRM_EVENT_FLIP_COMPLETE`

```c
DRM_EVENT_FLIP_COMPLETE
```

page-flip completion event

**Description**

This event is sent in response to an atomic commit or legacy page-flip with
the [`DRM_MODE_PAGE_FLIP_EVENT`](#c-DRM_MODE_PAGE_FLIP_EVENT) flag set.

The event payload is a struct drm_event_vblank.

#### <a id="c-DRM_EVENT_CRTC_SEQUENCE"></a>`DRM_EVENT_CRTC_SEQUENCE`

```c
DRM_EVENT_CRTC_SEQUENCE
```

CRTC sequence event

**Description**

This event is sent in response to `DRM_IOCTL_CRTC_QUEUE_SEQUENCE`.

The event payload is a struct drm_event_crtc_sequence.



#### <a id="c-struct-drm_mode_modeinfo"></a>`struct drm_mode_modeinfo`

Display mode information.

**Definition**

```c
struct drm_mode_modeinfo {
    __u32 clock;
    __u16 hdisplay;
    __u16 hsync_start;
    __u16 hsync_end;
    __u16 htotal;
    __u16 hskew;
    __u16 vdisplay;
    __u16 vsync_start;
    __u16 vsync_end;
    __u16 vtotal;
    __u16 vscan;
    __u32 vrefresh;
    __u32 flags;
    __u32 type;
    char name[DRM_DISPLAY_MODE_LEN];
};
```

**Members**

- `clock`: pixel clock in kHz
- `hdisplay`: horizontal display size
- `hsync_start`: horizontal sync start
- `hsync_end`: horizontal sync end
- `htotal`: horizontal total size
- `hskew`: horizontal skew
- `vdisplay`: vertical display size
- `vsync_start`: vertical sync start
- `vsync_end`: vertical sync end
- `vtotal`: vertical total size
- `vscan`: vertical scan
- `vrefresh`: approximate vertical refresh rate in Hz
- `flags`: bitmask of misc. flags, see DRM_MODE_FLAG_* defines
- `type`: bitmask of type flags, see DRM_MODE_TYPE_* defines
- `name`: string describing the mode resolution

**Description**

This is the user-space API display mode information structure. For the
kernel version see struct drm_display_mode.

#### <a id="c-struct-drm_mode_get_plane"></a>`struct drm_mode_get_plane`

Get plane metadata.

**Definition**

```c
struct drm_mode_get_plane {
    __u32 plane_id;
    __u32 crtc_id;
    __u32 fb_id;
    __u32 possible_crtcs;
    __u32 gamma_size;
    __u32 count_format_types;
    __u64 format_type_ptr;
};
```

**Members**

- `plane_id`: Object ID of the plane whose information should be
  retrieved. Set by caller.
- `crtc_id`: Object ID of the current CRTC.
- `fb_id`: Object ID of the current fb.
- `possible_crtcs`: Bitmask of CRTC's compatible with the plane. CRTC's
  are created and they receive an index, which corresponds to their
  position in the bitmask. Bit N corresponds to
  CRTC index N.
- `gamma_size`: Never used.
- `count_format_types`: Number of formats.
- `format_type_ptr`: Pointer to `__u32` array of formats that are
  supported by the plane. These formats do not require modifiers.

**Description**

Userspace can perform a GETPLANE ioctl to retrieve information about a
plane.

To retrieve the number of formats supported, set **count_format_types** to zero
and call the ioctl. **count_format_types** will be updated with the value.

To retrieve these formats, allocate an array with the memory needed to store
**count_format_types** formats. Point **format_type_ptr** to this array and call
the ioctl again (with **count_format_types** still set to the value returned in
the first ioctl call).

#### <a id="c-struct-drm_mode_get_connector"></a>`struct drm_mode_get_connector`

Get connector metadata.

**Definition**

```c
struct drm_mode_get_connector {
    __u64 encoders_ptr;
    __u64 modes_ptr;
    __u64 props_ptr;
    __u64 prop_values_ptr;
    __u32 count_modes;
    __u32 count_props;
    __u32 count_encoders;
    __u32 encoder_id;
    __u32 connector_id;
    __u32 connector_type;
    __u32 connector_type_id;
    __u32 connection;
    __u32 mm_width;
    __u32 mm_height;
    __u32 subpixel;
    __u32 pad;
};
```

**Members**

- `encoders_ptr`: Pointer to `__u32` array of object IDs.
- `modes_ptr`: Pointer to struct drm_mode_modeinfo array.
- `props_ptr`: Pointer to `__u32` array of property IDs.
- `prop_values_ptr`: Pointer to `__u64` array of property values.
- `count_modes`: Number of modes.
- `count_props`: Number of properties.
- `count_encoders`: Number of encoders.
- `encoder_id`: Object ID of the current encoder.
- `connector_id`: Object ID of the connector.
- `connector_type`: Type of the connector.

  See DRM_MODE_CONNECTOR_* defines.
- `connector_type_id`: Type-specific connector number.

  This is not an object ID. This is a per-type connector number. Each
  (type, type_id) combination is unique across all connectors of a DRM
  device.

  The (type, type_id) combination is not a stable identifier: the
  type_id can change depending on the driver probe order.
- `connection`: Status of the connector.

  See enum drm_connector_status.
- `mm_width`: Width of the connected sink in millimeters.
- `mm_height`: Height of the connected sink in millimeters.
- `subpixel`: Subpixel order of the connected sink.

  See enum subpixel_order.
- `pad`: Padding, must be zero.

**Description**

User-space can perform a GETCONNECTOR ioctl to retrieve information about a
connector. User-space is expected to retrieve encoders, modes and properties
by performing this ioctl at least twice: the first time to retrieve the
number of elements, the second time to retrieve the elements themselves.

To retrieve the number of elements, set **count_props** and **count_encoders** to
zero, set **count_modes** to 1, and set **modes_ptr** to a temporary struct
drm_mode_modeinfo element.

To retrieve the elements, allocate arrays for **encoders_ptr**, **modes_ptr**,
**props_ptr** and **prop_values_ptr**, then set **count_modes**, **count_props** and
**count_encoders** to their capacity.

Performing the ioctl only twice may be racy: the number of elements may have
changed with a hotplug event in-between the two ioctls. User-space is
expected to retry the last ioctl until the number of elements stabilizes.
The kernel won't fill any array which doesn't have the expected length.

**Force-probing a connector**

If the **count_modes** field is set to zero and the DRM client is the current
DRM master, the kernel will perform a forced probe on the connector to
refresh the connector status, modes and EDID. A forced-probe can be slow,
might cause flickering and the ioctl will block.

User-space needs to force-probe connectors to ensure their metadata is
up-to-date at startup and after receiving a hot-plug event. User-space
may perform a forced-probe when the user explicitly requests it. User-space
shouldn't perform a forced-probe in other situations.

#### <a id="c-struct-drm_mode_property_enum"></a>`struct drm_mode_property_enum`

Description for an enum/bitfield entry.

**Definition**

```c
struct drm_mode_property_enum {
    __u64 value;
    char name[DRM_PROP_NAME_LEN];
};
```

**Members**

- `value`: numeric value for this enum entry.
- `name`: symbolic name for this enum entry.

**Description**

See struct drm_property_enum for details.

#### <a id="c-struct-drm_mode_get_property"></a>`struct drm_mode_get_property`

Get property metadata.

**Definition**

```c
struct drm_mode_get_property {
    __u64 values_ptr;
    __u64 enum_blob_ptr;
    __u32 prop_id;
    __u32 flags;
    char name[DRM_PROP_NAME_LEN];
    __u32 count_values;
    __u32 count_enum_blobs;
};
```

**Members**

- `values_ptr`: Pointer to a `__u64` array.
- `enum_blob_ptr`: Pointer to a struct drm_mode_property_enum array.
- `prop_id`: Object ID of the property which should be retrieved. Set
  by the caller.
- `flags`: `DRM_MODE_PROP_*` bitfield. See [`drm_property.flags`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_property) for
  a definition of the flags.
- `name`: Symbolic property name. User-space should use this field to
  recognize properties.
- `count_values`: Number of elements in **values_ptr**.
- `count_enum_blobs`: Number of elements in **enum_blob_ptr**.

**Description**

User-space can perform a GETPROPERTY ioctl to retrieve information about a
property. The same property may be attached to multiple objects, see
"Modeset Base Object Abstraction".

The meaning of the **values_ptr** field changes depending on the property type.
See [`drm_property.flags`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_property) for more details.

The **enum_blob_ptr** and **count_enum_blobs** fields are only meaningful when the
property has the type `DRM_MODE_PROP_ENUM` or `DRM_MODE_PROP_BITMASK`. For
backwards compatibility, the kernel will always set **count_enum_blobs** to
zero when the property has the type `DRM_MODE_PROP_BLOB`. User-space must
ignore these two fields if the property has a different type.

User-space is expected to retrieve values and enums by performing this ioctl
at least twice: the first time to retrieve the number of elements, the
second time to retrieve the elements themselves.

To retrieve the number of elements, set **count_values** and **count_enum_blobs**
to zero, then call the ioctl. **count_values** will be updated with the number
of elements. If the property has the type `DRM_MODE_PROP_ENUM` or
`DRM_MODE_PROP_BITMASK`, **count_enum_blobs** will be updated as well.

To retrieve the elements themselves, allocate an array for **values_ptr** and
set **count_values** to its capacity. If the property has the type
`DRM_MODE_PROP_ENUM` or `DRM_MODE_PROP_BITMASK`, allocate an array for
**enum_blob_ptr** and set **count_enum_blobs** to its capacity. Calling the ioctl
again will fill the arrays.

#### <a id="c-struct-drm_mode_fb_cmd2"></a>`struct drm_mode_fb_cmd2`

Frame-buffer metadata.

**Definition**

```c
struct drm_mode_fb_cmd2 {
    __u32 fb_id;
    __u32 width;
    __u32 height;
    __u32 pixel_format;
    __u32 flags;
    __u32 handles[4];
    __u32 pitches[4];
    __u32 offsets[4];
    __u64 modifier[4];
};
```

**Members**

- `fb_id`: Object ID of the frame-buffer.
- `width`: Width of the frame-buffer.
- `height`: Height of the frame-buffer.
- `pixel_format`: FourCC format code, see `DRM_FORMAT_*` constants in
  `drm_fourcc.h`.
- `flags`: Frame-buffer flags (see `DRM_MODE_FB_INTERLACED` and
  `DRM_MODE_FB_MODIFIERS`).
- `handles`: GEM buffer handle, one per plane. Set to 0 if the plane is
  unused. The same handle can be used for multiple planes.
- `pitches`: Pitch (aka. stride) in bytes, one per plane.
- `offsets`: Offset into the buffer in bytes, one per plane.
- `modifier`: Format modifier, one per plane. See `DRM_FORMAT_MOD_*`
  constants in `drm_fourcc.h`. All planes must use the same
  modifier. Ignored unless `DRM_MODE_FB_MODIFIERS` is set in **flags**.

**Description**

This struct holds frame-buffer metadata. There are two ways to use it:

- User-space can fill this struct and perform a `DRM_IOCTL_MODE_ADDFB2`
  ioctl to register a new frame-buffer. The new frame-buffer object ID will
  be set by the kernel in **fb_id**.
- User-space can set **fb_id** and perform a [`DRM_IOCTL_MODE_GETFB2`](#c-DRM_IOCTL_MODE_GETFB2) ioctl to
  fetch metadata about an existing frame-buffer.

In case of planar formats, this struct allows up to 4 buffer objects with
offsets and pitches per plane. The pitch and offset order are dictated by
the format FourCC as defined by `drm_fourcc.h`, e.g. NV12 is described as:

YUV 4:2:0 image with a plane of 8-bit Y samples followed by an
interleaved U/V plane containing 8-bit 2x2 subsampled colour difference
samples.

So it would consist of a Y plane at `offsets[0]` and a UV plane at
`offsets[1]`.

To accommodate tiled, compressed, etc formats, a modifier can be specified.
For more information see the "Format Modifiers" section. Note that even
though it looks like we have a modifier per-plane, we in fact do not. The
modifier for each plane must be identical. Thus all combinations of
different data layouts for multi-plane formats must be enumerated as
separate modifiers.

All of the entries in **handles**, **pitches**, **offsets** and **modifier** must be
zero when unused. Warning, for **offsets** and **modifier** zero can't be used to
figure out whether the entry is used or not since it's a valid value (a zero
offset is common, and a zero modifier is `DRM_FORMAT_MOD_LINEAR`).

#### <a id="c-enum-drm_colorop_type"></a>`enum drm_colorop_type`

Type of color operation

**Constants**

- `DRM_COLOROP_1D_CURVE`: enum string "1D Curve"

  A 1D curve that is being applied to all color channels. The
  curve is specified via the CURVE_1D_TYPE colorop property.
- `DRM_COLOROP_1D_LUT`: enum string "1D LUT"

  A simple 1D LUT of uniformly spaced `drm_color_lut32` entries,
  packed into a blob via the DATA property. The driver's
  expected LUT size is advertised via the SIZE property.

  The DATA blob is an array of struct drm_color_lut32 with size
  of "size".
- `DRM_COLOROP_CTM_3X4`: enum string "3x4 Matrix"

  A 3x4 matrix. Its values are specified via the
  `drm_color_ctm_3x4` struct provided via the DATA property.

  The DATA blob is a float\[12\]:
  out   matrix          in
  | R |   | 0  1  2  3  |   | R |
  | G | = | 4  5  6  7  | x | G |
  | B |   | 8  9  10 12 |   | B |
- `DRM_COLOROP_MULTIPLIER`: enum string "Multiplier"

  A simple multiplier, applied to all color values. The
  multiplier is specified as a S31.32 via the MULTIPLIER
  property.
- `DRM_COLOROP_3D_LUT`: enum string "3D LUT"

  A 3D LUT of `drm_color_lut32` entries,
  packed into a blob via the DATA property. The driver's expected
  LUT size is advertised via the SIZE property, i.e., a 3D LUT with
  17x17x17 entries will have SIZE set to 17.

  The DATA blob is a 3D array of struct drm_color_lut32 with dimension
  length of "size".
  The LUT elements are traversed like so:

  - for B in range 0..n

    for G in range 0..n
    for R in range 0..n
    index = R + n * (G + n * B)
    color = lut3d\[index\]

**Description**

drm_colorops can be of many different types. Each type behaves differently
and defines a different set of properties. This enum defines all types and
gives a high-level description.

#### <a id="c-enum-drm_colorop_lut3d_interpolation_type"></a>`enum drm_colorop_lut3d_interpolation_type`

type of 3DLUT interpolation

**Constants**

- `DRM_COLOROP_LUT3D_INTERPOLATION_TETRAHEDRAL`: Tetrahedral 3DLUT interpolation

#### <a id="c-enum-drm_colorop_lut1d_interpolation_type"></a>`enum drm_colorop_lut1d_interpolation_type`

type of interpolation for 1D LUTs

**Constants**

- `DRM_COLOROP_LUT1D_INTERPOLATION_LINEAR`: Linear interpolation. Values between points of the LUT will be
  linearly interpolated.

#### <a id="c-struct-drm_plane_size_hint"></a>`struct drm_plane_size_hint`

Plane size hints

**Definition**

```c
struct drm_plane_size_hint {
    __u16 width;
    __u16 height;
};
```

**Members**

- `width`: The width of the plane in pixel
- `height`: The height of the plane in pixel

**Description**

The plane SIZE_HINTS property blob contains an
array of struct drm_plane_size_hint.

#### <a id="c-struct-hdr_metadata_infoframe"></a>`struct hdr_metadata_infoframe`

HDR Metadata Infoframe Data.

**Definition**

```c
struct hdr_metadata_infoframe {
    __u8 eotf;
    __u8 metadata_type;
    struct {
        __u16 x, y;
    } display_primaries[3];
    struct {
        __u16 x, y;
    } white_point;
    __u16 max_display_mastering_luminance;
    __u16 min_display_mastering_luminance;
    __u16 max_cll;
    __u16 max_fall;
};
```

**Members**

- `eotf`: Electro-Optical Transfer Function (EOTF)
  used in the stream.
- `metadata_type`: Static_Metadata_Descriptor_ID.
- `display_primaries`: Color Primaries of the Data.
  These are coded as unsigned 16-bit values in units of
  0.00002, where 0x0000 represents zero and 0xC350
  represents 1.0000.
  **display_primaries.x**: X coordinate of color primary.
  **display_primaries.y**: Y coordinate of color primary.
- `white_point`: White Point of Colorspace Data.
  These are coded as unsigned 16-bit values in units of
  0.00002, where 0x0000 represents zero and 0xC350
  represents 1.0000.
  **white_point.x**: X coordinate of whitepoint of color primary.
  **white_point.y**: Y coordinate of whitepoint of color primary.
- `max_display_mastering_luminance`: Max Mastering Display Luminance.
  This value is coded as an unsigned 16-bit value in units of 1 cd/m2,
  where 0x0001 represents 1 cd/m2 and 0xFFFF represents 65535 cd/m2.
- `min_display_mastering_luminance`: Min Mastering Display Luminance.
  This value is coded as an unsigned 16-bit value in units of
  0.0001 cd/m2, where 0x0001 represents 0.0001 cd/m2 and 0xFFFF
  represents 6.5535 cd/m2.
- `max_cll`: Max Content Light Level.
  This value is coded as an unsigned 16-bit value in units of 1 cd/m2,
  where 0x0001 represents 1 cd/m2 and 0xFFFF represents 65535 cd/m2.
- `max_fall`: Max Frame Average Light Level.
  This value is coded as an unsigned 16-bit value in units of 1 cd/m2,
  where 0x0001 represents 1 cd/m2 and 0xFFFF represents 65535 cd/m2.

**Description**

HDR Metadata Infoframe as per CTA 861.G spec. This is expected
to match exactly with the spec.

Userspace is expected to pass the metadata information as per
the format described in this structure.

#### <a id="c-struct-hdr_output_metadata"></a>`struct hdr_output_metadata`

HDR output metadata

**Definition**

```c
struct hdr_output_metadata {
    __u32 metadata_type;
    union {
        struct hdr_metadata_infoframe hdmi_metadata_type1;
    };
};
```

**Members**

- `metadata_type`: Static_Metadata_Descriptor_ID.
- `{unnamed_union}`: anonymous
- `hdmi_metadata_type1`: HDR Metadata Infoframe.

**Description**

Metadata Information to be passed from userspace

#### <a id="c-DRM_MODE_PAGE_FLIP_EVENT"></a>`DRM_MODE_PAGE_FLIP_EVENT`

```c
DRM_MODE_PAGE_FLIP_EVENT
```

**Description**

Request that the kernel sends back a vblank event (see
struct drm_event_vblank) with the [`DRM_EVENT_FLIP_COMPLETE`](#c-DRM_EVENT_FLIP_COMPLETE) type when the
page-flip is done.

When used with atomic uAPI, one event will be delivered per CRTC included in
the atomic commit. A CRTC is included in an atomic commit if one of its
properties is set, or if a property is set on a connector or plane linked
via the CRTC_ID property to the CRTC. At least one CRTC must be included,
and all pulled in CRTCs must be either previously or newly powered on (in
other words, a powered off CRTC which stays off cannot be included in the
atomic commit).

#### <a id="c-DRM_MODE_PAGE_FLIP_ASYNC"></a>`DRM_MODE_PAGE_FLIP_ASYNC`

```c
DRM_MODE_PAGE_FLIP_ASYNC
```

**Description**

Request that the page-flip is performed as soon as possible, ie. with no
delay due to waiting for vblank. This may cause tearing to be visible on
the screen.

When used with atomic uAPI, the driver will return an error if the hardware
doesn't support performing an asynchronous page-flip for this update.
User-space should handle this, e.g. by falling back to a regular page-flip.

Note, some hardware might need to perform one last synchronous page-flip
before being able to switch to asynchronous page-flips. As an exception,
the driver will return success even though that first page-flip is not
asynchronous.

#### <a id="c-DRM_MODE_PAGE_FLIP_FLAGS"></a>`DRM_MODE_PAGE_FLIP_FLAGS`

```c
DRM_MODE_PAGE_FLIP_FLAGS
```

**Description**

Bitmask of flags suitable for `drm_mode_crtc_page_flip_target.flags`.

#### <a id="c-struct-drm_mode_create_dumb"></a>`struct drm_mode_create_dumb`

Create a KMS dumb buffer for scanout.

**Definition**

```c
struct drm_mode_create_dumb {
    __u32 height;
    __u32 width;
    __u32 bpp;
    __u32 flags;
    __u32 handle;
    __u32 pitch;
    __u64 size;
};
```

**Members**

- `height`: buffer height in pixels
- `width`: buffer width in pixels
- `bpp`: color mode
- `flags`: must be zero
- `handle`: buffer object handle
- `pitch`: number of bytes between two consecutive lines
- `size`: size of the whole buffer in bytes

**Description**

User-space fills **height**, **width**, **bpp** and **flags**. If the IOCTL succeeds,
the kernel fills **handle**, **pitch** and **size**.

The value of **bpp** is a color-mode number describing a specific format
or a variant thereof. The value often corresponds to the number of bits
per pixel for most modes, although there are exceptions. Each color mode
maps to a DRM format plus a number of modes with similar pixel layout.
Framebuffer layout is always linear.

Support for all modes and formats is optional. Even if dumb-buffer
creation with a certain color mode succeeds, it is not guaranteed that
the DRM driver supports any of the related formats. Most drivers support
a color mode of 32 with a format of DRM_FORMAT_XRGB8888 on their primary
plane.

```text
+------------+------------------------+------------------------+
| Color mode | Framebuffer format     | Compatible formats     |
+============+========================+========================+
|     32     |  * DRM_FORMAT_XRGB8888 |  * DRM_FORMAT_BGRX8888 |
|            |                        |  * DRM_FORMAT_RGBX8888 |
|            |                        |  * DRM_FORMAT_XBGR8888 |
+------------+------------------------+------------------------+
|     24     |  * DRM_FORMAT_RGB888   |  * DRM_FORMAT_BGR888   |
+------------+------------------------+------------------------+
|     16     |  * DRM_FORMAT_RGB565   |  * DRM_FORMAT_BGR565   |
+------------+------------------------+------------------------+
|     15     |  * DRM_FORMAT_XRGB1555 |  * DRM_FORMAT_BGRX1555 |
|            |                        |  * DRM_FORMAT_RGBX1555 |
|            |                        |  * DRM_FORMAT_XBGR1555 |
+------------+------------------------+------------------------+
|      8     |  * DRM_FORMAT_C8       |  * DRM_FORMAT_D8       |
|            |                        |  * DRM_FORMAT_R8       |
+------------+------------------------+------------------------+
|      4     |  * DRM_FORMAT_C4       |  * DRM_FORMAT_D4       |
|            |                        |  * DRM_FORMAT_R4       |
+------------+------------------------+------------------------+
|      2     |  * DRM_FORMAT_C2       |  * DRM_FORMAT_D2       |
|            |                        |  * DRM_FORMAT_R2       |
+------------+------------------------+------------------------+
|      1     |  * DRM_FORMAT_C1       |  * DRM_FORMAT_D1       |
|            |                        |  * DRM_FORMAT_R1       |
+------------+------------------------+------------------------+
```

Color modes of 10, 12, 15, 30 and 64 are only supported for use by
legacy user space. Please don't use them in new code. Other modes
are not support.

Do not attempt to allocate anything but linear framebuffer memory
with single-plane RGB data. Allocation of other framebuffer
layouts requires dedicated ioctls in the respective DRM driver.

#### <a id="c-DRM_MODE_ATOMIC_TEST_ONLY"></a>`DRM_MODE_ATOMIC_TEST_ONLY`

```c
DRM_MODE_ATOMIC_TEST_ONLY
```

**Description**

Do not apply the atomic commit, instead check whether the hardware supports
this configuration.

See [`drm_mode_config_funcs.atomic_check`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_mode_config_funcs) for more details on test-only
commits.

#### <a id="c-DRM_MODE_ATOMIC_NONBLOCK"></a>`DRM_MODE_ATOMIC_NONBLOCK`

```c
DRM_MODE_ATOMIC_NONBLOCK
```

**Description**

Do not block while applying the atomic commit. The `DRM_IOCTL_MODE_ATOMIC`
IOCTL returns immediately instead of waiting for the changes to be applied
in hardware. Note, the driver will still check that the update can be
applied before retuning.

#### <a id="c-DRM_MODE_ATOMIC_ALLOW_MODESET"></a>`DRM_MODE_ATOMIC_ALLOW_MODESET`

```c
DRM_MODE_ATOMIC_ALLOW_MODESET
```

**Description**

Allow the update to result in temporary or transient visible artifacts while
the update is being applied. Applying the update may also take significantly
more time than a page flip. All visual artifacts will disappear by the time
the update is completed, as signalled through the vblank event's timestamp
(see struct drm_event_vblank).

This flag must be set when the KMS update might cause visible artifacts.
Without this flag such KMS update will return a EINVAL error. What kind of
update may cause visible artifacts depends on the driver and the hardware.
User-space that needs to know beforehand if an update might cause visible
artifacts can use [`DRM_MODE_ATOMIC_TEST_ONLY`](#c-DRM_MODE_ATOMIC_TEST_ONLY) without
[`DRM_MODE_ATOMIC_ALLOW_MODESET`](#c-DRM_MODE_ATOMIC_ALLOW_MODESET) to see if it fails.

To the best of the driver's knowledge, visual artifacts are guaranteed to
not appear when this flag is not set. Some sinks might display visual
artifacts outside of the driver's control.

#### <a id="c-DRM_MODE_ATOMIC_FLAGS"></a>`DRM_MODE_ATOMIC_FLAGS`

```c
DRM_MODE_ATOMIC_FLAGS
```

**Description**

Bitfield of flags accepted by the `DRM_IOCTL_MODE_ATOMIC` IOCTL in
`drm_mode_atomic.flags`.

#### <a id="c-struct-drm_mode_create_blob"></a>`struct drm_mode_create_blob`

Create New blob property

**Definition**

```c
struct drm_mode_create_blob {
    __u64 data;
    __u32 length;
    __u32 blob_id;
};
```

**Members**

- `data`: Pointer to data to copy.
- `length`: Length of data to copy.
- `blob_id`: Return: new property ID.

**Description**

Create a new 'blob' data property, copying length bytes from data pointer,
and returning new blob ID.

#### <a id="c-struct-drm_mode_destroy_blob"></a>`struct drm_mode_destroy_blob`

Destroy user blob

**Definition**

```c
struct drm_mode_destroy_blob {
    __u32 blob_id;
};
```

**Members**

- `blob_id`: blob_id to destroy

**Description**

Destroy a user-created blob property.

User-space can release blobs as soon as they do not need to refer to them by
their blob object ID.  For instance, if you are using a MODE_ID blob in an
atomic commit and you will not make another commit re-using the same ID, you
can destroy the blob as soon as the commit has been issued, without waiting
for it to complete.

#### <a id="c-struct-drm_mode_create_lease"></a>`struct drm_mode_create_lease`

Create lease

**Definition**

```c
struct drm_mode_create_lease {
    __u64 object_ids;
    __u32 object_count;
    __u32 flags;
    __u32 lessee_id;
    __u32 fd;
};
```

**Members**

- `object_ids`: Pointer to array of object ids (__u32)
- `object_count`: Number of object ids
- `flags`: flags for new FD (O_CLOEXEC, etc)
- `lessee_id`: Return: unique identifier for lessee.
- `fd`: Return: file descriptor to new drm_master file

**Description**

Lease mode resources, creating another drm_master.

The **object_ids** array must reference at least one CRTC, one connector and
one plane if [`DRM_CLIENT_CAP_UNIVERSAL_PLANES`](#c-DRM_CLIENT_CAP_UNIVERSAL_PLANES) is enabled. Alternatively,
the lease can be completely empty.

#### <a id="c-struct-drm_mode_list_lessees"></a>`struct drm_mode_list_lessees`

List lessees

**Definition**

```c
struct drm_mode_list_lessees {
    __u32 count_lessees;
    __u32 pad;
    __u64 lessees_ptr;
};
```

**Members**

- `count_lessees`: Number of lessees.

  On input, provides length of the array.
  On output, provides total number. No
  more than the input number will be written
  back, so two calls can be used to get
  the size and then the data.
- `pad`: Padding.
- `lessees_ptr`: Pointer to lessees.

  Pointer to __u64 array of lessee ids

**Description**

List lesses from a drm_master.

#### <a id="c-struct-drm_mode_get_lease"></a>`struct drm_mode_get_lease`

Get Lease

**Definition**

```c
struct drm_mode_get_lease {
    __u32 count_objects;
    __u32 pad;
    __u64 objects_ptr;
};
```

**Members**

- `count_objects`: Number of leased objects.

  On input, provides length of the array.
  On output, provides total number. No
  more than the input number will be written
  back, so two calls can be used to get
  the size and then the data.
- `pad`: Padding.
- `objects_ptr`: Pointer to objects.

  Pointer to __u32 array of object ids.

**Description**

Get leased objects.

#### <a id="c-struct-drm_mode_revoke_lease"></a>`struct drm_mode_revoke_lease`

Revoke lease

**Definition**

```c
struct drm_mode_revoke_lease {
    __u32 lessee_id;
};
```

**Members**

- `lessee_id`: Unique ID of lessee

#### <a id="c-struct-drm_mode_rect"></a>`struct drm_mode_rect`

Two dimensional rectangle.

**Definition**

```c
struct drm_mode_rect {
    __s32 x1;
    __s32 y1;
    __s32 x2;
    __s32 y2;
};
```

**Members**

- `x1`: Horizontal starting coordinate (inclusive).
- `y1`: Vertical starting coordinate (inclusive).
- `x2`: Horizontal ending coordinate (exclusive).
- `y2`: Vertical ending coordinate (exclusive).

**Description**

With drm subsystem using struct drm_rect to manage rectangular area this
export it to user-space.

Currently used by drm_mode_atomic blob property FB_DAMAGE_CLIPS.

#### <a id="c-struct-drm_mode_closefb"></a>`struct drm_mode_closefb`

**Definition**

```c
struct drm_mode_closefb {
    __u32 fb_id;
    __u32 pad;
};
```

**Members**

- `fb_id`: Framebuffer ID.
- `pad`: Must be zero.


<a id="rst-dma-buf-interoperability"></a>

## dma-buf interoperability

Please see [Documentation/userspace-api/dma-buf-alloc-exchange.rst](https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/Documentation/userspace-api/dma-buf-alloc-exchange.rst?id=9021cc14f7d98b4a1d2c932f52c5343d4d0f6b92) for information on how dma-buf is integrated and exposed within DRM.

<a id="rst-trace-events"></a>

## Trace events

See [Documentation/trace/tracepoints.rst](/kernel/development/trace/tracepoints.md) for information about using Linux Kernel Tracepoints. In the DRM subsystem, some events are considered stable uAPI to avoid breaking tools (e.g.: GPUVis, umr) relying on them. Stable means that fields cannot be removed, nor their formatting updated. Adding new fields is possible, under the normal uAPI requirements.

<a id="rst-stable-uapi-events"></a>

### Stable uAPI events

From `drivers/gpu/drm/scheduler/gpu_scheduler_trace.h`


`drm_sched_job_queue`, `drm_sched_job_run`, `drm_sched_job_add_dep`,
`drm_sched_job_done` and `drm_sched_job_unschedulable` are considered
stable uAPI.

Common trace events attributes:

* `dev`   - the [`dev_name()`](/kernel/hardware/driver-api/fundamentals/infrastructure.md#c-dev_name) of the device running the job.

* `ring`  - the hardware ring running the job. Together with `dev` it
  uniquely identifies where the job is going to be executed.

* `fence` - the [`struct dma_fence`](/kernel/hardware/driver-api/io-and-dma/dma-buf.md#c-struct-dma_fence).context and the [`struct dma_fence`](/kernel/hardware/driver-api/io-and-dma/dma-buf.md#c-struct-dma_fence).seqno of
  [`struct drm_sched_fence`](/kernel/hardware/gpu/drm-mm.md#c-struct-drm_sched_fence).finished

All the events depends on [`drm_sched_job_arm()`](/kernel/hardware/gpu/drm-mm.md#c-drm_sched_job_arm) having been called already for
the job because they use [`struct drm_sched_job`](/kernel/hardware/gpu/drm-mm.md#c-struct-drm_sched_job).sched or
[`struct drm_sched_job`](/kernel/hardware/gpu/drm-mm.md#c-struct-drm_sched_job).s_fence.

---

# DRM client usage stats

_Peios Kernel / Hardware and drivers / Graphics_

> DRM drivers can choose to export partly standardised text output via the fops->show_fdinfo() as part of the driver specific file operations registered in the struct drm_driver object registered with the DRM core.

<a id="rst-drm-client-usage-stats-1"></a>
<a id="rst-drm-client-usage-stats"></a>

DRM drivers can choose to export partly standardised text output via the `fops->show_fdinfo()` as part of the driver specific file operations registered in the `struct drm_driver` object registered with the DRM core.

One purpose of this output is to enable writing as generic as practically feasible `top(1)` like userspace monitoring tools.

Given the differences between various DRM drivers the specification of the output is split between common and driver specific parts. Having said that, wherever possible effort should still be made to standardise as much as possible.

<a id="rst-file-format-specification"></a>

## File format specification

- File shall contain one key value pair per one line of text.

- Colon character (`:`) must be used to delimit keys and values.

- All standardised keys shall be prefixed with `drm-`.

- Driver-specific keys shall be prefixed with `driver_name-`, where driver_name should ideally be the same as the `name` field in `struct drm_driver`, although this is not mandatory.

- Whitespace between the delimiter and first non-whitespace character shall be ignored when parsing.

- Keys are not allowed to contain whitespace characters.

- Numerical key value pairs can end with optional unit string.

- Data type of the value is fixed as defined in the specification.

<a id="rst-key-types"></a>

### Key types

1. Mandatory, fully standardised.

2. Optional, fully standardised.

3. Driver specific.

<a id="rst-data-types"></a>

### Data types

- &lt;uint&gt; - Unsigned integer without defining the maximum value.

- &lt;keystr&gt; - String excluding any above defined reserved characters or whitespace.

- &lt;valstr&gt; - String.

<a id="rst-mandatory-fully-standardised-keys"></a>

### Mandatory fully standardised keys

- drm-driver: &lt;valstr&gt;

String shall contain the name this driver registered as via the respective `struct drm_driver` data structure.

<a id="rst-optional-fully-standardised-keys"></a>

### Optional fully standardised keys

<a id="rst-identification"></a>

#### Identification

- drm-pdev: &lt;aaaa:bb.cc.d&gt;

For PCI devices this should contain the PCI slot address of the device in question.

- drm-client-id: &lt;uint&gt;

Unique value relating to the open DRM file descriptor used to distinguish duplicated and shared file descriptors. Conceptually the value should map 1:1 to the in kernel representation of `struct drm_file` instances.

Uniqueness of the value shall be either globally unique, or unique within the scope of each device, in which case `drm-pdev` shall be present as well.

Userspace should make sure to not double account any usage statistics by using the above described criteria in order to associate data to individual clients.

- drm-client-name: &lt;valstr&gt;

String optionally set by userspace using DRM_IOCTL_SET_CLIENT_NAME.

<a id="rst-utilization"></a>

#### Utilization

- drm-engine-&lt;keystr&gt;: &lt;uint&gt; ns

GPUs usually contain multiple execution engines. Each shall be given a stable and unique name (keystr), with possible values documented in the driver specific documentation.

Value shall be in specified time units which the respective GPU engine spent busy executing workloads belonging to this client.

Values are not required to be constantly monotonic if it makes the driver implementation easier, but are required to catch up with the previously reported larger value within a reasonable period. Upon observing a value lower than what was previously read, userspace is expected to stay with that larger previous value until a monotonic update is seen.

- drm-engine-capacity-&lt;keystr&gt;: &lt;uint&gt;

Engine identifier string must be the same as the one specified in the drm-engine-&lt;keystr&gt; tag and shall contain a greater than zero number in case the exported engine corresponds to a group of identical hardware engines.

In the absence of this tag parser shall assume capacity of one. Zero capacity is not allowed.

- drm-cycles-&lt;keystr&gt;: &lt;uint&gt;

Engine identifier string must be the same as the one specified in the drm-engine-&lt;keystr&gt; tag and shall contain the number of busy cycles for the given engine.

Values are not required to be constantly monotonic if it makes the driver implementation easier, but are required to catch up with the previously reported larger value within a reasonable period. Upon observing a value lower than what was previously read, userspace is expected to stay with that larger previous value until a monotonic update is seen.

- drm-total-cycles-&lt;keystr&gt;: &lt;uint&gt;

Engine identifier string must be the same as the one specified in the drm-cycles-&lt;keystr&gt; tag and shall contain the total number cycles for the given engine.

This is a timestamp in GPU unspecified unit that matches the update rate of drm-cycles-&lt;keystr&gt;. For drivers that implement this interface, the engine utilization can be calculated entirely on the GPU clock domain, without considering the CPU sleep time between 2 samples.

A driver may implement either this key or drm-maxfreq-&lt;keystr&gt;, but not both.

- drm-maxfreq-&lt;keystr&gt;: &lt;uint&gt; \[Hz\|MHz\|KHz\]

Engine identifier string must be the same as the one specified in the drm-engine-&lt;keystr&gt; tag and shall contain the maximum frequency for the given engine.  Taken together with drm-cycles-&lt;keystr&gt;, this can be used to calculate percentage utilization of the engine, whereas drm-engine-&lt;keystr&gt; only reflects time active without considering what frequency the engine is operating as a percentage of its maximum frequency.

A driver may implement either this key or drm-total-cycles-&lt;keystr&gt;, but not both.

<a id="rst-memory"></a>

#### Memory

Each possible memory type which can be used to store buffer objects by the GPU in question shall be given a stable and unique name to be used as the "&lt;region&gt;" string.

The region name "memory" is reserved to refer to normal system memory.

The value shall reflect the amount of storage currently consumed by the buffer objects belong to this client, in the respective memory region.

Default unit shall be bytes with optional unit specifiers of 'KiB' or 'MiB' indicating kibi- or mebi-bytes.

- drm-total-&lt;region&gt;: &lt;uint&gt; \[KiB\|MiB\]

The total size of all requested buffers, including both shared and private memory. The backing store for the buffers does not need to be currently instantiated to count under this category. To avoid double-counting, if a buffer has multiple regions where it can be allocated to, the implementation should consistently select a single region for accounting purposes.

- drm-shared-&lt;region&gt;: &lt;uint&gt; \[KiB\|MiB\]

The total size of buffers that are shared with another file (i.e., have more than one handle). The same requirement to avoid double-counting that applies to drm-total-&lt;region&gt; also applies here.

- drm-resident-&lt;region&gt;: &lt;uint&gt; \[KiB\|MiB\]

The total size of buffers that are resident (i.e., have their backing store present or instantiated) in the specified region.

- drm-memory-&lt;region&gt;: &lt;uint&gt; \[KiB\|MiB\]

This key is deprecated and is only printed by amdgpu; it is an alias for drm-resident-&lt;region&gt;.

- drm-purgeable-&lt;region&gt;: &lt;uint&gt; \[KiB\|MiB\]

The total size of buffers that are resident and purgeable.

For example, drivers that implement functionality similar to 'madvise' can count buffers that have instantiated backing stores but have been marked with an equivalent of MADV_DONTNEED.

- drm-active-&lt;region&gt;: &lt;uint&gt; \[KiB\|MiB\]

The total size of buffers that are active on one or more engines.

One practical example of this could be the presence of unsignaled fences in a GEM buffer reservation object. Therefore, the active category is a subset of the resident category.

<a id="rst-implementation-details"></a>

## Implementation Details

Drivers should use drm_show_fdinfo() in their `struct file_operations`, and implement &amp;drm_driver.show_fdinfo if they wish to provide any stats which are not provided by drm_show_fdinfo().  But even driver specific stats should be documented above and where possible, aligned with other drivers.

<a id="rst-driver-specific-implementations"></a>

### Driver specific implementations

- [i915 DRM client usage stats implementation](</kernel/hardware/gpu/i915.md#rst-i915-usage-stats>)

- [panfrost-usage-stats](</kernel/hardware/gpu/panfrost.md#rst-panfrost-usage-stats>)

- [panthor-usage-stats](</kernel/hardware/gpu/panthor.md#rst-panthor-usage-stats>)

- [Xe DRM client usage stats implementation](</kernel/hardware/gpu/xe/xe-drm-usage-stats.md#rst-xe-usage-stats>)

---

# Asynchronous VM_BIND

_Peios Kernel / Hardware and drivers / Graphics_

> VRAM: On-device memory. Sometimes referred to as device local memory.

<a id="rst-asynchronous-vm-bind"></a>

<!-- SPDX-License-Identifier: (GPL-2.0+ OR MIT) -->

<a id="rst-nomenclature"></a>

## Nomenclature:

- `VRAM`: On-device memory. Sometimes referred to as device local memory.

- `gpu_vm`: A virtual GPU address space. Typically per process, but can be shared by multiple processes.

- `VM_BIND`: An operation or a list of operations to modify a gpu_vm using an IOCTL. The operations include mapping and unmapping system- or VRAM memory.

- `syncobj`: A container that abstracts synchronization objects. The synchronization objects can be either generic, like dma-fences or driver specific. A syncobj typically indicates the type of the underlying synchronization object.

- `in-syncobj`: Argument to a VM_BIND IOCTL, the VM_BIND operation waits for these before starting.

- `out-syncobj`: Argument to a VM_BIND_IOCTL, the VM_BIND operation signals these when the bind operation is complete.

- `dma-fence`: A cross-driver synchronization object. A basic understanding of dma-fences is required to digest this document. Please refer to the `DMA Fences` section of the [dma-buf doc](</kernel/hardware/driver-api/io-and-dma/dma-buf.md>).

- `memory fence`: A synchronization object, different from a dma-fence. A memory fence uses the value of a specified memory location to determine signaled status. A memory fence can be awaited and signaled by both the GPU and CPU. Memory fences are sometimes referred to as user-fences, userspace-fences or gpu futexes and do not necessarily obey the dma-fence rule of signaling within a "reasonable amount of time". The kernel should thus avoid waiting for memory fences with locks held.

- `long-running workload`: A workload that may take more than the current stipulated dma-fence maximum signal delay to complete and which therefore needs to set the gpu_vm or the GPU execution context in a certain mode that disallows completion dma-fences.

- `exec function`: An exec function is a function that revalidates all affected gpu_vmas, submits a GPU command batch and registers the dma_fence representing the GPU command's activity with all affected dma_resvs. For completeness, although not covered by this document, it's worth mentioning that an exec function may also be the revalidation worker that is used by some drivers in compute / long-running mode.

- `bind context`: A context identifier used for the VM_BIND operation. VM_BIND operations that use the same bind context can be assumed, where it matters, to complete in order of submission. No such assumptions can be made for VM_BIND operations using separate bind contexts.

- `UMD`: User-mode driver.

- `KMD`: Kernel-mode driver.

<a id="rst-synchronous-asynchronous-vm-bind-operation"></a>

## Synchronous / Asynchronous VM_BIND operation

<a id="rst-synchronous-vm-bind"></a>

### Synchronous VM_BIND

With Synchronous VM_BIND, the VM_BIND operations all complete before the IOCTL returns. A synchronous VM_BIND takes neither in-fences nor out-fences. Synchronous VM_BIND may block and wait for GPU operations; for example swap-in or clearing, or even previous binds.

<a id="rst-asynchronous-vm-bind-1"></a>

### Asynchronous VM_BIND

Asynchronous VM_BIND accepts both in-syncobjs and out-syncobjs. While the IOCTL may return immediately, the VM_BIND operations wait for the in-syncobjs before modifying the GPU page-tables, and signal the out-syncobjs when the modification is done in the sense that the next exec function that awaits for the out-syncobjs will see the change. Errors are reported synchronously. In low-memory situations the implementation may block, performing the VM_BIND synchronously, because there might not be enough memory immediately available for preparing the asynchronous operation.

If the VM_BIND IOCTL takes a list or an array of operations as an argument, the in-syncobjs needs to signal before the first operation starts to execute, and the out-syncobjs signal after the last operation completes. Operations in the operation list can be assumed, where it matters, to complete in order.

Since asynchronous VM_BIND operations may use dma-fences embedded in out-syncobjs and internally in KMD to signal bind completion,  any memory fences given as VM_BIND in-fences need to be awaited synchronously before the VM_BIND ioctl returns, since dma-fences, required to signal in a reasonable amount of time, can never be made to depend on memory fences that don't have such a restriction.

The purpose of an Asynchronous VM_BIND operation is for user-mode drivers to be able to pipeline interleaved gpu_vm modifications and exec functions. For long-running workloads, such pipelining of a bind operation is not allowed and any in-fences need to be awaited synchronously. The reason for this is twofold. First, any memory fences gated by a long-running workload and used as in-syncobjs for the VM_BIND operation will need to be awaited synchronously anyway (see above). Second, any dma-fences used as in-syncobjs for VM_BIND operations for long-running workloads will not allow for pipelining anyway since long-running workloads don't allow for dma-fences as out-syncobjs, so while theoretically possible the use of them is questionable and should be rejected until there is a valuable use-case. Note that this is not a limitation imposed by dma-fence rules, but rather a limitation imposed to keep KMD implementation simple. It does not affect using dma-fences as dependencies for the long-running workload itself, which is allowed by dma-fence rules, but rather for the VM_BIND operation only.

An asynchronous VM_BIND operation may take substantial time to complete and signal the out_fence. In particular if the operation is deeply pipelined behind other VM_BIND operations and workloads submitted using exec functions. In that case, UMD might want to avoid a subsequent VM_BIND operation to be queued behind the first one if there are no explicit dependencies. In order to circumvent such a queue-up, a VM_BIND implementation may allow for VM_BIND contexts to be created. For each context, VM_BIND operations will be guaranteed to complete in the order they were submitted, but that is not the case for VM_BIND operations executing on separate VM_BIND contexts. Instead KMD will attempt to execute such VM_BIND operations in parallel but leaving no guarantee that they will actually be executed in parallel. There may be internal implicit dependencies that only KMD knows about, for example page-table structure changes. A way to attempt to avoid such internal dependencies is to have different VM_BIND contexts use separate regions of a VM.

Also for VM_BINDS for long-running gpu_vms the user-mode driver should typically select memory fences as out-fences since that gives greater flexibility for the kernel mode driver to inject other operations into the bind / unbind operations. Like for example inserting breakpoints into batch buffers. The workload execution can then easily be pipelined behind the bind completion using the memory out-fence as the signal condition for a GPU semaphore embedded by UMD in the workload.

There is no difference in the operations supported or in multi-operation support between asynchronous VM_BIND and synchronous VM_BIND.

<a id="rst-multi-operation-vm-bind-ioctl-error-handling-and-interrupts"></a>

## Multi-operation VM_BIND IOCTL error handling and interrupts

The VM_BIND operations of the IOCTL may error for various reasons, for example due to lack of resources to complete and due to interrupted waits. In these situations UMD should preferably restart the IOCTL after taking suitable action. If UMD has over-committed a memory resource, an -ENOSPC error will be returned, and UMD may then unbind resources that are not used at the moment and rerun the IOCTL. On -EINTR, UMD should simply rerun the IOCTL and on -ENOMEM user-space may either attempt to free known system memory resources or fail. In case of UMD deciding to fail a bind operation, due to an error return, no additional action is needed to clean up the failed operation, and the VM is left in the same state as it was before the failing IOCTL. Unbind operations are guaranteed not to return any errors due to resource constraints, but may return errors due to, for example, invalid arguments or the gpu_vm being banned. In the case an unexpected error happens during the asynchronous bind process, the gpu_vm will be banned, and attempts to use it after banning will return -ENOENT.

<a id="rst-example-the-xe-vm-bind-uapi"></a>

## Example: The Xe VM_BIND uAPI

Starting with the VM_BIND operation struct, the IOCTL call can take zero, one or many such operations. A zero number means only the synchronization part of the IOCTL is carried out: an asynchronous VM_BIND updates the syncobjects, whereas a sync VM_BIND waits for the implicit dependencies to be fulfilled.



```c
struct drm_xe_vm_bind_op {
     /**
      * @obj: GEM object to operate on, MBZ for MAP_USERPTR, MBZ for UNMAP
      */
     __u32 obj;

     /** @pad: MBZ */
     __u32 pad;

     union {
             /**
              * @obj_offset: Offset into the object for MAP.
              */
             __u64 obj_offset;

             /** @userptr: user virtual address for MAP_USERPTR */
             __u64 userptr;
     };

     /**
      * @range: Number of bytes from the object to bind to addr, MBZ for UNMAP_ALL
      */
     __u64 range;

     /** @addr: Address to operate on, MBZ for UNMAP_ALL */
     __u64 addr;

     /**
      * @tile_mask: Mask for which tiles to create binds for, 0 == All tiles,
      * only applies to creating new VMAs
      */
     __u64 tile_mask;

    /* Map (parts of) an object into the GPU virtual address range.
 #define XE_VM_BIND_OP_MAP           0x0
     /* Unmap a GPU virtual address range */
 #define XE_VM_BIND_OP_UNMAP         0x1
     /*
      * Map a CPU virtual address range into a GPU virtual
      * address range.
      */
 #define XE_VM_BIND_OP_MAP_USERPTR   0x2
     /* Unmap a gem object from the VM. */
 #define XE_VM_BIND_OP_UNMAP_ALL     0x3
     /*
      * Make the backing memory of an address range resident if
      * possible. Note that this doesn't pin backing memory.
      */
 #define XE_VM_BIND_OP_PREFETCH      0x4

     /* Make the GPU map readonly. */
 #define XE_VM_BIND_FLAG_READONLY    (0x1 << 16)
     /*
      * Valid on a faulting VM only, do the MAP operation immediately rather
      * than deferring the MAP to the page fault handler.
      */
 #define XE_VM_BIND_FLAG_IMMEDIATE   (0x1 << 17)
     /*
      * When the NULL flag is set, the page tables are setup with a special
      * bit which indicates writes are dropped and all reads return zero.  In
      * the future, the NULL flags will only be valid for XE_VM_BIND_OP_MAP
      * operations, the BO handle MBZ, and the BO offset MBZ. This flag is
      * intended to implement VK sparse bindings.
      */
 #define XE_VM_BIND_FLAG_NULL        (0x1 << 18)
     /** @op: Operation to perform (lower 16 bits) and flags (upper 16 bits) */
     __u32 op;

     /** @mem_region: Memory region to prefetch VMA to, instance not a mask */
     __u32 region;

     /** @reserved: Reserved */
     __u64 reserved[2];
};
```

The VM_BIND IOCTL argument itself, looks like follows. Note that for synchronous VM_BIND, the num_syncs and syncs fields must be zero. Here the `exec_queue_id` field is the VM_BIND context discussed previously that is used to facilitate out-of-order VM_BINDs.



```c
struct drm_xe_vm_bind {
    /** @extensions: Pointer to the first extension struct, if any */
    __u64 extensions;

    /** @vm_id: The ID of the VM to bind to */
    __u32 vm_id;

    /**
     * @exec_queue_id: exec_queue_id, must be of class DRM_XE_ENGINE_CLASS_VM_BIND
     * and exec queue must have same vm_id. If zero, the default VM bind engine
     * is used.
     */
    __u32 exec_queue_id;

    /** @num_binds: number of binds in this IOCTL */
    __u32 num_binds;

    /* If set, perform an async VM_BIND, if clear a sync VM_BIND */
#define XE_VM_BIND_IOCTL_FLAG_ASYNC (0x1 << 0)

    /** @flag: Flags controlling all operations in this ioctl. */
    __u32 flags;

    union {
            /** @bind: used if num_binds == 1 */
            struct drm_xe_vm_bind_op bind;

            /**
             * @vector_of_binds: userptr to array of struct
             * drm_xe_vm_bind_op if num_binds > 1
             */
            __u64 vector_of_binds;
    };

    /** @num_syncs: amount of syncs to wait for or to signal on completion. */
    __u32 num_syncs;

    /** @pad2: MBZ */
    __u32 pad2;

    /** @syncs: pointer to struct drm_xe_sync array */
    __u64 syncs;

    /** @reserved: Reserved */
    __u64 reserved[2];
};
```

---

# VM_BIND locking

_Peios Kernel / Hardware and drivers / Graphics_

> This document attempts to describe what's needed to get VM_BIND locking right, including the userptr mmu_notifier locking. It also discusses some optimizations to get rid of the looping through of all userptr mappings and external / shared…

<a id="rst-vm-bind-locking"></a>

<!-- SPDX-License-Identifier: (GPL-2.0+ OR MIT) -->

This document attempts to describe what's needed to get VM_BIND locking right, including the userptr mmu_notifier locking. It also discusses some optimizations to get rid of the looping through of all userptr mappings and external / shared object mappings that is needed in the simplest implementation. In addition, there is a section describing the VM_BIND locking required for implementing recoverable pagefaults.

<a id="rst-the-drm-gpuvm-set-of-helpers"></a>

## The DRM GPUVM set of helpers

There is a set of helpers for drivers implementing VM_BIND, and this set of helpers implements much, but not all of the locking described in this document. In particular, it is currently lacking a userptr implementation. This document does not intend to describe the DRM GPUVM implementation in detail, but it is covered in [its own documentation](</kernel/hardware/gpu/drm-mm.md#rst-drm-gpuvm>). It is highly recommended for any driver implementing VM_BIND to use the DRM GPUVM helpers and to extend it if common functionality is missing.

<a id="rst-nomenclature"></a>

## Nomenclature

- `gpu_vm`: Abstraction of a virtual GPU address space with meta-data. Typically one per client (DRM file-private), or one per execution context.

- `gpu_vma`: Abstraction of a GPU address range within a gpu_vm with associated meta-data. The backing storage of a gpu_vma can either be a GEM object or anonymous or page-cache pages mapped also into the CPU address space for the process.

- `gpu_vm_bo`: Abstracts the association of a GEM object and a VM. The GEM object maintains a list of gpu_vm_bos, where each gpu_vm_bo maintains a list of gpu_vmas.

- `userptr gpu_vma or just userptr`: A gpu_vma, whose backing store is anonymous or page-cache pages as described above.

- `revalidating`: Revalidating a gpu_vma means making the latest version of the backing store resident and making sure the gpu_vma's page-table entries point to that backing store.

- `dma_fence`: A struct dma_fence that is similar to a struct completion and which tracks GPU activity. When the GPU activity is finished, the dma_fence signals. Please refer to the `DMA Fences` section of the [dma-buf doc](</kernel/hardware/driver-api/io-and-dma/dma-buf.md>).

- `dma_resv`: A struct dma_resv (a.k.a reservation object) that is used to track GPU activity in the form of multiple dma_fences on a gpu_vm or a GEM object. The dma_resv contains an array / list of dma_fences and a lock that needs to be held when adding additional dma_fences to the dma_resv. The lock is of a type that allows deadlock-safe locking of multiple dma_resvs in arbitrary order. Please refer to the `Reservation Objects` section of the [dma-buf doc](</kernel/hardware/driver-api/io-and-dma/dma-buf.md>).

- `exec function`: An exec function is a function that revalidates all affected gpu_vmas, submits a GPU command batch and registers the dma_fence representing the GPU command's activity with all affected dma_resvs. For completeness, although not covered by this document, it's worth mentioning that an exec function may also be the revalidation worker that is used by some drivers in compute / long-running mode.

- `local object`: A GEM object which is only mapped within a single VM. Local GEM objects share the gpu_vm's dma_resv.

- `external object`: a.k.a shared object: A GEM object which may be shared by multiple gpu_vms and whose backing storage may be shared with other drivers.

<a id="rst-locks-and-locking-order"></a>

## Locks and locking order

One of the benefits of VM_BIND is that local GEM objects share the gpu_vm's dma_resv object and hence the dma_resv lock. So, even with a huge number of local GEM objects, only one lock is needed to make the exec sequence atomic.

The following locks and locking orders are used:

- The `gpu_vm->lock` (optionally an rwsem). Protects the gpu_vm's data structure keeping track of gpu_vmas. It can also protect the gpu_vm's list of userptr gpu_vmas. With a CPU mm analogy this would correspond to the mmap_lock. An rwsem allows several readers to walk the VM tree concurrently, but the benefit of that concurrency most likely varies from driver to driver.

- The `userptr_seqlock`. This lock is taken in read mode for each userptr gpu_vma on the gpu_vm's userptr list, and in write mode during mmu notifier invalidation. This is not a real seqlock but described in `mm/mmu_notifier.c` as a "Collision-retry read-side/write-side 'lock' a lot like a seqcount. However this allows multiple write-sides to hold it at once...". The read side critical section is enclosed by `mmu_interval_read_begin() / mmu_interval_read_retry()` with `mmu_interval_read_begin()` sleeping if the write side is held. The write side is held by the core mm while calling mmu interval invalidation notifiers.

- The `gpu_vm->resv` lock. Protects the gpu_vm's list of gpu_vmas needing rebinding, as well as the residency state of all the gpu_vm's local GEM objects. Furthermore, it typically protects the gpu_vm's list of evicted and external GEM objects.

- The `gpu_vm->userptr_notifier_lock`. This is an rwsem that is taken in read mode during exec and write mode during a mmu notifier invalidation. The userptr notifier lock is per gpu_vm.

- The `gem_object->gpuva_lock` This lock protects the GEM object's list of gpu_vm_bos. This is usually the same lock as the GEM object's dma_resv, but some drivers protects this list differently, see below.

- The `gpu_vm list spinlocks`. With some implementations they are needed to be able to update the gpu_vm evicted- and external object list. For those implementations, the spinlocks are grabbed when the lists are manipulated. However, to avoid locking order violations with the dma_resv locks, a special scheme is needed when iterating over the lists.

<a id="rst-protection-and-lifetime-of-gpu-vm-bos-and-gpu-vmas"></a>
<a id="rst-gpu-vma-lifetime"></a>

## Protection and lifetime of gpu_vm_bos and gpu_vmas

The GEM object's list of gpu_vm_bos, and the gpu_vm_bo's list of gpu_vmas is protected by the `gem_object->gpuva_lock`, which is typically the same as the GEM object's dma_resv, but if the driver needs to access these lists from within a dma_fence signalling critical section, it can instead choose to protect it with a separate lock, which can be locked from within the dma_fence signalling critical section. Such drivers then need to pay additional attention to what locks need to be taken from within the loop when iterating over the gpu_vm_bo and gpu_vma lists to avoid locking-order violations.

The DRM GPUVM set of helpers provide lockdep asserts that this lock is held in relevant situations and also provides a means of making itself aware of which lock is actually used: `drm_gem_gpuva_set_lock()`.

Each gpu_vm_bo holds a reference counted pointer to the underlying GEM object, and each gpu_vma holds a reference counted pointer to the gpu_vm_bo. When iterating over the GEM object's list of gpu_vm_bos and over the gpu_vm_bo's list of gpu_vmas, the `gem_object->gpuva_lock` must not be dropped, otherwise, gpu_vmas attached to a gpu_vm_bo may disappear without notice since those are not reference-counted. A driver may implement its own scheme to allow this at the expense of additional complexity, but this is outside the scope of this document.

In the DRM GPUVM implementation, each gpu_vm_bo and each gpu_vma holds a reference count on the gpu_vm itself. Due to this, and to avoid circular reference counting, cleanup of the gpu_vm's gpu_vmas must not be done from the gpu_vm's destructor. Drivers typically implements a gpu_vm close function for this cleanup. The gpu_vm close function will abort gpu execution using this VM, unmap all gpu_vmas and release page-table memory.

<a id="rst-revalidation-and-eviction-of-local-objects"></a>

## Revalidation and eviction of local objects

Note that in all the code examples given below we use simplified pseudo-code. In particular, the dma_resv deadlock avoidance algorithm as well as reserving memory for dma_resv fences is left out.

<a id="rst-revalidation"></a>

### Revalidation

With VM_BIND, all local objects need to be resident when the gpu is executing using the gpu_vm, and the objects need to have valid gpu_vmas set up pointing to them. Typically, each gpu command buffer submission is therefore preceded with a re-validation section:



```C
dma_resv_lock(gpu_vm->resv);

// Validation section starts here.
for_each_gpu_vm_bo_on_evict_list(&gpu_vm->evict_list, &gpu_vm_bo) {
        validate_gem_bo(&gpu_vm_bo->gem_bo);

        // The following list iteration needs the Gem object's
        // dma_resv to be held (it protects the gpu_vm_bo's list of
        // gpu_vmas, but since local gem objects share the gpu_vm's
        // dma_resv, it is already held at this point.
        for_each_gpu_vma_of_gpu_vm_bo(&gpu_vm_bo, &gpu_vma)
               move_gpu_vma_to_rebind_list(&gpu_vma, &gpu_vm->rebind_list);
}

for_each_gpu_vma_on_rebind_list(&gpu vm->rebind_list, &gpu_vma) {
        rebind_gpu_vma(&gpu_vma);
        remove_gpu_vma_from_rebind_list(&gpu_vma);
}
// Validation section ends here, and job submission starts.

add_dependencies(&gpu_job, &gpu_vm->resv);
job_dma_fence = gpu_submit(&gpu_job));

add_dma_fence(job_dma_fence, &gpu_vm->resv);
dma_resv_unlock(gpu_vm->resv);
```

The reason for having a separate gpu_vm rebind list is that there might be userptr gpu_vmas that are not mapping a buffer object that also need rebinding.

<a id="rst-eviction"></a>

### Eviction

Eviction of one of these local objects will then look similar to the following:



```C
obj = get_object_from_lru();

dma_resv_lock(obj->resv);
for_each_gpu_vm_bo_of_obj(obj, &gpu_vm_bo);
        add_gpu_vm_bo_to_evict_list(&gpu_vm_bo, &gpu_vm->evict_list);

add_dependencies(&eviction_job, &obj->resv);
job_dma_fence = gpu_submit(&eviction_job);
add_dma_fence(&obj->resv, job_dma_fence);

dma_resv_unlock(&obj->resv);
put_object(obj);
```

Note that since the object is local to the gpu_vm, it will share the gpu_vm's dma_resv lock such that `obj->resv == gpu_vm->resv`. The gpu_vm_bos marked for eviction are put on the gpu_vm's evict list, which is protected by `gpu_vm->resv`. During eviction all local objects have their dma_resv locked and, due to the above equality, also the gpu_vm's dma_resv protecting the gpu_vm's evict list is locked.

With VM_BIND, gpu_vmas don't need to be unbound before eviction, since the driver must ensure that the eviction blit or copy will wait for GPU idle or depend on all previous GPU activity. Furthermore, any subsequent attempt by the GPU to access freed memory through the gpu_vma will be preceded by a new exec function, with a revalidation section which will make sure all gpu_vmas are rebound. The eviction code holding the object's dma_resv while revalidating will ensure a new exec function may not race with the eviction.

A driver can be implemented in such a way that, on each exec function, only a subset of vmas are selected for rebind.  In this case, all vmas that are *not* selected for rebind must be unbound before the exec function workload is submitted.

<a id="rst-locking-with-external-buffer-objects"></a>

## Locking with external buffer objects

Since external buffer objects may be shared by multiple gpu_vm's they can't share their reservation object with a single gpu_vm. Instead they need to have a reservation object of their own. The external objects bound to a gpu_vm using one or many gpu_vmas are therefore put on a per-gpu_vm list which is protected by the gpu_vm's dma_resv lock or one of the [gpu_vm list spinlocks](<#rst-spinlock-iteration>). Once the gpu_vm's reservation object is locked, it is safe to traverse the external object list and lock the dma_resvs of all external objects. However, if instead a list spinlock is used, a more elaborate iteration scheme needs to be used.

At eviction time, the gpu_vm_bos of *all* the gpu_vms an external object is bound to need to be put on their gpu_vm's evict list. However, when evicting an external object, the dma_resvs of the gpu_vms the object is bound to are typically not held. Only the object's private dma_resv can be guaranteed to be held. If there is a ww_acquire context at hand at eviction time we could grab those dma_resvs but that could cause expensive ww_mutex rollbacks. A simple option is to just mark the gpu_vm_bos of the evicted gem object with an `evicted` bool that is inspected before the next time the corresponding gpu_vm evicted list needs to be traversed. For example, when traversing the list of external objects and locking them. At that time, both the gpu_vm's dma_resv and the object's dma_resv is held, and the gpu_vm_bo marked evicted, can then be added to the gpu_vm's list of evicted gpu_vm_bos. The `evicted` bool is formally protected by the object's dma_resv.

The exec function becomes



```C
dma_resv_lock(gpu_vm->resv);

// External object list is protected by the gpu_vm->resv lock.
for_each_gpu_vm_bo_on_extobj_list(gpu_vm, &gpu_vm_bo) {
        dma_resv_lock(gpu_vm_bo.gem_obj->resv);
        if (gpu_vm_bo_marked_evicted(&gpu_vm_bo))
                add_gpu_vm_bo_to_evict_list(&gpu_vm_bo, &gpu_vm->evict_list);
}

for_each_gpu_vm_bo_on_evict_list(&gpu_vm->evict_list, &gpu_vm_bo) {
        validate_gem_bo(&gpu_vm_bo->gem_bo);

        for_each_gpu_vma_of_gpu_vm_bo(&gpu_vm_bo, &gpu_vma)
               move_gpu_vma_to_rebind_list(&gpu_vma, &gpu_vm->rebind_list);
}

for_each_gpu_vma_on_rebind_list(&gpu vm->rebind_list, &gpu_vma) {
        rebind_gpu_vma(&gpu_vma);
        remove_gpu_vma_from_rebind_list(&gpu_vma);
}

add_dependencies(&gpu_job, &gpu_vm->resv);
job_dma_fence = gpu_submit(&gpu_job));

add_dma_fence(job_dma_fence, &gpu_vm->resv);
for_each_external_obj(gpu_vm, &obj)
       add_dma_fence(job_dma_fence, &obj->resv);
dma_resv_unlock_all_resv_locks();
```

And the corresponding shared-object aware eviction would look like:



```C
obj = get_object_from_lru();

dma_resv_lock(obj->resv);
for_each_gpu_vm_bo_of_obj(obj, &gpu_vm_bo)
        if (object_is_vm_local(obj))
             add_gpu_vm_bo_to_evict_list(&gpu_vm_bo, &gpu_vm->evict_list);
        else
             mark_gpu_vm_bo_evicted(&gpu_vm_bo);

add_dependencies(&eviction_job, &obj->resv);
job_dma_fence = gpu_submit(&eviction_job);
add_dma_fence(&obj->resv, job_dma_fence);

dma_resv_unlock(&obj->resv);
put_object(obj);
```

<a id="rst-accessing-the-gpu-vm-s-lists-without-the-dma-resv-lock-held"></a>
<a id="rst-spinlock-iteration"></a>

## Accessing the gpu_vm's lists without the dma_resv lock held

Some drivers will hold the gpu_vm's dma_resv lock when accessing the gpu_vm's evict list and external objects lists. However, there are drivers that need to access these lists without the dma_resv lock held, for example due to asynchronous state updates from within the dma_fence signalling critical path. In such cases, a spinlock can be used to protect manipulation of the lists. However, since higher level sleeping locks need to be taken for each list item while iterating over the lists, the items already iterated over need to be temporarily moved to a private list and the spinlock released while processing each item:

<!-- code block:: C

struct list_head still_in_list;

INIT_LIST_HEAD(&still_in_list);

spin_lock(&gpu_vm->list_lock);
do {
        struct list_head *entry = list_first_entry_or_null(&gpu_vm->list, head);

        if (!entry)
                break;

        list_move_tail(&entry->head, &still_in_list);
        list_entry_get_unless_zero(entry);
        spin_unlock(&gpu_vm->list_lock);

        process(entry);

        spin_lock(&gpu_vm->list_lock);
        list_entry_put(entry);
} while (true);

list_splice_tail(&still_in_list, &gpu_vm->list);
spin_unlock(&gpu_vm->list_lock); -->

Due to the additional locking and atomic operations, drivers that *can* avoid accessing the gpu_vm's list outside of the dma_resv lock might want to avoid also this iteration scheme. Particularly, if the driver anticipates a large number of list items. For lists where the anticipated number of list items is small, where list iteration doesn't happen very often or if there is a significant additional cost associated with each iteration, the atomic operation overhead associated with this type of iteration is, most likely, negligible. Note that if this scheme is used, it is necessary to make sure this list iteration is protected by an outer level lock or semaphore, since list items are temporarily pulled off the list while iterating, and it is also worth mentioning that the local list `still_in_list` should also be considered protected by the `gpu_vm->list_lock`, and it is thus possible that items can be removed also from the local list concurrently with list iteration.

Please refer to the [DRM GPUVM locking section](</kernel/hardware/gpu/drm-mm.md#rst-drm-gpuvm-locking>) and its internal `get_next_vm_bo_from_list()` function.

<a id="rst-userptr-gpu-vmas"></a>

## userptr gpu_vmas

A userptr gpu_vma is a gpu_vma that, instead of mapping a buffer object to a GPU virtual address range, directly maps a CPU mm range of anonymous- or file page-cache pages. A very simple approach would be to just pin the pages using pin_user_pages() at bind time and unpin them at unbind time, but this creates a Denial-Of-Service vector since a single user-space process would be able to pin down all of system memory, which is not desirable. (For special use-cases and assuming proper accounting pinning might still be a desirable feature, though). What we need to do in the general case is to obtain a reference to the desired pages, make sure we are notified using a MMU notifier just before the CPU mm unmaps the pages, dirty them if they are not mapped read-only to the GPU, and then drop the reference. When we are notified by the MMU notifier that CPU mm is about to drop the pages, we need to stop GPU access to the pages by waiting for VM idle in the MMU notifier and make sure that before the next time the GPU tries to access whatever is now present in the CPU mm range, we unmap the old pages from the GPU page tables and repeat the process of obtaining new page references. (See the [notifier example](<#rst-invalidation-example>) below). Note that when the core mm decides to laundry pages, we get such an unmap MMU notification and can mark the pages dirty again before the next GPU access. We also get similar MMU notifications for NUMA accounting which the GPU driver doesn't really need to care about, but so far it has proven difficult to exclude certain notifications.

Using a MMU notifier for device DMA (and other methods) is described in [the pin_user_pages() documentation](</kernel/internals/core-api/pin-user-pages.md#rst-mmu-notifier-registration-case>).

Now, the method of obtaining struct page references using get_user_pages() unfortunately can't be used under a dma_resv lock since that would violate the locking order of the dma_resv lock vs the mmap_lock that is grabbed when resolving a CPU pagefault. This means the gpu_vm's list of userptr gpu_vmas needs to be protected by an outer lock, which in our example below is the `gpu_vm->lock`.

The MMU interval seqlock for a userptr gpu_vma is used in the following way:



```C
// Exclusive locking mode here is strictly needed only if there are
// invalidated userptr gpu_vmas present, to avoid concurrent userptr
// revalidations of the same userptr gpu_vma.
down_write(&gpu_vm->lock);
retry:

// Note: mmu_interval_read_begin() blocks until there is no
// invalidation notifier running anymore.
seq = mmu_interval_read_begin(&gpu_vma->userptr_interval);
if (seq != gpu_vma->saved_seq) {
        obtain_new_page_pointers(&gpu_vma);
        dma_resv_lock(&gpu_vm->resv);
        add_gpu_vma_to_revalidate_list(&gpu_vma, &gpu_vm);
        dma_resv_unlock(&gpu_vm->resv);
        gpu_vma->saved_seq = seq;
}

// The usual revalidation goes here.

// Final userptr sequence validation may not happen before the
// submission dma_fence is added to the gpu_vm's resv, from the POW
// of the MMU invalidation notifier. Hence the
// userptr_notifier_lock that will make them appear atomic.

add_dependencies(&gpu_job, &gpu_vm->resv);
down_read(&gpu_vm->userptr_notifier_lock);
if (mmu_interval_read_retry(&gpu_vma->userptr_interval, gpu_vma->saved_seq)) {
       up_read(&gpu_vm->userptr_notifier_lock);
       goto retry;
}

job_dma_fence = gpu_submit(&gpu_job));

add_dma_fence(job_dma_fence, &gpu_vm->resv);

for_each_external_obj(gpu_vm, &obj)
       add_dma_fence(job_dma_fence, &obj->resv);

dma_resv_unlock_all_resv_locks();
up_read(&gpu_vm->userptr_notifier_lock);
up_write(&gpu_vm->lock);
```

The code between `mmu_interval_read_begin()` and the `mmu_interval_read_retry()` marks the read side critical section of what we call the `userptr_seqlock`. In reality, the gpu_vm's userptr gpu_vma list is looped through, and the check is done for *all* of its userptr gpu_vmas, although we only show a single one here.

The userptr gpu_vma MMU invalidation notifier might be called from reclaim context and, again, to avoid locking order violations, we can't take any dma_resv lock nor the gpu_vm-&gt;lock from within it.

<a id="rst-invalidation-example"></a>



```C
bool gpu_vma_userptr_invalidate(userptr_interval, cur_seq)
{
        // Make sure the exec function either sees the new sequence
        // and backs off or we wait for the dma-fence:

        down_write(&gpu_vm->userptr_notifier_lock);
        mmu_interval_set_seq(userptr_interval, cur_seq);
        up_write(&gpu_vm->userptr_notifier_lock);

        // At this point, the exec function can't succeed in
        // submitting a new job, because cur_seq is an invalid
        // sequence number and will always cause a retry. When all
        // invalidation callbacks, the mmu notifier core will flip
        // the sequence number to a valid one. However we need to
        // stop gpu access to the old pages here.

        dma_resv_wait_timeout(&gpu_vm->resv, DMA_RESV_USAGE_BOOKKEEP,
                              false, MAX_SCHEDULE_TIMEOUT);
        return true;
}
```

When this invalidation notifier returns, the GPU can no longer be accessing the old pages of the userptr gpu_vma and needs to redo the page-binding before a new GPU submission can succeed.

<a id="rst-efficient-userptr-gpu-vma-exec-function-iteration"></a>

### Efficient userptr gpu_vma exec_function iteration

If the gpu_vm's list of userptr gpu_vmas becomes large, it's inefficient to iterate through the complete lists of userptrs on each exec function to check whether each userptr gpu_vma's saved sequence number is stale. A solution to this is to put all *invalidated* userptr gpu_vmas on a separate gpu_vm list and only check the gpu_vmas present on this list on each exec function. This list will then lend itself very-well to the spinlock locking scheme that is [described in the spinlock iteration section](<#rst-spinlock-iteration>), since in the mmu notifier, where we add the invalidated gpu_vmas to the list, it's not possible to take any outer locks like the `gpu_vm->lock` or the `gpu_vm->resv` lock. Note that the `gpu_vm->lock` still needs to be taken while iterating to ensure the list is complete, as also mentioned in that section.

If using an invalidated userptr list like this, the retry check in the exec function trivially becomes a check for invalidated list empty.

<a id="rst-locking-at-bind-and-unbind-time"></a>

## Locking at bind and unbind time

At bind time, assuming a GEM object backed gpu_vma, each gpu_vma needs to be associated with a gpu_vm_bo and that gpu_vm_bo in turn needs to be added to the GEM object's gpu_vm_bo list, and possibly to the gpu_vm's external object list. This is referred to as *linking* the gpu_vma, and typically requires that the `gpu_vm->lock` and the `gem_object->gpuva_lock` are held. When unlinking a gpu_vma the same locks should be held, and that ensures that when iterating over ```gpu_vmas`, either under the ``gpu_vm->resv``` or the GEM object's dma_resv, that the gpu_vmas stay alive as long as the lock under which we iterate is not released. For userptr gpu_vmas it's similarly required that during vma destroy, the outer `gpu_vm->lock` is held, since otherwise when iterating over the invalidated userptr list as described in the previous section, there is nothing keeping those userptr gpu_vmas alive.

<a id="rst-locking-for-recoverable-page-fault-page-table-updates"></a>

## Locking for recoverable page-fault page-table updates

There are two important things we need to ensure with locking for recoverable page-faults:

- At the time we return pages back to the system / allocator for reuse, there should be no remaining GPU mappings and any GPU TLB must have been flushed.

- The unmapping and mapping of a gpu_vma must not race.

Since the unmapping (or zapping) of GPU ptes is typically taking place where it is hard or even impossible to take any outer level locks we must either introduce a new lock that is held at both mapping and unmapping time, or look at the locks we do hold at unmapping time and make sure that they are held also at mapping time. For userptr gpu_vmas, the `userptr_seqlock` is held in write mode in the mmu invalidation notifier where zapping happens. Hence, if the `userptr_seqlock` as well as the `gpu_vm->userptr_notifier_lock` is held in read mode during mapping, it will not race with the zapping. For GEM object backed gpu_vmas, zapping will take place under the GEM object's dma_resv and ensuring that the dma_resv is held also when populating the page-tables for any gpu_vma pointing to the GEM object, will similarly ensure we are race-free.

If any part of the mapping is performed asynchronously under a dma-fence with these locks released, the zapping will need to wait for that dma-fence to signal under the relevant lock before starting to modify the page-table.

Since modifying the page-table structure in a way that frees up page-table memory might also require outer level locks, the zapping of GPU ptes typically focuses only on zeroing page-table or page-directory entries and flushing TLB, whereas freeing of page-table memory is deferred to unbind or rebind time.

---

# drm/i915 Intel GFX Driver

_Peios Kernel / Hardware and drivers / Graphics_

> The drm/i915 driver supports all (with the exception of some very early models) integrated GFX chipsets with both Intel display and rendering blocks. This excludes a set of SoC platforms with an SGX rendering unit, those have basic support…

<a id="rst-drm-i915-intel-gfx-driver"></a>

The drm/i915 driver supports all (with the exception of some very early models) integrated GFX chipsets with both Intel display and rendering blocks. This excludes a set of SoC platforms with an SGX rendering unit, those have basic support through the gma500 drm driver.

<a id="rst-core-driver-infrastructure"></a>

## Core Driver Infrastructure

This section covers core driver infrastructure used by both the display and the GEM parts of the driver.

<a id="rst-runtime-power-management"></a>

### Runtime Power Management


The i915 driver supports dynamic enabling and disabling of entire hardware
blocks at runtime. This is especially important on the display side where
software is supposed to control many power gates manually on recent hardware,
since on the GT side a lot of the power management is done by the hardware.
But even there some manual control at the device level is required.

Since i915 supports a diverse set of platforms with a unified codebase and
hardware engineers just love to shuffle functionality around between power
domains there's a sizeable amount of indirection required. This file provides
generic functions to the driver for grabbing and releasing references for
abstract power domains. It then maps those to the actual power wells
present for a given platform.



#### <a id="c-intel_runtime_pm_get_raw"></a>`intel_runtime_pm_get_raw()`

```c
intel_wakeref_t intel_runtime_pm_get_raw(struct intel_runtime_pm *rpm)
```

grab a raw runtime pm reference

**Parameters**

- `struct intel_runtime_pm *rpm`: the intel_runtime_pm structure

**Description**

This is the unlocked version of `intel_display_power_is_enabled()` and should
only be used from error capture and recovery code where deadlocks are
possible.
This function grabs a device-level runtime pm reference (mostly used for
asynchronous PM management from display code) and ensures that it is powered
up. Raw references are not considered during wakelock assert checks.

Any runtime pm reference obtained by this function must have a symmetric
call to [`intel_runtime_pm_put_raw()`](#c-intel_runtime_pm_put_raw) to release the reference again.

**Return**

the wakeref cookie to pass to [`intel_runtime_pm_put_raw()`](#c-intel_runtime_pm_put_raw), evaluates
as True if the wakeref was acquired, or False otherwise.

#### <a id="c-intel_runtime_pm_get"></a>`intel_runtime_pm_get()`

```c
intel_wakeref_t intel_runtime_pm_get(struct intel_runtime_pm *rpm)
```

grab a runtime pm reference

**Parameters**

- `struct intel_runtime_pm *rpm`: the intel_runtime_pm structure

**Description**

This function grabs a device-level runtime pm reference (mostly used for GEM
code to ensure the GTT or GT is on) and ensures that it is powered up.

Any runtime pm reference obtained by this function must have a symmetric
call to [`intel_runtime_pm_put()`](#c-intel_runtime_pm_put) to release the reference again.

**Return**

the wakeref cookie to pass to [`intel_runtime_pm_put()`](#c-intel_runtime_pm_put)

#### <a id="c-__intel_runtime_pm_get_if_active"></a>`__intel_runtime_pm_get_if_active()`

```c
intel_wakeref_t __intel_runtime_pm_get_if_active(struct intel_runtime_pm *rpm, bool ignore_usecount)
```

grab a runtime pm reference if device is active

**Parameters**

- `struct intel_runtime_pm *rpm`: the intel_runtime_pm structure
- `bool ignore_usecount`: get a ref even if dev->power.usage_count is 0

**Description**

This function grabs a device-level runtime pm reference if the device is
already active and ensures that it is powered up. It is illegal to try
and access the HW should `intel_runtime_pm_get_if_active()` report failure.

If **ignore_usecount** is true, a reference will be acquired even if there is no
user requiring the device to be powered up (dev->power.usage_count == 0).
If the function returns false in this case then it's guaranteed that the
device's runtime suspend hook has been called already or that it will be
called (and hence it's also guaranteed that the device's runtime resume
hook will be called eventually).

Any runtime pm reference obtained by this function must have a symmetric
call to [`intel_runtime_pm_put()`](#c-intel_runtime_pm_put) to release the reference again.

**Return**

the wakeref cookie to pass to [`intel_runtime_pm_put()`](#c-intel_runtime_pm_put), evaluates
as True if the wakeref was acquired, or False otherwise.

#### <a id="c-intel_runtime_pm_get_noresume"></a>`intel_runtime_pm_get_noresume()`

```c
intel_wakeref_t intel_runtime_pm_get_noresume(struct intel_runtime_pm *rpm)
```

grab a runtime pm reference

**Parameters**

- `struct intel_runtime_pm *rpm`: the intel_runtime_pm structure

**Description**

This function grabs a device-level runtime pm reference.

It will _not_ resume the device but instead only get an extra wakeref.
Therefore it is only valid to call this functions from contexts where
the device is known to be active and with another wakeref previously hold.

Any runtime pm reference obtained by this function must have a symmetric
call to [`intel_runtime_pm_put()`](#c-intel_runtime_pm_put) to release the reference again.

**Return**

the wakeref cookie to pass to [`intel_runtime_pm_put()`](#c-intel_runtime_pm_put)

#### <a id="c-intel_runtime_pm_put_raw"></a>`intel_runtime_pm_put_raw()`

```c
void intel_runtime_pm_put_raw(struct intel_runtime_pm *rpm, intel_wakeref_t wref)
```

release a raw runtime pm reference

**Parameters**

- `struct intel_runtime_pm *rpm`: the intel_runtime_pm structure
- `intel_wakeref_t wref`: wakeref acquired for the reference that is being released

**Description**

This function drops the device-level runtime pm reference obtained by
[`intel_runtime_pm_get_raw()`](#c-intel_runtime_pm_get_raw) and might power down the corresponding
hardware block right away if this is the last reference.

#### <a id="c-intel_runtime_pm_put_unchecked"></a>`intel_runtime_pm_put_unchecked()`

```c
void intel_runtime_pm_put_unchecked(struct intel_runtime_pm *rpm)
```

release an unchecked runtime pm reference

**Parameters**

- `struct intel_runtime_pm *rpm`: the intel_runtime_pm structure

**Description**

This function drops the device-level runtime pm reference obtained by
[`intel_runtime_pm_get()`](#c-intel_runtime_pm_get) and might power down the corresponding
hardware block right away if this is the last reference.

This function exists only for historical reasons and should be avoided in
new code, as the correctness of its use cannot be checked. Always use
[`intel_runtime_pm_put()`](#c-intel_runtime_pm_put) instead.

#### <a id="c-intel_runtime_pm_put"></a>`intel_runtime_pm_put()`

```c
void intel_runtime_pm_put(struct intel_runtime_pm *rpm, intel_wakeref_t wref)
```

release a runtime pm reference

**Parameters**

- `struct intel_runtime_pm *rpm`: the intel_runtime_pm structure
- `intel_wakeref_t wref`: wakeref acquired for the reference that is being released

**Description**

This function drops the device-level runtime pm reference obtained by
[`intel_runtime_pm_get()`](#c-intel_runtime_pm_get) and might power down the corresponding
hardware block right away if this is the last reference.

#### <a id="c-intel_runtime_pm_enable"></a>`intel_runtime_pm_enable()`

```c
void intel_runtime_pm_enable(struct intel_runtime_pm *rpm)
```

enable runtime pm

**Parameters**

- `struct intel_runtime_pm *rpm`: the intel_runtime_pm structure

**Description**

This function enables runtime pm at the end of the driver load sequence.

Note that this function does currently not enable runtime pm for the
subordinate display power domains. That is done by
`intel_power_domains_enable()`.



#### <a id="c-intel_uncore_forcewake_get"></a>`intel_uncore_forcewake_get()`

```c
void intel_uncore_forcewake_get(struct intel_uncore *uncore, enum forcewake_domains fw_domains)
```

grab forcewake domain references

**Parameters**

- `struct intel_uncore *uncore`: the intel_uncore structure
- `enum forcewake_domains fw_domains`: forcewake domains to get reference on

**Description**

This function can be used get GT's forcewake domain references.
Normal register access will handle the forcewake domains automatically.
However if some sequence requires the GT to not power down a particular
forcewake domains this function should be called at the beginning of the
sequence. And subsequently the reference should be dropped by symmetric
call to `intel_unforce_forcewake_put()`. Usually caller wants all the domains
to be kept awake so the **fw_domains** would be then FORCEWAKE_ALL.

#### <a id="c-intel_uncore_forcewake_user_get"></a>`intel_uncore_forcewake_user_get()`

```c
void intel_uncore_forcewake_user_get(struct intel_uncore *uncore)
```

claim forcewake on behalf of userspace

**Parameters**

- `struct intel_uncore *uncore`: the intel_uncore structure

**Description**

This function is a wrapper around [`intel_uncore_forcewake_get()`](#c-intel_uncore_forcewake_get) to acquire
the GT powerwell and in the process disable our debugging for the
duration of userspace's bypass.

#### <a id="c-intel_uncore_forcewake_user_put"></a>`intel_uncore_forcewake_user_put()`

```c
void intel_uncore_forcewake_user_put(struct intel_uncore *uncore)
```

release forcewake on behalf of userspace

**Parameters**

- `struct intel_uncore *uncore`: the intel_uncore structure

**Description**

This function complements [`intel_uncore_forcewake_user_get()`](#c-intel_uncore_forcewake_user_get) and releases
the GT powerwell taken on behalf of the userspace bypass.

#### <a id="c-intel_uncore_forcewake_get__locked"></a>`intel_uncore_forcewake_get__locked()`

```c
void intel_uncore_forcewake_get__locked(struct intel_uncore *uncore, enum forcewake_domains fw_domains)
```

grab forcewake domain references

**Parameters**

- `struct intel_uncore *uncore`: the intel_uncore structure
- `enum forcewake_domains fw_domains`: forcewake domains to get reference on

**Description**

See [`intel_uncore_forcewake_get()`](#c-intel_uncore_forcewake_get). This variant places the onus
on the caller to explicitly handle the dev_priv->uncore.lock spinlock.

#### <a id="c-intel_uncore_forcewake_put"></a>`intel_uncore_forcewake_put()`

```c
void intel_uncore_forcewake_put(struct intel_uncore *uncore, enum forcewake_domains fw_domains)
```

release a forcewake domain reference

**Parameters**

- `struct intel_uncore *uncore`: the intel_uncore structure
- `enum forcewake_domains fw_domains`: forcewake domains to put references

**Description**

This function drops the device-level forcewakes for specified
domains obtained by [`intel_uncore_forcewake_get()`](#c-intel_uncore_forcewake_get).

#### <a id="c-intel_uncore_forcewake_flush"></a>`intel_uncore_forcewake_flush()`

```c
void intel_uncore_forcewake_flush(struct intel_uncore *uncore, enum forcewake_domains fw_domains)
```

flush the delayed release

**Parameters**

- `struct intel_uncore *uncore`: the intel_uncore structure
- `enum forcewake_domains fw_domains`: forcewake domains to flush

#### <a id="c-intel_uncore_forcewake_put__locked"></a>`intel_uncore_forcewake_put__locked()`

```c
void intel_uncore_forcewake_put__locked(struct intel_uncore *uncore, enum forcewake_domains fw_domains)
```

release forcewake domain references

**Parameters**

- `struct intel_uncore *uncore`: the intel_uncore structure
- `enum forcewake_domains fw_domains`: forcewake domains to put references

**Description**

See [`intel_uncore_forcewake_put()`](#c-intel_uncore_forcewake_put). This variant places the onus
on the caller to explicitly handle the dev_priv->uncore.lock spinlock.

#### <a id="c-__intel_wait_for_register_fw"></a>`__intel_wait_for_register_fw()`

```c
int __intel_wait_for_register_fw(struct intel_uncore *uncore, i915_reg_t reg, u32 mask, u32 value, unsigned int fast_timeout_us, unsigned int slow_timeout_ms, u32 *out_value)
```

wait until register matches expected state

**Parameters**

- `struct intel_uncore *uncore`: the struct intel_uncore
- `i915_reg_t reg`: the register to read
- `u32 mask`: mask to apply to register value
- `u32 value`: expected value
- `unsigned int fast_timeout_us`: fast timeout in microsecond for atomic/tight wait
- `unsigned int slow_timeout_ms`: slow timeout in millisecond
- `u32 *out_value`: optional placeholder to hold registry value

**Description**

This routine waits until the target register **reg** contains the expected
**value** after applying the **mask**, i.e. it waits until

```text
(intel_uncore_read_fw(uncore, reg) & mask) == value
```

Otherwise, the wait will timeout after **slow_timeout_ms** milliseconds.
For atomic context **slow_timeout_ms** must be zero and **fast_timeout_us**
must be not larger than 20,0000 microseconds.

Note that this routine assumes the caller holds forcewake asserted, it is
not suitable for very long waits. See `intel_wait_for_register()` if you
wish to wait without holding forcewake for the duration (i.e. you expect
the wait to be slow).

**Return**

0 if the register matches the desired condition, or -ETIMEDOUT.

#### <a id="c-__intel_wait_for_register"></a>`__intel_wait_for_register()`

```c
int __intel_wait_for_register(struct intel_uncore *uncore, i915_reg_t reg, u32 mask, u32 value, unsigned int fast_timeout_us, unsigned int slow_timeout_ms, u32 *out_value)
```

wait until register matches expected state

**Parameters**

- `struct intel_uncore *uncore`: the struct intel_uncore
- `i915_reg_t reg`: the register to read
- `u32 mask`: mask to apply to register value
- `u32 value`: expected value
- `unsigned int fast_timeout_us`: fast timeout in microsecond for atomic/tight wait
- `unsigned int slow_timeout_ms`: slow timeout in millisecond
- `u32 *out_value`: optional placeholder to hold registry value

**Description**

This routine waits until the target register **reg** contains the expected
**value** after applying the **mask**, i.e. it waits until

```text
(intel_uncore_read(uncore, reg) & mask) == value
```

Otherwise, the wait will timeout after **timeout_ms** milliseconds.

**Return**

0 if the register matches the desired condition, or -ETIMEDOUT.

#### <a id="c-intel_uncore_forcewake_for_reg"></a>`intel_uncore_forcewake_for_reg()`

```c
enum forcewake_domains intel_uncore_forcewake_for_reg(struct intel_uncore *uncore, i915_reg_t reg, unsigned int op)
```

which forcewake domains are needed to access a register

**Parameters**

- `struct intel_uncore *uncore`: pointer to struct intel_uncore
- `i915_reg_t reg`: register in question
- `unsigned int op`: operation bitmask of FW_REG_READ and/or FW_REG_WRITE

**Description**

Returns a set of forcewake domains required to be taken with for example
intel_uncore_forcewake_get for the specified register to be accessible in the
specified mode (read, write or read/write) with raw mmio accessors.

**NOTE**

On Gen6 and Gen7 write forcewake domain (FORCEWAKE_RENDER) requires the
callers to do FIFO management on their own or risk losing writes.


<a id="rst-interrupt-handling"></a>

### Interrupt Handling


These functions provide the basic support for enabling and disabling the
interrupt handling support. There's a lot more functionality in i915_irq.c
and related files, but that will be described in separate chapters.



#### <a id="c-intel_irq_init"></a>`intel_irq_init()`

```c
void intel_irq_init(struct drm_i915_private *dev_priv)
```

initializes irq support

**Parameters**

- `struct drm_i915_private *dev_priv`: i915 device instance

**Description**

This function initializes all the irq support including work items, timers
and all the vtables. It does not setup the interrupt itself though.



#### <a id="c-intel_irq_suspend"></a>`intel_irq_suspend()`

```c
void intel_irq_suspend(struct drm_i915_private *i915)
```

Suspend interrupts

**Parameters**

- `struct drm_i915_private *i915`: i915 device instance

**Description**

This function is used to disable interrupts at runtime.



#### <a id="c-intel_irq_resume"></a>`intel_irq_resume()`

```c
void intel_irq_resume(struct drm_i915_private *i915)
```

Resume interrupts

**Parameters**

- `struct drm_i915_private *i915`: i915 device instance

**Description**

This function is used to enable interrupts at runtime.


<a id="rst-intel-gvt-g-guest-support-vgpu"></a>

### Intel GVT-g Guest Support(vGPU)


Intel GVT-g is a graphics virtualization technology which shares the
GPU among multiple virtual machines on a time-sharing basis. Each
virtual machine is presented a virtual GPU (vGPU), which has equivalent
features as the underlying physical GPU (pGPU), so i915 driver can run
seamlessly in a virtual machine. This file provides vGPU specific
optimizations when running in a virtual machine, to reduce the complexity
of vGPU emulation and to improve the overall performance.

A primary function introduced here is so-called "address space ballooning"
technique. Intel GVT-g partitions global graphics memory among multiple VMs,
so each VM can directly access a portion of the memory without hypervisor's
intervention, e.g. filling textures or queuing commands. However with the
partitioning an unmodified i915 driver would assume a smaller graphics
memory starting from address ZERO, then requires vGPU emulation module to
translate the graphics address between 'guest view' and 'host view', for
all registers and command opcodes which contain a graphics memory address.
To reduce the complexity, Intel GVT-g introduces "address space ballooning",
by telling the exact partitioning knowledge to each guest i915 driver, which
then reserves and prevents non-allocated portions from allocation. Thus vGPU
emulation module only needs to scan and validate graphics addresses without
complexity of address translation.



#### <a id="c-intel_vgpu_detect"></a>`intel_vgpu_detect()`

```c
void intel_vgpu_detect(struct drm_i915_private *dev_priv)
```

detect virtual GPU

**Parameters**

- `struct drm_i915_private *dev_priv`: i915 device private

**Description**

This function is called at the initialization stage, to detect whether
running on a vGPU.

#### <a id="c-intel_vgt_deballoon"></a>`intel_vgt_deballoon()`

```c
void intel_vgt_deballoon(struct i915_ggtt *ggtt)
```

deballoon reserved graphics address trunks

**Parameters**

- `struct i915_ggtt *ggtt`: the global GGTT from which we reserved earlier

**Description**

This function is called to deallocate the ballooned-out graphic memory, when
driver is unloaded or when ballooning fails.

#### <a id="c-intel_vgt_balloon"></a>`intel_vgt_balloon()`

```c
int intel_vgt_balloon(struct i915_ggtt *ggtt)
```

balloon out reserved graphics address trunks

**Parameters**

- `struct i915_ggtt *ggtt`: the global GGTT from which to reserve

**Description**

This function is called at the initialization stage, to balloon out the
graphic address space allocated to other vGPUs, by marking these spaces as
reserved. The ballooning related knowledge(starting address and size of
the mappable/unmappable graphic memory) is described in the vgt_if structure
in a reserved mmio range.

To give an example, the drawing below depicts one typical scenario after
ballooning. Here the vGPU1 has 2 pieces of graphic address spaces ballooned
out each for the mappable and the non-mappable part. From the vGPU1 point of
view, the total size is the same as the physical one, with the start address
of its graphic space being zero. Yet there are some portions ballooned out(
the shadow part, which are marked as reserved by drm allocator). From the
host point of view, the graphic address space is partitioned by multiple
vGPUs in different VMs.

```text
                       vGPU1 view         Host view
            0 ------> +-----------+     +-----------+
              ^       |###########|     |   vGPU3   |
              |       |###########|     +-----------+
              |       |###########|     |   vGPU2   |
              |       +-----------+     +-----------+
       mappable GM    | available | ==> |   vGPU1   |
              |       +-----------+     +-----------+
              |       |###########|     |           |
              v       |###########|     |   Host    |
              +=======+===========+     +===========+
              ^       |###########|     |   vGPU3   |
              |       |###########|     +-----------+
              |       |###########|     |   vGPU2   |
              |       +-----------+     +-----------+
     unmappable GM    | available | ==> |   vGPU1   |
              |       +-----------+     +-----------+
              |       |###########|     |           |
              |       |###########|     |   Host    |
              v       |###########|     |           |
total GM size ------> +-----------+     +-----------+
```

**Return**

zero on success, non-zero if configuration invalid or ballooning failed


<a id="rst-intel-gvt-g-host-support-vgpu-device-model"></a>

### Intel GVT-g Host Support(vGPU device model)


Intel GVT-g is a graphics virtualization technology which shares the
GPU among multiple virtual machines on a time-sharing basis. Each
virtual machine is presented a virtual GPU (vGPU), which has equivalent
features as the underlying physical GPU (pGPU), so i915 driver can run
seamlessly in a virtual machine.

To virtualize GPU resources GVT-g driver depends on hypervisor technology
e.g KVM/VFIO/mdev, Xen, etc. to provide resource access trapping capability
and be virtualized within GVT-g device module. More architectural design
doc is available on https://github.com/intel/gvt-linux/wiki.



#### <a id="c-intel_gvt_init"></a>`intel_gvt_init()`

```c
int intel_gvt_init(struct drm_i915_private *dev_priv)
```

initialize GVT components

**Parameters**

- `struct drm_i915_private *dev_priv`: drm i915 private data

**Description**

This function is called at the initialization stage to create a GVT device.

**Return**

Zero on success, negative error code if failed.

#### <a id="c-intel_gvt_driver_remove"></a>`intel_gvt_driver_remove()`

```c
void intel_gvt_driver_remove(struct drm_i915_private *dev_priv)
```

cleanup GVT components when i915 driver is unbinding

**Parameters**

- `struct drm_i915_private *dev_priv`: drm i915 private *

**Description**

This function is called at the i915 driver unloading stage, to shutdown
GVT components and release the related resources.

#### <a id="c-intel_gvt_resume"></a>`intel_gvt_resume()`

```c
void intel_gvt_resume(struct drm_i915_private *dev_priv)
```

GVT resume routine wrapper

**Parameters**

- `struct drm_i915_private *dev_priv`: drm i915 private *

**Description**

This function is called at the i915 driver resume stage to restore required
HW status for GVT so that vGPU can continue running after resumed.


<a id="rst-workarounds"></a>

### Workarounds


Hardware workarounds are register programming documented to be executed in
the driver that fall outside of the normal programming sequences for a
platform. There are some basic categories of workarounds, depending on
how/when they are applied:

- Context workarounds: workarounds that touch registers that are
  saved/restored to/from the HW context image. The list is emitted (via Load
  Register Immediate commands) once when initializing the device and saved in
  the default context. That default context is then used on every context
  creation to have a "primed golden context", i.e. a context image that
  already contains the changes needed to all the registers.

  Context workarounds should be implemented in the \*`_ctx_workarounds_init()`
  variants respective to the targeted platforms.

- Engine workarounds: the list of these WAs is applied whenever the specific
  engine is reset. It's also possible that a set of engine classes share a
  common power domain and they are reset together. This happens on some
  platforms with render and compute engines. In this case (at least) one of
  them need to keeep the workaround programming: the approach taken in the
  driver is to tie those workarounds to the first compute/render engine that
  is registered.  When executing with GuC submission, engine resets are
  outside of kernel driver control, hence the list of registers involved in
  written once, on engine initialization, and then passed to GuC, that
  saves/restores their values before/after the reset takes place. See
  `drivers/gpu/drm/i915/gt/uc/intel_guc_ads.c` for reference.

  Workarounds for registers specific to RCS and CCS should be implemented in
  `rcs_engine_wa_init()` and `ccs_engine_wa_init()`, respectively; those for
  registers belonging to BCS, VCS or VECS should be implemented in
  `xcs_engine_wa_init()`. Workarounds for registers not belonging to a specific
  engine's MMIO range but that are part of of the common RCS/CCS reset domain
  should be implemented in `general_render_compute_wa_init()`. The settings
  about the CCS load balancing should be added in `ccs_engine_wa_mode()`.

- GT workarounds: the list of these WAs is applied whenever these registers
  revert to their default values: on GPU reset, suspend/resume \[1\]_, etc.

  GT workarounds should be implemented in the \*`_gt_workarounds_init()`
  variants respective to the targeted platforms.

- Register whitelist: some workarounds need to be implemented in userspace,
  but need to touch privileged registers. The whitelist in the kernel
  instructs the hardware to allow the access to happen. From the kernel side,
  this is just a special case of a MMIO workaround (as we write the list of
  these to/be-whitelisted registers to some special HW registers).

  Register whitelisting should be done in the \*`_whitelist_build()` variants
  respective to the targeted platforms.

- Workaround batchbuffers: buffers that get executed automatically by the
  hardware on every HW context restore. These buffers are created and
  programmed in the default context so the hardware always go through those
  programming sequences when switching contexts. The support for workaround
  batchbuffers is enabled these hardware mechanisms:

  1. INDIRECT_CTX: A batchbuffer and an offset are provided in the default
     context, pointing the hardware to jump to that location when that offset
     is reached in the context restore. Workaround batchbuffer in the driver
     currently uses this mechanism for all platforms.

  1. BB_PER_CTX_PTR: A batchbuffer is provided in the default context,
     pointing the hardware to a buffer to continue executing after the
     engine registers are restored in a context restore sequence. This is
     currently not used in the driver.

- Other:  There are WAs that, due to their nature, cannot be applied from a
  central place. Those are peppered around the rest of the code, as needed.
  Workarounds related to the display IP are the main example.


<a id="rst-display-hardware-handling"></a>

## Display Hardware Handling

This section covers everything related to the display hardware including the mode setting infrastructure, plane, sprite and cursor handling and display, output probing and related topics.

<a id="rst-mode-setting-infrastructure"></a>

### Mode Setting Infrastructure

The i915 driver is thus far the only DRM driver which doesn't use the common DRM helper code to implement mode setting sequences. Thus it has its own tailor-made infrastructure for executing a display configuration change.

<a id="rst-frontbuffer-tracking"></a>

### Frontbuffer Tracking


Many features require us to track changes to the currently active
frontbuffer, especially rendering targeted at the frontbuffer.

To be able to do so we track frontbuffers using a bitmask for all possible
frontbuffer slots through [`intel_frontbuffer_track()`](#c-intel_frontbuffer_track). The functions in this
file are then called when the contents of the frontbuffer are invalidated,
when frontbuffer rendering has stopped again to flush out all the changes
and when the frontbuffer is exchanged with a flip. Subsystems interested in
frontbuffer changes (e.g. PSR, FBC, DRRS) should directly put their callbacks
into the relevant places and filter for the frontbuffer slots that they are
interested int.

On a high level there are two types of powersaving features. The first one
work like a special cache (FBC and PSR) and are interested when they should
stop caching and when to restart caching. This is done by placing callbacks
into the invalidate and the flush functions: At invalidate the caching must
be stopped and at flush time it can be restarted. And maybe they need to know
when the frontbuffer changes (e.g. when the hw doesn't initiate an invalidate
and flush on its own) which can be achieved with placing callbacks into the
flip functions.

The other type of display power saving feature only cares about busyness
(e.g. DRRS). In that case all three (invalidate, flush and flip) indicate
busyness. There is no direct way to detect idleness. Instead an idle timer
work delayed work should be started from the flush and flip functions and
cancelled as soon as busyness is detected.



#### <a id="c-intel_frontbuffer_invalidate"></a>`intel_frontbuffer_invalidate()`

```c
bool intel_frontbuffer_invalidate(struct intel_frontbuffer *front, enum fb_op_origin origin)
```

invalidate frontbuffer object

**Parameters**

- `struct intel_frontbuffer *front`: GEM object to invalidate
- `enum fb_op_origin origin`: which operation caused the invalidation

**Description**

This function gets called every time rendering on the given object starts and
frontbuffer caching (fbc, low refresh rate for DRRS, panel self refresh) must
be invalidated. For ORIGIN_CS any subsequent invalidation will be delayed
until the rendering completes or a flip on this frontbuffer plane is
scheduled.

#### <a id="c-intel_frontbuffer_flush"></a>`intel_frontbuffer_flush()`

```c
void intel_frontbuffer_flush(struct intel_frontbuffer *front, enum fb_op_origin origin)
```

flush frontbuffer object

**Parameters**

- `struct intel_frontbuffer *front`: GEM object to flush
- `enum fb_op_origin origin`: which operation caused the flush

**Description**

This function gets called every time rendering on the given object has
completed and frontbuffer caching can be started again.



#### <a id="c-frontbuffer_flush"></a>`frontbuffer_flush()`

```c
void frontbuffer_flush(struct intel_display *display, unsigned int frontbuffer_bits, enum fb_op_origin origin)
```

flush frontbuffer

**Parameters**

- `struct intel_display *display`: display device
- `unsigned int frontbuffer_bits`: frontbuffer plane tracking bits
- `enum fb_op_origin origin`: which operation caused the flush

**Description**

This function gets called every time rendering on the given planes has
completed and frontbuffer caching can be started again. Flushes will get
delayed if they're blocked by some outstanding asynchronous rendering.

Can be called without any locks held.

#### <a id="c-intel_frontbuffer_flip"></a>`intel_frontbuffer_flip()`

```c
void intel_frontbuffer_flip(struct intel_display *display, unsigned frontbuffer_bits)
```

synchronous frontbuffer flip

**Parameters**

- `struct intel_display *display`: display device
- `unsigned frontbuffer_bits`: frontbuffer plane tracking bits

**Description**

This function gets called after scheduling a flip on **obj**. This is for
synchronous plane updates which will happen on the next vblank and which will
not get delayed by pending gpu rendering.

Can be called without any locks held.

#### <a id="c-intel_frontbuffer_queue_flush"></a>`intel_frontbuffer_queue_flush()`

```c
void intel_frontbuffer_queue_flush(struct intel_frontbuffer *front)
```

queue flushing frontbuffer object

**Parameters**

- `struct intel_frontbuffer *front`: GEM object to flush

**Description**

This function is targeted for our dirty callback for queueing flush when
dma fence is signals

#### <a id="c-intel_frontbuffer_track"></a>`intel_frontbuffer_track()`

```c
void intel_frontbuffer_track(struct intel_frontbuffer *old, struct intel_frontbuffer *new, unsigned int frontbuffer_bits)
```

update frontbuffer tracking

**Parameters**

- `struct intel_frontbuffer *old`: current buffer for the frontbuffer slots
- `struct intel_frontbuffer *new`: new buffer for the frontbuffer slots
- `unsigned int frontbuffer_bits`: bitmask of frontbuffer slots

**Description**

This updates the frontbuffer tracking bits **frontbuffer_bits** by clearing them
from **old** and setting them in **new**. Both **old** and **new** can be NULL.


<a id="rst-display-fifo-underrun-reporting"></a>

### Display FIFO Underrun Reporting


The i915 driver checks for display fifo underruns using the interrupt signals
provided by the hardware. This is enabled by default and fairly useful to
debug display issues, especially watermark settings.

If an underrun is detected this is logged into dmesg. To avoid flooding logs
and occupying the cpu underrun interrupts are disabled after the first
occurrence until the next modeset on a given pipe.

Note that underrun detection on gmch platforms is a bit more ugly since there
is no interrupt (despite that the signalling bit is in the PIPESTAT pipe
interrupt register). Also on some other platforms underrun interrupts are
shared, which means that if we detect an underrun we need to disable underrun
reporting on all pipes.

The code also supports underrun detection on the PCH transcoder.



#### <a id="c-intel_set_cpu_fifo_underrun_reporting"></a>`intel_set_cpu_fifo_underrun_reporting()`

```c
bool intel_set_cpu_fifo_underrun_reporting(struct intel_display *display, enum pipe pipe, bool enable)
```

set cpu fifo underrun reporting state

**Parameters**

- `struct intel_display *display`: display device instance
- `enum pipe pipe`: (CPU) pipe to set state for
- `bool enable`: whether underruns should be reported or not

**Description**

This function sets the fifo underrun state for **pipe**. It is used in the
modeset code to avoid false positives since on many platforms underruns are
expected when disabling or enabling the pipe.

Notice that on some platforms disabling underrun reports for one pipe
disables for all due to shared interrupts. Actual reporting is still per-pipe
though.

Returns the previous state of underrun reporting.

#### <a id="c-intel_set_pch_fifo_underrun_reporting"></a>`intel_set_pch_fifo_underrun_reporting()`

```c
bool intel_set_pch_fifo_underrun_reporting(struct intel_display *display, enum pipe pch_transcoder, bool enable)
```

set PCH fifo underrun reporting state

**Parameters**

- `struct intel_display *display`: display device instance
- `enum pipe pch_transcoder`: the PCH transcoder (same as pipe on IVB and older)
- `bool enable`: whether underruns should be reported or not

**Description**

This function makes us disable or enable PCH fifo underruns for a specific
PCH transcoder. Notice that on some PCHs (e.g. CPT/PPT), disabling FIFO
underrun reporting for one transcoder may also disable all the other PCH
error interruts for the other transcoders, due to the fact that there's just
one interrupt mask/enable bit for all the transcoders.

Returns the previous state of underrun reporting.

#### <a id="c-intel_cpu_fifo_underrun_irq_handler"></a>`intel_cpu_fifo_underrun_irq_handler()`

```c
void intel_cpu_fifo_underrun_irq_handler(struct intel_display *display, enum pipe pipe)
```

handle CPU fifo underrun interrupt

**Parameters**

- `struct intel_display *display`: display device instance
- `enum pipe pipe`: (CPU) pipe to set state for

**Description**

This handles a CPU fifo underrun interrupt, generating an underrun warning
into dmesg if underrun reporting is enabled and then disables the underrun
interrupt to avoid an irq storm.

#### <a id="c-intel_pch_fifo_underrun_irq_handler"></a>`intel_pch_fifo_underrun_irq_handler()`

```c
void intel_pch_fifo_underrun_irq_handler(struct intel_display *display, enum pipe pch_transcoder)
```

handle PCH fifo underrun interrupt

**Parameters**

- `struct intel_display *display`: display device instance
- `enum pipe pch_transcoder`: the PCH transcoder (same as pipe on IVB and older)

**Description**

This handles a PCH fifo underrun interrupt, generating an underrun warning
into dmesg if underrun reporting is enabled and then disables the underrun
interrupt to avoid an irq storm.

#### <a id="c-intel_check_cpu_fifo_underruns"></a>`intel_check_cpu_fifo_underruns()`

```c
void intel_check_cpu_fifo_underruns(struct intel_display *display)
```

check for CPU fifo underruns immediately

**Parameters**

- `struct intel_display *display`: display device instance

**Description**

Check for CPU fifo underruns immediately. Useful on IVB/HSW where the shared
error interrupt may have been disabled, and so CPU fifo underruns won't
necessarily raise an interrupt, and on GMCH platforms where underruns never
raise an interrupt.

#### <a id="c-intel_check_pch_fifo_underruns"></a>`intel_check_pch_fifo_underruns()`

```c
void intel_check_pch_fifo_underruns(struct intel_display *display)
```

check for PCH fifo underruns immediately

**Parameters**

- `struct intel_display *display`: display device instance

**Description**

Check for PCH fifo underruns immediately. Useful on CPT/PPT where the shared
error interrupt may have been disabled, and so PCH fifo underruns won't
necessarily raise an interrupt.


<a id="rst-plane-configuration"></a>

### Plane Configuration

This section covers plane configuration and composition with the primary plane, sprites, cursors and overlays. This includes the infrastructure to do atomic vsync'ed updates of all this state and also tightly coupled topics like watermark setup and computation, framebuffer compression and panel self refresh.

<a id="rst-atomic-plane-helpers"></a>

### Atomic Plane Helpers


The functions here are used by the atomic plane helper functions to
implement legacy plane updates (i.e., drm_plane->`update_plane()` and
drm_plane->`disable_plane()`).  This allows plane updates to use the
atomic state infrastructure and perform plane updates as separate
prepare/check/commit/cleanup steps.



#### <a id="c-intel_plane_destroy"></a>`intel_plane_destroy()`

```c
void intel_plane_destroy(struct drm_plane *plane)
```

destroy a plane

**Parameters**

- `struct drm_plane *plane`: plane to destroy

**Description**

Common destruction function for all types of planes (primary, cursor,
sprite).

#### <a id="c-intel_plane_duplicate_state"></a>`intel_plane_duplicate_state()`

```c
struct drm_plane_state * intel_plane_duplicate_state(struct drm_plane *plane)
```

duplicate plane state

**Parameters**

- `struct drm_plane *plane`: drm plane

**Description**

Allocates and returns a copy of the plane state (both common and
Intel-specific) for the specified plane.

**Return**

The newly allocated plane state, or NULL on failure.

#### <a id="c-intel_plane_destroy_state"></a>`intel_plane_destroy_state()`

```c
void intel_plane_destroy_state(struct drm_plane *plane, struct drm_plane_state *state)
```

destroy plane state

**Parameters**

- `struct drm_plane *plane`: drm plane
- `struct drm_plane_state *state`: state object to destroy

**Description**

Destroys the plane state (both common and Intel-specific) for the
specified plane.

#### <a id="c-intel_prepare_plane_fb"></a>`intel_prepare_plane_fb()`

```c
int intel_prepare_plane_fb(struct drm_plane *_plane, struct drm_plane_state *_new_plane_state)
```

Prepare fb for usage on plane

**Parameters**

- `struct drm_plane *_plane`: drm plane to prepare for
- `struct drm_plane_state *_new_plane_state`: the plane state being prepared

**Description**

Prepares a framebuffer for usage on a display plane.  Generally this
involves pinning the underlying object and updating the frontbuffer tracking
bits.  Some older platforms need special physical address handling for
cursor planes.

Returns 0 on success, negative error code on failure.

#### <a id="c-intel_cleanup_plane_fb"></a>`intel_cleanup_plane_fb()`

```c
void intel_cleanup_plane_fb(struct drm_plane *plane, struct drm_plane_state *_old_plane_state)
```

Cleans up an fb after plane use

**Parameters**

- `struct drm_plane *plane`: drm plane to clean up for
- `struct drm_plane_state *_old_plane_state`: the state from the previous modeset

**Description**

Cleans up a framebuffer that has just been removed from a plane.


<a id="rst-asynchronous-page-flip"></a>

### Asynchronous Page Flip


Asynchronous page flip is the implementation for the DRM_MODE_PAGE_FLIP_ASYNC
flag. Currently async flip is only supported via the drmModePageFlip IOCTL.
Correspondingly, support is currently added for primary plane only.

Async flip can only change the plane surface address, so anything else
changing is rejected from the `intel_async_flip_check_hw()` function.
Once this check is cleared, flip done interrupt is enabled using
the `intel_crtc_enable_flip_done()` function.

As soon as the surface address register is written, flip done interrupt is
generated and the requested events are sent to the userspace in the interrupt
handler itself. The timestamp and sequence sent during the flip done event
correspond to the last vblank and have no relation to the actual time when
the flip done event was sent.


<a id="rst-output-probing"></a>

### Output Probing

This section covers output probing and related infrastructure like the hotplug interrupt storm detection and mitigation code. Note that the i915 driver still uses most of the common DRM helper code for output probing, so those sections fully apply.

<a id="rst-hotplug"></a>

### Hotplug


Simply put, hotplug occurs when a display is connected to or disconnected
from the system. However, there may be adapters and docking stations and
Display Port short pulses and MST devices involved, complicating matters.

Hotplug in i915 is handled in many different levels of abstraction.

The platform dependent interrupt handling code in i915_irq.c enables,
disables, and does preliminary handling of the interrupts. The interrupt
handlers gather the hotplug detect (HPD) information from relevant registers
into a platform independent mask of hotplug pins that have fired.

The platform independent interrupt handler [`intel_hpd_irq_handler()`](#c-intel_hpd_irq_handler) in
intel_hotplug.c does hotplug irq storm detection and mitigation, and passes
further processing to appropriate bottom halves (Display Port specific and
regular hotplug).

The Display Port work function `i915_digport_work_func()` calls into
`intel_dp_hpd_pulse()` via hooks, which handles DP short pulses and DP MST long
pulses, with failures and non-MST long pulses triggering regular hotplug
processing on the connector.

The regular hotplug work function `i915_hotplug_work_func()` calls connector
detect hooks, and, if connector status changes, triggers sending of hotplug
uevent to userspace via [`drm_kms_helper_hotplug_event()`](/kernel/hardware/gpu/drm-kms-helpers.md#c-drm_kms_helper_hotplug_event).

Finally, the userspace is responsible for triggering a modeset upon receiving
the hotplug uevent, disabling or enabling the crtc as needed.

The hotplug interrupt storm detection and mitigation code keeps track of the
number of interrupts per hotplug pin per a period of time, and if the number
of interrupts exceeds a certain threshold, the interrupt is disabled for a
while before being re-enabled. The intention is to mitigate issues raising
from broken hardware triggering massive amounts of interrupts and grinding
the system to a halt.

Current implementation expects that hotplug interrupt storm will not be
seen when display port sink is connected, hence on platforms whose DP
callback is handled by i915_digport_work_func reenabling of hpd is not
performed (it was never expected to be disabled in the first place ;) )
this is specific to DP sinks handled by this routine and any other display
such as HDMI or DVI enabled on the same port will have proper logic since
it will use i915_hotplug_work_func where this logic is handled.



#### <a id="c-intel_hpd_pin_default"></a>`intel_hpd_pin_default()`

```c
enum hpd_pin intel_hpd_pin_default(enum port port)
```

return default pin associated with certain port.

**Parameters**

- `enum port port`: the hpd port to get associated pin

**Description**

It is only valid and used by digital port encoder.

Return pin that is associatade with **port**.

#### <a id="c-intel_hpd_irq_storm_detect"></a>`intel_hpd_irq_storm_detect()`

```c
bool intel_hpd_irq_storm_detect(struct intel_display *display, enum hpd_pin pin, bool long_hpd)
```

gather stats and detect HPD IRQ storm on a pin

**Parameters**

- `struct intel_display *display`: display device
- `enum hpd_pin pin`: the pin to gather stats on
- `bool long_hpd`: whether the HPD IRQ was long or short

**Description**

Gather stats about HPD IRQs from the specified **pin**, and detect IRQ
storms. Only the pin specific stats and state are changed, the caller is
responsible for further action.

The number of IRQs that are allowed within **HPD_STORM_DETECT_PERIOD** is
stored in **display->hotplug.hpd_storm_threshold** which defaults to
**HPD_STORM_DEFAULT_THRESHOLD**. Long IRQs count as +10 to this threshold, and
short IRQs count as +1. If this threshold is exceeded, it's considered an
IRQ storm and the IRQ state is set to **HPD_MARK_DISABLED**.

By default, most systems will only count long IRQs towards
`display->hotplug`.hpd_storm_threshold. However, some older systems also
suffer from short IRQ storms and must also track these. Because short IRQ
storms are naturally caused by sideband interactions with DP MST devices,
short IRQ detection is only enabled for systems without DP MST support.
Systems which are new enough to support DP MST are far less likely to
suffer from IRQ storms at all, so this is fine.

The HPD threshold can be controlled through i915_hpd_storm_ctl in debugfs,
and should only be adjusted for automated hotplug testing.

Return true if an IRQ storm was detected on **pin**.

#### <a id="c-intel_hpd_trigger_irq"></a>`intel_hpd_trigger_irq()`

```c
void intel_hpd_trigger_irq(struct intel_digital_port *dig_port)
```

trigger an hpd irq event for a port

**Parameters**

- `struct intel_digital_port *dig_port`: digital port

**Description**

Trigger an HPD interrupt event for the given port, emulating a short pulse
generated by the sink, and schedule the dig port work to handle it.

#### <a id="c-intel_hpd_irq_handler"></a>`intel_hpd_irq_handler()`

```c
void intel_hpd_irq_handler(struct intel_display *display, u32 pin_mask, u32 long_mask)
```

main hotplug irq handler

**Parameters**

- `struct intel_display *display`: display device
- `u32 pin_mask`: a mask of hpd pins that have triggered the irq
- `u32 long_mask`: a mask of hpd pins that may be long hpd pulses

**Description**

This is the main hotplug irq handler for all platforms. The platform specific
irq handlers call the platform specific hotplug irq handlers, which read and
decode the appropriate registers into bitmasks about hpd pins that have
triggered (**pin_mask**), and which of those pins may be long pulses
(**long_mask**). The **long_mask** is ignored if the port corresponding to the pin
is not a digital port.

Here, we do hotplug irq storm detection and mitigation, and pass further
processing to appropriate bottom halves.

#### <a id="c-intel_hpd_init"></a>`intel_hpd_init()`

```c
void intel_hpd_init(struct intel_display *display)
```

initializes and enables hpd support

**Parameters**

- `struct intel_display *display`: display device instance

**Description**

This function enables the hotplug support. It requires that interrupts have
already been enabled with `intel_irq_init_hw()`. From this point on hotplug and
poll request can run concurrently to other code, so locking rules must be
obeyed.

This is a separate step from interrupt enabling to simplify the locking rules
in the driver load and resume code.

Also see: [`intel_hpd_poll_enable()`](#c-intel_hpd_poll_enable) and [`intel_hpd_poll_disable()`](#c-intel_hpd_poll_disable).

#### <a id="c-intel_hpd_poll_enable"></a>`intel_hpd_poll_enable()`

```c
void intel_hpd_poll_enable(struct intel_display *display)
```

enable polling for connectors with hpd

**Parameters**

- `struct intel_display *display`: display device instance

**Description**

This function enables polling for all connectors which support HPD.
Under certain conditions HPD may not be functional. On most Intel GPUs,
this happens when we enter runtime suspend.
On Valleyview and Cherryview systems, this also happens when we shut off all
of the powerwells.

Since this function can get called in contexts where we're already holding
dev->mode_config.mutex, we do the actual hotplug enabling in a separate
worker.

Also see: [`intel_hpd_init()`](#c-intel_hpd_init) and [`intel_hpd_poll_disable()`](#c-intel_hpd_poll_disable).

#### <a id="c-intel_hpd_poll_disable"></a>`intel_hpd_poll_disable()`

```c
void intel_hpd_poll_disable(struct intel_display *display)
```

disable polling for connectors with hpd

**Parameters**

- `struct intel_display *display`: display device instance

**Description**

This function disables polling for all connectors which support HPD.
Under certain conditions HPD may not be functional. On most Intel GPUs,
this happens when we enter runtime suspend.
On Valleyview and Cherryview systems, this also happens when we shut off all
of the powerwells.

Since this function can get called in contexts where we're already holding
dev->mode_config.mutex, we do the actual hotplug enabling in a separate
worker.

Also used during driver init to initialize connector->polled
appropriately for all connectors.

Also see: [`intel_hpd_init()`](#c-intel_hpd_init) and [`intel_hpd_poll_enable()`](#c-intel_hpd_poll_enable).

#### <a id="c-intel_hpd_block"></a>`intel_hpd_block()`

```c
void intel_hpd_block(struct intel_encoder *encoder)
```

Block handling of HPD IRQs on an HPD pin

**Parameters**

- `struct intel_encoder *encoder`: Encoder to block the HPD handling for

**Description**

Blocks the handling of HPD IRQs on the HPD pin of **encoder**.

On return:

- It's guaranteed that the blocked encoders' HPD pulse handler
  (via intel_digital_port::`hpd_pulse()`) is not running.
- The hotplug event handling (via intel_encoder::`hotplug()`) of an
  HPD IRQ pending at the time this function is called may be still
  running.
- Detection on the encoder's connector (via
  drm_connector_helper_funcs::`detect_ctx()`,
  drm_connector_funcs::`detect()`) remains allowed, for instance as part of
  userspace connector probing, or DRM core's connector polling.

The call must be followed by calling [`intel_hpd_unblock()`](#c-intel_hpd_unblock), or
[`intel_hpd_clear_and_unblock()`](#c-intel_hpd_clear_and_unblock).

Note that the handling of HPD IRQs for another encoder using the same HPD
pin as that of **encoder** will be also blocked.

#### <a id="c-intel_hpd_unblock"></a>`intel_hpd_unblock()`

```c
void intel_hpd_unblock(struct intel_encoder *encoder)
```

Unblock handling of HPD IRQs on an HPD pin

**Parameters**

- `struct intel_encoder *encoder`: Encoder to unblock the HPD handling for

**Description**

Unblock the handling of HPD IRQs on the HPD pin of **encoder**, which was
previously blocked by [`intel_hpd_block()`](#c-intel_hpd_block). Any HPD IRQ raised on the
HPD pin while it was blocked will be handled for **encoder** and for any
other encoder sharing the same HPD pin.

#### <a id="c-intel_hpd_clear_and_unblock"></a>`intel_hpd_clear_and_unblock()`

```c
void intel_hpd_clear_and_unblock(struct intel_encoder *encoder)
```

Unblock handling of new HPD IRQs on an HPD pin

**Parameters**

- `struct intel_encoder *encoder`: Encoder to unblock the HPD handling for

**Description**

Unblock the handling of HPD IRQs on the HPD pin of **encoder**, which was
previously blocked by [`intel_hpd_block()`](#c-intel_hpd_block). Any HPD IRQ raised on the
HPD pin while it was blocked will be cleared, handling only new IRQs.


<a id="rst-high-definition-audio"></a>

### High Definition Audio


The graphics and audio drivers together support High Definition Audio over
HDMI and Display Port. The audio programming sequences are divided into audio
codec and controller enable and disable sequences. The graphics driver
handles the audio codec sequences, while the audio driver handles the audio
controller sequences.

The disable sequences must be performed before disabling the transcoder or
port. The enable sequences may only be performed after enabling the
transcoder and port, and after completed link training. Therefore the audio
enable/disable sequences are part of the modeset sequence.

The codec and controller sequences could be done either parallel or serial,
but generally the ELDV/PD change in the codec sequence indicates to the audio
driver that the controller sequence should start. Indeed, most of the
co-operation between the graphics and audio drivers is handled via audio
related registers. (The notable exception is the power management, not
covered here.)

The struct [`i915_audio_component`](#c-struct-i915_audio_component) is used to interact between the graphics
and audio drivers. The struct `i915_audio_component_ops` **ops** in it is
defined in graphics driver and called in audio driver. The
struct `i915_audio_component_audio_ops` **audio_ops** is called from i915 driver.



#### <a id="c-intel_audio_codec_enable"></a>`intel_audio_codec_enable()`

```c
void intel_audio_codec_enable(struct intel_encoder *encoder, const struct intel_crtc_state *crtc_state, const struct drm_connector_state *conn_state)
```

Enable the audio codec for HD audio

**Parameters**

- `struct intel_encoder *encoder`: encoder on which to enable audio
- `const struct intel_crtc_state *crtc_state`: pointer to the current crtc state.
- `const struct drm_connector_state *conn_state`: pointer to the current connector state.

**Description**

The enable sequences may only be performed after enabling the transcoder and
port, and after completed link training.

#### <a id="c-intel_audio_codec_disable"></a>`intel_audio_codec_disable()`

```c
void intel_audio_codec_disable(struct intel_encoder *encoder, const struct intel_crtc_state *old_crtc_state, const struct drm_connector_state *old_conn_state)
```

Disable the audio codec for HD audio

**Parameters**

- `struct intel_encoder *encoder`: encoder on which to disable audio
- `const struct intel_crtc_state *old_crtc_state`: pointer to the old crtc state.
- `const struct drm_connector_state *old_conn_state`: pointer to the old connector state.

**Description**

The disable sequences must be performed before disabling the transcoder or
port.

#### <a id="c-intel_audio_hooks_init"></a>`intel_audio_hooks_init()`

```c
void intel_audio_hooks_init(struct intel_display *display)
```

Set up chip specific audio hooks

**Parameters**

- `struct intel_display *display`: display device

#### <a id="c-intel_audio_component_init"></a>`intel_audio_component_init()`

```c
void intel_audio_component_init(struct intel_display *display)
```

initialize and register the audio component

**Parameters**

- `struct intel_display *display`: display device

**Description**

This will register with the component framework a child component which
will bind dynamically to the snd_hda_intel driver's corresponding master
component when the latter is registered. During binding the child
initializes an instance of struct i915_audio_component which it receives
from the master. The master can then start to use the interface defined by
this struct. Each side can break the binding at any point by deregistering
its own component after which each side's component unbind callback is
called.

We ignore any error during registration and continue with reduced
functionality (i.e. without HDMI audio).

#### <a id="c-intel_audio_component_cleanup"></a>`intel_audio_component_cleanup()`

```c
void intel_audio_component_cleanup(struct intel_display *display)
```

deregister the audio component

**Parameters**

- `struct intel_display *display`: display device

**Description**

Deregisters the audio component, breaking any existing binding to the
corresponding snd_hda_intel driver's master component.

#### <a id="c-intel_audio_init"></a>`intel_audio_init()`

```c
void intel_audio_init(struct intel_display *display)
```

Initialize the audio driver either using component framework or using lpe audio bridge

**Parameters**

- `struct intel_display *display`: display device

#### <a id="c-intel_audio_deinit"></a>`intel_audio_deinit()`

```c
void intel_audio_deinit(struct intel_display *display)
```

deinitialize the audio driver

**Parameters**

- `struct intel_display *display`: display device



#### <a id="c-struct-i915_audio_component"></a>`struct i915_audio_component`

Used for direct communication between i915 and hda drivers

**Definition**

```c
struct i915_audio_component {
    struct drm_audio_component      base;
    int aud_sample_rate[MAX_PORTS];
};
```

**Members**

- `base`: the drm_audio_component base class
- `aud_sample_rate`: the array of audio sample rate per port


<a id="rst-intel-hdmi-lpe-audio-support"></a>

### Intel HDMI LPE Audio Support


Motivation:
Atom platforms (e.g. valleyview and cherryTrail) integrates a DMA-based
interface as an alternative to the traditional HDaudio path. While this
mode is unrelated to the LPE aka SST audio engine, the documentation refers
to this mode as LPE so we keep this notation for the sake of consistency.

The interface is handled by a separate standalone driver maintained in the
ALSA subsystem for simplicity. To minimize the interaction between the two
subsystems, a bridge is setup between the hdmi-lpe-audio and i915:
1. Create a platform device to share MMIO/IRQ resources
2. Make the platform device child of i915 device for runtime PM.
3. Create IRQ chip to forward the LPE audio irqs.
the hdmi-lpe-audio driver probes the lpe audio device and creates a new
sound card

Threats:
Due to the restriction in Linux platform device model, user need manually
uninstall the hdmi-lpe-audio driver before uninstalling i915 module,
otherwise we might run into use-after-free issues after i915 removes the
platform device: even though hdmi-lpe-audio driver is released, the modules
is still in "installed" status.

Implementation:
The MMIO/REG platform resources are created according to the registers
specification.
When forwarding LPE audio irqs, the flow control handler selection depends
on the platform, for example on valleyview handle_simple_irq is enough.



#### <a id="c-intel_lpe_audio_irq_handler"></a>`intel_lpe_audio_irq_handler()`

```c
void intel_lpe_audio_irq_handler(struct intel_display *display)
```

forwards the LPE audio irq

**Parameters**

- `struct intel_display *display`: display device

**Description**

the LPE Audio irq is forwarded to the irq handler registered by LPE audio
driver.

#### <a id="c-intel_lpe_audio_init"></a>`intel_lpe_audio_init()`

```c
int intel_lpe_audio_init(struct intel_display *display)
```

detect and setup the bridge between HDMI LPE Audio driver and i915

**Parameters**

- `struct intel_display *display`: display device

**Return**

0 if successful. non-zero if detection or
llocation/initialization fails

#### <a id="c-intel_lpe_audio_teardown"></a>`intel_lpe_audio_teardown()`

```c
void intel_lpe_audio_teardown(struct intel_display *display)
```

destroy the bridge between HDMI LPE audio driver and i915

**Parameters**

- `struct intel_display *display`: display device

**Description**

release all the resources for LPE audio \<-> i915 bridge.

#### <a id="c-intel_lpe_audio_notify"></a>`intel_lpe_audio_notify()`

```c
void intel_lpe_audio_notify(struct intel_display *display, enum transcoder cpu_transcoder, enum port port, const void *eld, int ls_clock, bool dp_output)
```

notify lpe audio event audio driver and i915

**Parameters**

- `struct intel_display *display`: display device
- `enum transcoder cpu_transcoder`: CPU transcoder
- `enum port port`: port
- `const void *eld`: ELD data
- `int ls_clock`: Link symbol clock in kHz
- `bool dp_output`: Driving a DP output?

**Description**

Notify lpe audio driver of eld change.


<a id="rst-panel-self-refresh-psr-psr-srd"></a>

### Panel Self Refresh PSR (PSR/SRD)


Since Haswell Display controller supports Panel Self-Refresh on display
panels witch have a remote frame buffer (RFB) implemented according to PSR
spec in eDP1.3. PSR feature allows the display to go to lower standby states
when system is idle but display is on as it eliminates display refresh
request to DDR memory completely as long as the frame buffer for that
display is unchanged.

Panel Self Refresh must be supported by both Hardware (source) and
Panel (sink).

PSR saves power by caching the framebuffer in the panel RFB, which allows us
to power down the link and memory controller. For DSI panels the same idea
is called "manual mode".

The implementation uses the hardware-based PSR support which automatically
enters/exits self-refresh mode. The hardware takes care of sending the
required DP aux message and could even retrain the link (that part isn't
enabled yet though). The hardware also keeps track of any frontbuffer
changes to know when to exit self-refresh mode again. Unfortunately that
part doesn't work too well, hence why the i915 PSR support uses the
software frontbuffer tracking to make sure it doesn't miss a screen
update. For this integration [`intel_psr_invalidate()`](#c-intel_psr_invalidate) and [`intel_psr_flush()`](#c-intel_psr_flush)
get called by the frontbuffer tracking code. Note that because of locking
issues the self-refresh re-enable code is done from a work queue, which
must be correctly synchronized/cancelled when shutting down the pipe."

DC3CO (DC3 clock off)

On top of PSR2, GEN12 adds a intermediate power savings state that turns
clock off automatically during PSR2 idle state.
The smaller overhead of DC3co entry/exit vs. the overhead of PSR2 deep sleep
entry/exit allows the HW to enter a low-power state even when page flipping
periodically (for instance a 30fps video playback scenario).

Every time a flips occurs PSR2 will get out of deep sleep state(if it was),
so DC3CO is enabled and tgl_dc3co_disable_work is schedule to run after 6
frames, if no other flip occurs and the function above is executed, DC3CO is
disabled and PSR2 is configured to enter deep sleep, resetting again in case
of another flip.
Front buffer modifications do not trigger DC3CO activation on purpose as it
would bring a lot of complexity and most of the moderns systems will only
use page flips.



#### <a id="c-intel_psr_disable"></a>`intel_psr_disable()`

```c
void intel_psr_disable(struct intel_dp *intel_dp, const struct intel_crtc_state *old_crtc_state)
```

Disable PSR

**Parameters**

- `struct intel_dp *intel_dp`: Intel DP
- `const struct intel_crtc_state *old_crtc_state`: old CRTC state

**Description**

This function needs to be called before disabling pipe.

#### <a id="c-intel_psr_pause"></a>`intel_psr_pause()`

```c
void intel_psr_pause(struct intel_dp *intel_dp)
```

Pause PSR

**Parameters**

- `struct intel_dp *intel_dp`: Intel DP

**Description**

This function need to be called after enabling psr.

#### <a id="c-intel_psr_resume"></a>`intel_psr_resume()`

```c
void intel_psr_resume(struct intel_dp *intel_dp)
```

Resume PSR

**Parameters**

- `struct intel_dp *intel_dp`: Intel DP

**Description**

This function need to be called after pausing psr.

#### <a id="c-intel_psr_needs_vblank_notification"></a>`intel_psr_needs_vblank_notification()`

```c
bool intel_psr_needs_vblank_notification(const struct intel_crtc_state *crtc_state)
```

Check if PSR need vblank enable/disable notification.

**Parameters**

- `const struct intel_crtc_state *crtc_state`: CRTC status

**Description**

We need to block DC6 entry in case of Panel Replay as enabling VBI doesn't
prevent it in case of Panel Replay. Panel Replay switches main link off on
DC entry. This means vblank interrupts are not fired and is a problem if
user-space is polling for vblank events. Also Wa_16025596647 needs
information when vblank is enabled/disabled.

#### <a id="c-intel_psr_trigger_frame_change_event"></a>`intel_psr_trigger_frame_change_event()`

```c
void intel_psr_trigger_frame_change_event(struct intel_dsb *dsb, struct intel_atomic_state *state, struct intel_crtc *crtc)
```

Trigger "Frame Change" event

**Parameters**

- `struct intel_dsb *dsb`: DSB context
- `struct intel_atomic_state *state`: the atomic state
- `struct intel_crtc *crtc`: the CRTC

**Description**

Generate PSR "Frame Change" event.

#### <a id="c-intel_psr_min_set_context_latency"></a>`intel_psr_min_set_context_latency()`

```c
int intel_psr_min_set_context_latency(const struct intel_crtc_state *crtc_state)
```

Minimum 'set context latency' lines needed by PSR

**Parameters**

- `const struct intel_crtc_state *crtc_state`: the crtc state

**Description**

Return minimum SCL lines/delay needed by PSR.

#### <a id="c-intel_psr_wait_for_idle_locked"></a>`intel_psr_wait_for_idle_locked()`

```c
void intel_psr_wait_for_idle_locked(const struct intel_crtc_state *new_crtc_state)
```

wait for PSR be ready for a pipe update

**Parameters**

- `const struct intel_crtc_state *new_crtc_state`: new CRTC state

**Description**

This function is expected to be called from `pipe_update_start()` where it is
not expected to race with PSR enable or disable.

#### <a id="c-intel_psr_invalidate"></a>`intel_psr_invalidate()`

```c
void intel_psr_invalidate(struct intel_display *display, unsigned frontbuffer_bits, enum fb_op_origin origin)
```

Invalidate PSR

**Parameters**

- `struct intel_display *display`: display device
- `unsigned frontbuffer_bits`: frontbuffer plane tracking bits
- `enum fb_op_origin origin`: which operation caused the invalidate

**Description**

Since the hardware frontbuffer tracking has gaps we need to integrate
with the software frontbuffer tracking. This function gets called every
time frontbuffer rendering starts and a buffer gets dirtied. PSR must be
disabled if the frontbuffer mask contains a buffer relevant to PSR.

Dirty frontbuffers relevant to PSR are tracked in busy_frontbuffer_bits."

#### <a id="c-intel_psr_flush"></a>`intel_psr_flush()`

```c
void intel_psr_flush(struct intel_display *display, unsigned frontbuffer_bits, enum fb_op_origin origin)
```

Flush PSR

**Parameters**

- `struct intel_display *display`: display device
- `unsigned frontbuffer_bits`: frontbuffer plane tracking bits
- `enum fb_op_origin origin`: which operation caused the flush

**Description**

Since the hardware frontbuffer tracking has gaps we need to integrate
with the software frontbuffer tracking. This function gets called every
time frontbuffer rendering has completed and flushed out to memory. PSR
can be enabled again if no other frontbuffer relevant to PSR is dirty.

Dirty frontbuffers relevant to PSR are tracked in busy_frontbuffer_bits.

#### <a id="c-intel_psr_init"></a>`intel_psr_init()`

```c
void intel_psr_init(struct intel_dp *intel_dp)
```

Init basic PSR work and mutex.

**Parameters**

- `struct intel_dp *intel_dp`: Intel DP

**Description**

This function is called after the initializing connector.
(the initializing of connector treats the handling of connector capabilities)
And it initializes basic PSR stuff for each DP Encoder.

#### <a id="c-intel_psr_link_ok"></a>`intel_psr_link_ok()`

```c
bool intel_psr_link_ok(struct intel_dp *intel_dp)
```

return psr->link_ok

**Parameters**

- `struct intel_dp *intel_dp`: struct intel_dp

**Description**

We are seeing unexpected link re-trainings with some panels. This is caused
by panel stating bad link status after PSR is enabled. Code checking link
status can call this to ensure it can ignore bad link status stated by the
panel I.e. if panel is stating bad link and intel_psr_link_ok is stating link
is ok caller should rely on latter.

Return value of link_ok

#### <a id="c-intel_psr_lock"></a>`intel_psr_lock()`

```c
void intel_psr_lock(const struct intel_crtc_state *crtc_state)
```

grab PSR lock

**Parameters**

- `const struct intel_crtc_state *crtc_state`: the crtc state

**Description**

This is initially meant to be used by around CRTC update, when
vblank sensitive registers are updated and we need grab the lock
before it to avoid vblank evasion.

#### <a id="c-intel_psr_unlock"></a>`intel_psr_unlock()`

```c
void intel_psr_unlock(const struct intel_crtc_state *crtc_state)
```

release PSR lock

**Parameters**

- `const struct intel_crtc_state *crtc_state`: the crtc state

**Description**

Release the PSR lock that was held during pipe update.

#### <a id="c-intel_psr_notify_dc5_dc6"></a>`intel_psr_notify_dc5_dc6()`

```c
void intel_psr_notify_dc5_dc6(struct intel_display *display)
```

Notify PSR about enable/disable dc5/dc6

**Parameters**

- `struct intel_display *display`: intel atomic state

**Description**

This is targeted for underrun on idle PSR HW bug (Wa_16025596647) to schedule
psr_dc5_dc6_wa_work used for applying/removing the workaround.

#### <a id="c-intel_psr_dc5_dc6_wa_init"></a>`intel_psr_dc5_dc6_wa_init()`

```c
void intel_psr_dc5_dc6_wa_init(struct intel_display *display)
```

Init work for underrun on idle PSR HW bug wa

**Parameters**

- `struct intel_display *display`: intel atomic state

**Description**

This is targeted for underrun on idle PSR HW bug (Wa_16025596647) to init
psr_dc5_dc6_wa_work used for applying the workaround.

#### <a id="c-intel_psr_notify_pipe_change"></a>`intel_psr_notify_pipe_change()`

```c
void intel_psr_notify_pipe_change(struct intel_atomic_state *state, struct intel_crtc *crtc, bool enable)
```

Notify PSR about enable/disable of a pipe

**Parameters**

- `struct intel_atomic_state *state`: intel atomic state
- `struct intel_crtc *crtc`: intel crtc
- `bool enable`: enable/disable

**Description**

This is targeted for underrun on idle PSR HW bug (Wa_16025596647) to apply
remove the workaround when pipe is getting enabled/disabled

#### <a id="c-intel_psr_notify_vblank_enable_disable"></a>`intel_psr_notify_vblank_enable_disable()`

```c
void intel_psr_notify_vblank_enable_disable(struct intel_display *display, bool enable)
```

Notify PSR about enable/disable of vblank

**Parameters**

- `struct intel_display *display`: intel display struct
- `bool enable`: enable/disable

**Description**

This is targeted for underrun on idle PSR HW bug (Wa_16025596647) to apply
remove the workaround when vblank is getting enabled/disabled


<a id="rst-frame-buffer-compression-fbc"></a>

### Frame Buffer Compression (FBC)


FBC tries to save memory bandwidth (and so power consumption) by
compressing the amount of memory used by the display. It is total
transparent to user space and completely handled in the kernel.

The benefits of FBC are mostly visible with solid backgrounds and
variation-less patterns. It comes from keeping the memory footprint small
and having fewer memory pages opened and accessed for refreshing the display.

i915 is responsible to reserve stolen memory for FBC and configure its
offset on proper registers. The hardware takes care of all
compress/decompress. However there are many known cases where we have to
forcibly disable it to allow proper screen updates.



#### <a id="c-intel_fbc_disable"></a>`intel_fbc_disable()`

```c
void intel_fbc_disable(struct intel_crtc *crtc)
```

disable FBC if it's associated with crtc

**Parameters**

- `struct intel_crtc *crtc`: the CRTC

**Description**

This function disables FBC if it's associated with the provided CRTC.

#### <a id="c-intel_fbc_handle_fifo_underrun_irq"></a>`intel_fbc_handle_fifo_underrun_irq()`

```c
void intel_fbc_handle_fifo_underrun_irq(struct intel_display *display)
```

disable FBC when we get a FIFO underrun

**Parameters**

- `struct intel_display *display`: display

**Description**

Without FBC, most underruns are harmless and don't really cause too many
problems, except for an annoying message on dmesg. With FBC, underruns can
become black screens or even worse, especially when paired with bad
watermarks. So in order for us to be on the safe side, completely disable FBC
in case we ever detect a FIFO underrun on any pipe. An underrun on any pipe
already suggests that watermarks may be bad, so try to be as safe as
possible.

This function is called from the IRQ handler.

#### <a id="c-intel_fbc_read_underrun_dbg_info"></a>`intel_fbc_read_underrun_dbg_info()`

```c
void intel_fbc_read_underrun_dbg_info(struct intel_display *display, enum pipe pipe, bool log)
```

Read and log FBC-related FIFO underrun debug info

**Parameters**

- `struct intel_display *display`: display device instance
- `enum pipe pipe`: the pipe possibly containing the FBC
- `bool log`: log the info?

**Description**

If **pipe** does not contain an FBC instance, this function bails early.
Otherwise, FBC-related FIFO underrun is read and cleared, and then, if **log**
is true, printed with error level.

#### <a id="c-intel_fbc_init"></a>`intel_fbc_init()`

```c
void intel_fbc_init(struct intel_display *display)
```

Initialize FBC

**Parameters**

- `struct intel_display *display`: display

**Description**

This function might be called during PM init process.

#### <a id="c-intel_fbc_sanitize"></a>`intel_fbc_sanitize()`

```c
void intel_fbc_sanitize(struct intel_display *display)
```

Sanitize FBC

**Parameters**

- `struct intel_display *display`: display

**Description**

Make sure FBC is initially disabled since we have no
idea eg. into which parts of stolen it might be scribbling
into.


<a id="rst-display-refresh-rate-switching-drrs"></a>

### Display Refresh Rate Switching (DRRS)


Display Refresh Rate Switching (DRRS) is a power conservation feature
which enables swtching between low and high refresh rates,
dynamically, based on the usage scenario. This feature is applicable
for internal panels.

Indication that the panel supports DRRS is given by the panel EDID, which
would list multiple refresh rates for one resolution.

DRRS is of 2 types - static and seamless.
Static DRRS involves changing refresh rate (RR) by doing a full modeset
(may appear as a blink on screen) and is used in dock-undock scenario.
Seamless DRRS involves changing RR without any visual effect to the user
and can be used during normal system usage. This is done by programming
certain registers.

Support for static/seamless DRRS may be indicated in the VBT based on
inputs from the panel spec.

DRRS saves power by switching to low RR based on usage scenarios.

The implementation is based on frontbuffer tracking implementation.  When
there is a disturbance on the screen triggered by user activity or a periodic
system activity, DRRS is disabled (RR is changed to high RR).  When there is
no movement on screen, after a timeout of 1 second, a switch to low RR is
made.

For integration with frontbuffer tracking code, [`intel_drrs_invalidate()`](#c-intel_drrs_invalidate)
and [`intel_drrs_flush()`](#c-intel_drrs_flush) are called.

DRRS can be further extended to support other internal panels and also
the scenario of video playback wherein RR is set based on the rate
requested by userspace.



#### <a id="c-intel_drrs_activate"></a>`intel_drrs_activate()`

```c
void intel_drrs_activate(const struct intel_crtc_state *crtc_state)
```

activate DRRS

**Parameters**

- `const struct intel_crtc_state *crtc_state`: the crtc state

**Description**

Activates DRRS on the crtc.

#### <a id="c-intel_drrs_deactivate"></a>`intel_drrs_deactivate()`

```c
void intel_drrs_deactivate(const struct intel_crtc_state *old_crtc_state)
```

deactivate DRRS

**Parameters**

- `const struct intel_crtc_state *old_crtc_state`: the old crtc state

**Description**

Deactivates DRRS on the crtc.

#### <a id="c-intel_drrs_invalidate"></a>`intel_drrs_invalidate()`

```c
void intel_drrs_invalidate(struct intel_display *display, unsigned int frontbuffer_bits)
```

Disable Idleness DRRS

**Parameters**

- `struct intel_display *display`: display device
- `unsigned int frontbuffer_bits`: frontbuffer plane tracking bits

**Description**

This function gets called everytime rendering on the given planes start.
Hence DRRS needs to be Upclocked, i.e. (LOW_RR -> HIGH_RR).

Dirty frontbuffers relevant to DRRS are tracked in busy_frontbuffer_bits.

#### <a id="c-intel_drrs_flush"></a>`intel_drrs_flush()`

```c
void intel_drrs_flush(struct intel_display *display, unsigned int frontbuffer_bits)
```

Restart Idleness DRRS

**Parameters**

- `struct intel_display *display`: display device
- `unsigned int frontbuffer_bits`: frontbuffer plane tracking bits

**Description**

This function gets called every time rendering on the given planes has
completed or flip on a crtc is completed. So DRRS should be upclocked
(LOW_RR -> HIGH_RR). And also Idleness detection should be started again,
if no other planes are dirty.

Dirty frontbuffers relevant to DRRS are tracked in busy_frontbuffer_bits.

#### <a id="c-intel_drrs_crtc_init"></a>`intel_drrs_crtc_init()`

```c
void intel_drrs_crtc_init(struct intel_crtc *crtc)
```

Init DRRS for CRTC

**Parameters**

- `struct intel_crtc *crtc`: crtc

**Description**

This function is called only once at driver load to initialize basic
DRRS stuff.


<a id="rst-dpio"></a>

### DPIO


VLV, CHV and BXT have slightly peculiar display PHYs for driving DP/HDMI
ports. DPIO is the name given to such a display PHY. These PHYs
don't follow the standard programming model using direct MMIO
registers, and instead their registers must be accessed through IOSF
sideband. VLV has one such PHY for driving ports B and C, and CHV
adds another PHY for driving port D. Each PHY responds to specific
IOSF-SB port.

Each display PHY is made up of one or two channels. Each channel
houses a common lane part which contains the PLL and other common
logic. CH0 common lane also contains the IOSF-SB logic for the
Common Register Interface (CRI) ie. the DPIO registers. CRI clock
must be running when any DPIO registers are accessed.

In addition to having their own registers, the PHYs are also
controlled through some dedicated signals from the display
controller. These include PLL reference clock enable, PLL enable,
and CRI clock selection, for example.

Eeach channel also has two splines (also called data lanes), and
each spline is made up of one Physical Access Coding Sub-Layer
(PCS) block and two TX lanes. So each channel has two PCS blocks
and four TX lanes. The TX lanes are used as DP lanes or TMDS
data/clock pairs depending on the output type.

Additionally the PHY also contains an AUX lane with AUX blocks
for each channel. This is used for DP AUX communication, but
this fact isn't really relevant for the driver since AUX is
controlled from the display controller side. No DPIO registers
need to be accessed during AUX communication,

Generally on VLV/CHV the common lane corresponds to the pipe and
the spline (PCS/TX) corresponds to the port.

For dual channel PHY (VLV/CHV):

pipe A == CMN/PLL/REF CH0

pipe B == CMN/PLL/REF CH1

port B == PCS/TX CH0

port C == PCS/TX CH1

This is especially important when we cross the streams
ie. drive port B with pipe B, or port C with pipe A.

For single channel PHY (CHV):

pipe C == CMN/PLL/REF CH0

port D == PCS/TX CH0

On BXT the entire PHY channel corresponds to the port. That means
the PLL is also now associated with the port rather than the pipe,
and so the clock needs to be routed to the appropriate transcoder.
Port A PLL is directly connected to transcoder EDP and port B/C
PLLs can be routed to any transcoder A/B/C.

Note: DDI0 is digital port B, DD1 is digital port C, and DDI2 is
digital port D (CHV) or port A (BXT).

```text
Dual channel PHY (VLV/CHV/BXT)
---------------------------------
|      CH0      |      CH1      |
|  CMN/PLL/REF  |  CMN/PLL/REF  |
|---------------|---------------| Display PHY
| PCS01 | PCS23 | PCS01 | PCS23 |
|-------|-------|-------|-------|
|TX0|TX1|TX2|TX3|TX0|TX1|TX2|TX3|
---------------------------------
|     DDI0      |     DDI1      | DP/HDMI ports
---------------------------------

Single channel PHY (CHV/BXT)
-----------------
|      CH0      |
|  CMN/PLL/REF  |
|---------------| Display PHY
| PCS01 | PCS23 |
|-------|-------|
|TX0|TX1|TX2|TX3|
-----------------
|     DDI2      | DP/HDMI port
-----------------
```


<a id="rst-dmc-firmware-support"></a>

### DMC Firmware Support


From gen9 onwards we have newly added DMC (Display microcontroller) in display
engine to save and restore the state of display engine when it enter into
low-power state and comes back to normal.



#### <a id="c-intel_dmc_block_pkgc"></a>`intel_dmc_block_pkgc()`

```c
void intel_dmc_block_pkgc(struct intel_display *display, enum pipe pipe, bool block)
```

block PKG C-state

**Parameters**

- `struct intel_display *display`: display instance
- `enum pipe pipe`: pipe which register use to block
- `bool block`: block/unblock

**Description**

This interface is target for Wa_16025596647 usage. I.e. to set/clear
PIPEDMC_BLOCK_PKGC_SW_BLOCK_PKGC_ALWAYS bit in PIPEDMC_BLOCK_PKGC_SW register.

#### <a id="c-intel_dmc_start_pkgc_exit_at_start_of_undelayed_vblank"></a>`intel_dmc_start_pkgc_exit_at_start_of_undelayed_vblank()`

```c
void intel_dmc_start_pkgc_exit_at_start_of_undelayed_vblank(struct intel_display *display, enum pipe pipe, bool enable)
```

start of PKG C-state exit

**Parameters**

- `struct intel_display *display`: display instance
- `enum pipe pipe`: pipe which register use to block
- `bool enable`: enable/disable

**Description**

This interface is target for Wa_16025596647 usage. I.e. start the package C
exit at the start of the undelayed vblank

#### <a id="c-intel_dmc_load_program"></a>`intel_dmc_load_program()`

```c
void intel_dmc_load_program(struct intel_display *display)
```

write the firmware from memory to register.

**Parameters**

- `struct intel_display *display`: display instance

**Description**

DMC firmware is read from a .bin file and kept in internal memory one time.
Everytime display comes back from low power state this function is called to
copy the firmware from internal memory to registers.

#### <a id="c-intel_dmc_disable_program"></a>`intel_dmc_disable_program()`

```c
void intel_dmc_disable_program(struct intel_display *display)
```

disable the firmware

**Parameters**

- `struct intel_display *display`: display instance

**Description**

Disable all event handlers in the firmware, making sure the firmware is
inactive after the display is uninitialized.

#### <a id="c-intel_dmc_init"></a>`intel_dmc_init()`

```c
void intel_dmc_init(struct intel_display *display)
```

initialize the firmware loading.

**Parameters**

- `struct intel_display *display`: display instance

**Description**

This function is called at the time of loading the display driver to read
firmware from a .bin file and copied into a internal memory.

#### <a id="c-intel_dmc_suspend"></a>`intel_dmc_suspend()`

```c
void intel_dmc_suspend(struct intel_display *display)
```

prepare DMC firmware before system suspend

**Parameters**

- `struct intel_display *display`: display instance

**Description**

Prepare the DMC firmware before entering system suspend. This includes
flushing pending work items and releasing any resources acquired during
init.

#### <a id="c-intel_dmc_resume"></a>`intel_dmc_resume()`

```c
void intel_dmc_resume(struct intel_display *display)
```

init DMC firmware during system resume

**Parameters**

- `struct intel_display *display`: display instance

**Description**

Reinitialize the DMC firmware during system resume, reacquiring any
resources released in [`intel_dmc_suspend()`](#c-intel_dmc_suspend).

#### <a id="c-intel_dmc_fini"></a>`intel_dmc_fini()`

```c
void intel_dmc_fini(struct intel_display *display)
```

unload the DMC firmware.

**Parameters**

- `struct intel_display *display`: display instance

**Description**

Firmmware unloading includes freeing the internal memory and reset the
firmware loading status.


<a id="rst-dmc-flip-queue"></a>

### DMC Flip Queue


A flip queue is a ring buffer implemented by the pipe DMC firmware.
The driver inserts entries into the queues to be executed by the
pipe DMC at a specified presentation timestamp (PTS).

Each pipe DMC provides several queues:

- 1 general queue (two DSB buffers executed per entry)
- 3 plane queues (one DSB buffer executed per entry)
- 1 fast queue (deprecated)


<a id="rst-dmc-wakelock-support"></a>

### DMC wakelock support


Wake lock is the mechanism to cause display engine to exit DC
states to allow programming to registers that are powered down in
those states. Previous projects exited DC states automatically when
detecting programming. Now software controls the exit by
programming the wake lock. This improves system performance and
system interactions and better fits the flip queue style of
programming. Wake lock is only required when DC5, DC6, or DC6v have
been enabled in DC_STATE_EN and the wake lock mode of operation has
been enabled.

The wakelock mechanism in DMC allows the display engine to exit DC
states explicitly before programming registers that may be powered
down.  In earlier hardware, this was done automatically and
implicitly when the display engine accessed a register.  With the
wakelock implementation, the driver asserts a wakelock in DMC,
which forces it to exit the DC state until the wakelock is
deasserted.

The mechanism can be enabled and disabled by writing to the
DMC_WAKELOCK_CFG register.  There are also 13 control registers
that can be used to hold and release different wakelocks.  In the
current implementation, we only need one wakelock, so only
DMC_WAKELOCK1_CTL is used.  The other definitions are here for
potential future use.


<a id="rst-video-bios-table-vbt"></a>

### Video BIOS Table (VBT)


The Video BIOS Table, or VBT, provides platform and board specific
configuration information to the driver that is not discoverable or available
through other means. The configuration is mostly related to display
hardware. The VBT is available via the ACPI OpRegion or, on older systems, in
the PCI ROM.

The VBT consists of a VBT Header (defined as [`struct vbt_header`](#c-struct-vbt_header)), a BDB
Header ([`struct bdb_header`](#c-struct-bdb_header)), and a number of BIOS Data Blocks (BDB) that
contain the actual configuration information. The VBT Header, and thus the
VBT, begins with "$VBT" signature. The VBT Header contains the offset of the
BDB Header. The data blocks are concatenated after the BDB Header. The data
blocks have a 1-byte Block ID, 2-byte Block Size, and Block Size bytes of
data. (Block 53, the MIPI Sequence Block is an exception.)

The driver parses the VBT during load. The relevant information is stored in
driver private data for ease of use, and the actual VBT is not read after
that.



#### <a id="c-intel_bios_is_valid_vbt"></a>`intel_bios_is_valid_vbt()`

```c
bool intel_bios_is_valid_vbt(struct intel_display *display, const void *buf, size_t size)
```

does the given buffer contain a valid VBT

**Parameters**

- `struct intel_display *display`: display device
- `const void *buf`: pointer to a buffer to validate
- `size_t size`: size of the buffer

**Description**

Returns true on valid VBT.

#### <a id="c-intel_bios_init"></a>`intel_bios_init()`

```c
void intel_bios_init(struct intel_display *display)
```

find VBT and initialize settings from the BIOS

**Parameters**

- `struct intel_display *display`: display device instance

**Description**

Parse and initialize settings from the Video BIOS Tables (VBT). If the VBT
was not found in ACPI OpRegion, try to find it in PCI ROM first. Also
initialize some defaults if the VBT is not present at all.

#### <a id="c-intel_bios_driver_remove"></a>`intel_bios_driver_remove()`

```c
void intel_bios_driver_remove(struct intel_display *display)
```

Free any resources allocated by [`intel_bios_init()`](#c-intel_bios_init)

**Parameters**

- `struct intel_display *display`: display device instance

#### <a id="c-intel_bios_is_tv_present"></a>`intel_bios_is_tv_present()`

```c
bool intel_bios_is_tv_present(struct intel_display *display)
```

is integrated TV present in VBT

**Parameters**

- `struct intel_display *display`: display device instance

**Description**

Return true if TV is present. If no child devices were parsed from VBT,
assume TV is present.

#### <a id="c-intel_bios_is_lvds_present"></a>`intel_bios_is_lvds_present()`

```c
bool intel_bios_is_lvds_present(struct intel_display *display, u8 *i2c_pin)
```

is LVDS present in VBT

**Parameters**

- `struct intel_display *display`: display device instance
- `u8 *i2c_pin`: i2c pin for LVDS if present

**Description**

Return true if LVDS is present. If no child devices were parsed from VBT,
assume LVDS is present.

#### <a id="c-intel_bios_is_port_present"></a>`intel_bios_is_port_present()`

```c
bool intel_bios_is_port_present(struct intel_display *display, enum port port)
```

is the specified digital port present

**Parameters**

- `struct intel_display *display`: display device instance
- `enum port port`: port to check

**Description**

Return true if the device in `port` is present.

#### <a id="c-intel_bios_is_dsi_present"></a>`intel_bios_is_dsi_present()`

```c
bool intel_bios_is_dsi_present(struct intel_display *display, enum port *port)
```

is DSI present in VBT

**Parameters**

- `struct intel_display *display`: display device instance
- `enum port *port`: port for DSI if present

**Description**

Return true if DSI is present, and return the port in `port`.



#### <a id="c-struct-vbt_header"></a>`struct vbt_header`

VBT Header structure

**Definition**

```c
struct vbt_header {
    u8 signature[20];
    u16 version;
    u16 header_size;
    u16 vbt_size;
    u8 vbt_checksum;
    u8 reserved0;
    u32 bdb_offset;
    u32 aim_offset[4];
};
```

**Members**

- `signature`: VBT signature, always starts with "$VBT"
- `version`: Version of this structure
- `header_size`: Size of this structure
- `vbt_size`: Size of VBT (VBT Header, BDB Header and data blocks)
- `vbt_checksum`: Checksum
- `reserved0`: Reserved
- `bdb_offset`: Offset of [`struct bdb_header`](#c-struct-bdb_header) from beginning of VBT
- `aim_offset`: Offsets of add-in data blocks from beginning of VBT

#### <a id="c-struct-bdb_header"></a>`struct bdb_header`

BDB Header structure

**Definition**

```c
struct bdb_header {
    u8 signature[16];
    u16 version;
    u16 header_size;
    u16 bdb_size;
};
```

**Members**

- `signature`: BDB signature "BIOS_DATA_BLOCK"
- `version`: Version of the data block definitions
- `header_size`: Size of this structure
- `bdb_size`: Size of BDB (BDB Header and data blocks)


<a id="rst-display-clocks"></a>

### Display clocks


The display engine uses several different clocks to do its work. There
are two main clocks involved that aren't directly related to the actual
pixel clock or any symbol/bit clock of the actual output port. These
are the core display clock (CDCLK) and RAWCLK.

CDCLK clocks most of the display pipe logic, and thus its frequency
must be high enough to support the rate at which pixels are flowing
through the pipes. Downscaling must also be accounted as that increases
the effective pixel rate.

On several platforms the CDCLK frequency can be changed dynamically
to minimize power consumption for a given display configuration.
Typically changes to the CDCLK frequency require all the display pipes
to be shut down while the frequency is being changed.

On SKL+ the DMC will toggle the CDCLK off/on during DC5/6 entry/exit.
DMC will not change the active CDCLK frequency however, so that part
will still be performed by the driver directly.

There are multiple components involved in the generation of the CDCLK
frequency:

- We have the CDCLK PLL, which generates an output clock based on a
  reference clock and a ratio parameter.
- The CD2X Divider, which divides the output of the PLL based on a
  divisor selected from a set of pre-defined choices.
- The CD2X Squasher, which further divides the output based on a
  waveform represented as a sequence of bits where each zero
  "squashes out" a clock cycle.
- And, finally, a fixed divider that divides the output frequency by 2.

As such, the resulting CDCLK frequency can be calculated with the
following formula:

cdclk = vco / cd2x_div / (sq_len / sq_div) / 2

, where vco is the frequency generated by the PLL; cd2x_div
represents the CD2X Divider; sq_len and sq_div are the bit length
and the number of high bits for the CD2X Squasher waveform, respectively;
and 2 represents the fixed divider.

Note that some older platforms do not contain the CD2X Divider
and/or CD2X Squasher, in which case we can ignore their respective
factors in the formula above.

Several methods exist to change the CDCLK frequency, which ones are
supported depends on the platform:

- Full PLL disable + re-enable with new VCO frequency. Pipes must be inactive.
- CD2X divider update. Single pipe can be active as the divider update
  can be synchronized with the pipe's start of vblank.
- Crawl the PLL smoothly to the new VCO frequency. Pipes can be active.
- Squash waveform update. Pipes can be active.
- Crawl and squash can also be done back to back. Pipes can be active.

RAWCLK is a fixed frequency clock, often used by various auxiliary
blocks such as AUX CH or backlight PWM. Hence the only thing we
really need to know about RAWCLK is its frequency so that various
dividers can be programmed correctly.



#### <a id="c-intel_cdclk_init_hw"></a>`intel_cdclk_init_hw()`

```c
void intel_cdclk_init_hw(struct intel_display *display)
```

Initialize CDCLK hardware

**Parameters**

- `struct intel_display *display`: display instance

**Description**

Initialize CDCLK. This consists mainly of initializing display->cdclk.hw and
sanitizing the state of the hardware if needed. This is generally done only
during the display core initialization sequence, after which the DMC will
take care of turning CDCLK off/on as needed.

#### <a id="c-intel_cdclk_uninit_hw"></a>`intel_cdclk_uninit_hw()`

```c
void intel_cdclk_uninit_hw(struct intel_display *display)
```

Uninitialize CDCLK hardware

**Parameters**

- `struct intel_display *display`: display instance

**Description**

Uninitialize CDCLK. This is done only during the display core
uninitialization sequence.

#### <a id="c-intel_cdclk_clock_changed"></a>`intel_cdclk_clock_changed()`

```c
bool intel_cdclk_clock_changed(const struct intel_cdclk_config *a, const struct intel_cdclk_config *b)
```

Check whether the clock changed

**Parameters**

- `const struct intel_cdclk_config *a`: first CDCLK configuration
- `const struct intel_cdclk_config *b`: second CDCLK configuration

**Return**

True if CDCLK changed in a way that requires re-programming and
False otherwise.

#### <a id="c-intel_cdclk_can_cd2x_update"></a>`intel_cdclk_can_cd2x_update()`

```c
bool intel_cdclk_can_cd2x_update(struct intel_display *display, const struct intel_cdclk_config *a, const struct intel_cdclk_config *b)
```

Determine if changing between the two CDCLK configurations requires only a cd2x divider update

**Parameters**

- `struct intel_display *display`: display instance
- `const struct intel_cdclk_config *a`: first CDCLK configuration
- `const struct intel_cdclk_config *b`: second CDCLK configuration

**Return**

True if changing between the two CDCLK configurations
can be done with just a cd2x divider update, false if not.

#### <a id="c-intel_cdclk_changed"></a>`intel_cdclk_changed()`

```c
bool intel_cdclk_changed(const struct intel_cdclk_config *a, const struct intel_cdclk_config *b)
```

Determine if two CDCLK configurations are different

**Parameters**

- `const struct intel_cdclk_config *a`: first CDCLK configuration
- `const struct intel_cdclk_config *b`: second CDCLK configuration

**Return**

True if the CDCLK configurations don't match, false if they do.

#### <a id="c-intel_set_cdclk_pre_plane_update"></a>`intel_set_cdclk_pre_plane_update()`

```c
void intel_set_cdclk_pre_plane_update(struct intel_atomic_state *state)
```

Push the CDCLK state to the hardware

**Parameters**

- `struct intel_atomic_state *state`: intel atomic state

**Description**

Program the hardware before updating the HW plane state based on the
new CDCLK state, if necessary.

#### <a id="c-intel_set_cdclk_post_plane_update"></a>`intel_set_cdclk_post_plane_update()`

```c
void intel_set_cdclk_post_plane_update(struct intel_atomic_state *state)
```

Push the CDCLK state to the hardware

**Parameters**

- `struct intel_atomic_state *state`: intel atomic state

**Description**

Program the hardware after updating the HW plane state based on the
new CDCLK state, if necessary.

#### <a id="c-intel_update_max_cdclk"></a>`intel_update_max_cdclk()`

```c
void intel_update_max_cdclk(struct intel_display *display)
```

Determine the maximum support CDCLK frequency

**Parameters**

- `struct intel_display *display`: display instance

**Description**

Determine the maximum CDCLK frequency the platform supports, and also
derive the maximum dot clock frequency the maximum CDCLK frequency
allows.

#### <a id="c-intel_update_cdclk"></a>`intel_update_cdclk()`

```c
void intel_update_cdclk(struct intel_display *display)
```

Determine the current CDCLK frequency

**Parameters**

- `struct intel_display *display`: display instance

**Description**

Determine the current CDCLK frequency.

#### <a id="c-intel_read_rawclk"></a>`intel_read_rawclk()`

```c
u32 intel_read_rawclk(struct intel_display *display)
```

Determine the current RAWCLK frequency

**Parameters**

- `struct intel_display *display`: display instance

**Description**

Determine the current RAWCLK frequency. RAWCLK is a fixed
frequency clock so this needs to done only once.

#### <a id="c-intel_init_cdclk_hooks"></a>`intel_init_cdclk_hooks()`

```c
void intel_init_cdclk_hooks(struct intel_display *display)
```

Initialize CDCLK related modesetting hooks

**Parameters**

- `struct intel_display *display`: display instance


<a id="rst-display-plls"></a>

### Display PLLs


Display PLLs used for driving outputs vary by platform. While some have
per-pipe or per-encoder dedicated PLLs, others allow the use of any PLL
from a pool. In the latter scenario, it is possible that multiple pipes
share a PLL if their configurations match.

This file provides an abstraction over display PLLs. The function
[`intel_dpll_init()`](#c-intel_dpll_init) initializes the PLLs for the given platform.  The
users of a PLL are tracked and that tracking is integrated with the atomic
modset interface. During an atomic operation, required PLLs can be reserved
for a given CRTC and encoder configuration by calling
[`intel_dpll_reserve()`](#c-intel_dpll_reserve) and previously reserved PLLs can be released
with [`intel_dpll_release()`](#c-intel_dpll_release).
Changes to the users are first staged in the atomic state, and then made
effective by calling [`intel_dpll_swap_state()`](#c-intel_dpll_swap_state) during the atomic
commit phase.



#### <a id="c-intel_get_dpll_by_id"></a>`intel_get_dpll_by_id()`

```c
struct intel_dpll * intel_get_dpll_by_id(struct intel_display *display, enum intel_dpll_id id)
```

get a DPLL given its id

**Parameters**

- `struct intel_display *display`: intel_display device instance
- `enum intel_dpll_id id`: pll id

**Return**

A pointer to the DPLL with **id**

#### <a id="c-intel_dpll_enable"></a>`intel_dpll_enable()`

```c
void intel_dpll_enable(const struct intel_crtc_state *crtc_state)
```

enable a CRTC's DPLL

**Parameters**

- `const struct intel_crtc_state *crtc_state`: CRTC, and its state, which has a DPLL

**Description**

Enable DPLL used by **crtc**.

#### <a id="c-intel_dpll_disable"></a>`intel_dpll_disable()`

```c
void intel_dpll_disable(const struct intel_crtc_state *crtc_state)
```

disable a CRTC's shared DPLL

**Parameters**

- `const struct intel_crtc_state *crtc_state`: CRTC, and its state, which has a shared DPLL

**Description**

Disable DPLL used by **crtc**.

#### <a id="c-intel_dpll_crtc_get"></a>`intel_dpll_crtc_get()`

```c
void intel_dpll_crtc_get(const struct intel_crtc *crtc, const struct intel_dpll *pll, struct intel_dpll_state *dpll_state)
```

Get a DPLL reference for a CRTC

**Parameters**

- `const struct intel_crtc *crtc`: CRTC on which behalf the reference is taken
- `const struct intel_dpll *pll`: DPLL for which the reference is taken
- `struct intel_dpll_state *dpll_state`: the DPLL atomic state in which the reference is tracked

**Description**

Take a reference for **pll** tracking the use of it by **crtc**.

#### <a id="c-intel_dpll_crtc_put"></a>`intel_dpll_crtc_put()`

```c
void intel_dpll_crtc_put(const struct intel_crtc *crtc, const struct intel_dpll *pll, struct intel_dpll_state *dpll_state)
```

Drop a DPLL reference for a CRTC

**Parameters**

- `const struct intel_crtc *crtc`: CRTC on which behalf the reference is dropped
- `const struct intel_dpll *pll`: DPLL for which the reference is dropped
- `struct intel_dpll_state *dpll_state`: the DPLL atomic state in which the reference is tracked

**Description**

Drop a reference for **pll** tracking the end of use of it by **crtc**.

#### <a id="c-intel_dpll_swap_state"></a>`intel_dpll_swap_state()`

```c
void intel_dpll_swap_state(struct intel_atomic_state *state)
```

make atomic DPLL configuration effective

**Parameters**

- `struct intel_atomic_state *state`: atomic state

**Description**

This is the dpll version of [`drm_atomic_helper_swap_state()`](/kernel/hardware/gpu/drm-kms-helpers.md#c-drm_atomic_helper_swap_state) since the
helper does not handle driver-specific global state.

For consistency with atomic helpers this function does a complete swap,
i.e. it also puts the current state into **state**, even though there is no
need for that at this moment.

#### <a id="c-icl_set_active_port_dpll"></a>`icl_set_active_port_dpll()`

```c
void icl_set_active_port_dpll(struct intel_crtc_state *crtc_state, enum icl_port_dpll_id port_dpll_id)
```

select the active port DPLL for a given CRTC

**Parameters**

- `struct intel_crtc_state *crtc_state`: state for the CRTC to select the DPLL for
- `enum icl_port_dpll_id port_dpll_id`: the active **port_dpll_id** to select

**Description**

Select the given **port_dpll_id** instance from the DPLLs reserved for the
CRTC.

#### <a id="c-intel_dpll_init"></a>`intel_dpll_init()`

```c
void intel_dpll_init(struct intel_display *display)
```

Initialize DPLLs

**Parameters**

- `struct intel_display *display`: intel_display device

**Description**

Initialize DPLLs for **display**.

#### <a id="c-intel_dpll_compute"></a>`intel_dpll_compute()`

```c
int intel_dpll_compute(struct intel_atomic_state *state, struct intel_crtc *crtc, struct intel_encoder *encoder)
```

compute DPLL state CRTC and encoder combination

**Parameters**

- `struct intel_atomic_state *state`: atomic state
- `struct intel_crtc *crtc`: CRTC to compute DPLLs for
- `struct intel_encoder *encoder`: encoder

**Description**

This function computes the DPLL state for the given CRTC and encoder.

The new configuration in the atomic commit **state** is made effective by
calling [`intel_dpll_swap_state()`](#c-intel_dpll_swap_state).

**Return**

0 on success, negative error code on failure.

#### <a id="c-intel_dpll_reserve"></a>`intel_dpll_reserve()`

```c
int intel_dpll_reserve(struct intel_atomic_state *state, struct intel_crtc *crtc, struct intel_encoder *encoder)
```

reserve DPLLs for CRTC and encoder combination

**Parameters**

- `struct intel_atomic_state *state`: atomic state
- `struct intel_crtc *crtc`: CRTC to reserve DPLLs for
- `struct intel_encoder *encoder`: encoder

**Description**

This function reserves all required DPLLs for the given CRTC and encoder
combination in the current atomic commit **state** and the new **crtc** atomic
state.

The new configuration in the atomic commit **state** is made effective by
calling [`intel_dpll_swap_state()`](#c-intel_dpll_swap_state).

The reserved DPLLs should be released by calling
[`intel_dpll_release()`](#c-intel_dpll_release).

**Return**

0 if all required DPLLs were successfully reserved,
negative error code otherwise.

#### <a id="c-intel_dpll_release"></a>`intel_dpll_release()`

```c
void intel_dpll_release(struct intel_atomic_state *state, struct intel_crtc *crtc)
```

end use of DPLLs by CRTC in atomic state

**Parameters**

- `struct intel_atomic_state *state`: atomic state
- `struct intel_crtc *crtc`: crtc from which the DPLLs are to be released

**Description**

This function releases all DPLLs reserved by [`intel_dpll_reserve()`](#c-intel_dpll_reserve)
from the current atomic commit **state** and the old **crtc** atomic state.

The new configuration in the atomic commit **state** is made effective by
calling [`intel_dpll_swap_state()`](#c-intel_dpll_swap_state).

#### <a id="c-intel_dpll_update_active"></a>`intel_dpll_update_active()`

```c
void intel_dpll_update_active(struct intel_atomic_state *state, struct intel_crtc *crtc, struct intel_encoder *encoder)
```

update the active DPLL for a CRTC/encoder

**Parameters**

- `struct intel_atomic_state *state`: atomic state
- `struct intel_crtc *crtc`: the CRTC for which to update the active DPLL
- `struct intel_encoder *encoder`: encoder determining the type of port DPLL

**Description**

Update the active DPLL for the given **crtc**/**encoder** in **crtc**'s atomic state,
from the port DPLLs reserved previously by [`intel_dpll_reserve()`](#c-intel_dpll_reserve). The
DPLL selected will be based on the current mode of the encoder's port.

#### <a id="c-intel_dpll_get_freq"></a>`intel_dpll_get_freq()`

```c
int intel_dpll_get_freq(struct intel_display *display, const struct intel_dpll *pll, const struct intel_dpll_hw_state *dpll_hw_state)
```

calculate the DPLL's output frequency

**Parameters**

- `struct intel_display *display`: intel_display device
- `const struct intel_dpll *pll`: DPLL for which to calculate the output frequency
- `const struct intel_dpll_hw_state *dpll_hw_state`: DPLL state from which to calculate the output frequency

**Description**

Return the output frequency corresponding to **pll**'s passed in **dpll_hw_state**.

#### <a id="c-intel_dpll_get_hw_state"></a>`intel_dpll_get_hw_state()`

```c
bool intel_dpll_get_hw_state(struct intel_display *display, struct intel_dpll *pll, struct intel_dpll_hw_state *dpll_hw_state)
```

readout the DPLL's hardware state

**Parameters**

- `struct intel_display *display`: intel_display device instance
- `struct intel_dpll *pll`: DPLL for which to calculate the output frequency
- `struct intel_dpll_hw_state *dpll_hw_state`: DPLL's hardware state

**Description**

Read out **pll**'s hardware state into **dpll_hw_state**.

#### <a id="c-intel_dpll_dump_hw_state"></a>`intel_dpll_dump_hw_state()`

```c
void intel_dpll_dump_hw_state(struct intel_display *display, struct drm_printer *p, const struct intel_dpll_hw_state *dpll_hw_state)
```

dump hw_state

**Parameters**

- `struct intel_display *display`: intel_display structure
- `struct drm_printer *p`: where to print the state to
- `const struct intel_dpll_hw_state *dpll_hw_state`: hw state to be dumped

**Description**

Dumo out the relevant values in **dpll_hw_state**.

#### <a id="c-intel_dpll_compare_hw_state"></a>`intel_dpll_compare_hw_state()`

```c
bool intel_dpll_compare_hw_state(struct intel_display *display, const struct intel_dpll_hw_state *a, const struct intel_dpll_hw_state *b)
```

compare the two states

**Parameters**

- `struct intel_display *display`: intel_display structure
- `const struct intel_dpll_hw_state *a`: first DPLL hw state
- `const struct intel_dpll_hw_state *b`: second DPLL hw state

**Description**

Compare DPLL hw states **a** and **b**.

**Return**

true if the states are equal, false if the differ



#### <a id="c-enum-intel_dpll_id"></a>`enum intel_dpll_id`

possible DPLL ids

**Constants**

- `DPLL_ID_PRIVATE`: non-shared dpll in use
- `DPLL_ID_PCH_PLL_A`: DPLL A in ILK, SNB and IVB
- `DPLL_ID_PCH_PLL_B`: DPLL B in ILK, SNB and IVB
- `DPLL_ID_WRPLL1`: HSW and BDW WRPLL1
- `DPLL_ID_WRPLL2`: HSW and BDW WRPLL2
- `DPLL_ID_SPLL`: HSW and BDW SPLL
- `DPLL_ID_LCPLL_810`: HSW and BDW 0.81 GHz LCPLL
- `DPLL_ID_LCPLL_1350`: HSW and BDW 1.35 GHz LCPLL
- `DPLL_ID_LCPLL_2700`: HSW and BDW 2.7 GHz LCPLL
- `DPLL_ID_SKL_DPLL0`: SKL and later DPLL0
- `DPLL_ID_SKL_DPLL1`: SKL and later DPLL1
- `DPLL_ID_SKL_DPLL2`: SKL and later DPLL2
- `DPLL_ID_SKL_DPLL3`: SKL and later DPLL3
- `DPLL_ID_ICL_DPLL0`: ICL/TGL combo PHY DPLL0
- `DPLL_ID_ICL_DPLL1`: ICL/TGL combo PHY DPLL1
- `DPLL_ID_EHL_DPLL4`: EHL combo PHY DPLL4
- `DPLL_ID_ICL_TBTPLL`: ICL/TGL TBT PLL
- `DPLL_ID_ICL_MGPLL1`:

  - ICL MG PLL 1 port 1 (C),

    TGL TC PLL 1 port 1 (TC1)
- `DPLL_ID_ICL_MGPLL2`:

  - ICL MG PLL 1 port 2 (D)

    TGL TC PLL 1 port 2 (TC2)
- `DPLL_ID_ICL_MGPLL3`:

  - ICL MG PLL 1 port 3 (E)

    TGL TC PLL 1 port 3 (TC3)
- `DPLL_ID_ICL_MGPLL4`:

  - ICL MG PLL 1 port 4 (F)

    TGL TC PLL 1 port 4 (TC4)
- `DPLL_ID_TGL_MGPLL5`: TGL TC PLL port 5 (TC5)
- `DPLL_ID_TGL_MGPLL6`: TGL TC PLL port 6 (TC6)
- `DPLL_ID_DG1_DPLL0`: DG1 combo PHY DPLL0
- `DPLL_ID_DG1_DPLL1`: DG1 combo PHY DPLL1
- `DPLL_ID_DG1_DPLL2`: DG1 combo PHY DPLL2
- `DPLL_ID_DG1_DPLL3`: DG1 combo PHY DPLL3

**Description**

Enumeration of possible IDs for a DPLL. Real shared dpll ids must be >= 0.

#### <a id="c-struct-intel_dpll_state"></a>`struct intel_dpll_state`

hold the DPLL atomic state

**Definition**

```c
struct intel_dpll_state {
    u8 pipe_mask;
    struct intel_dpll_hw_state hw_state;
};
```

**Members**

- `pipe_mask`: mask of pipes using this DPLL, active or not
- `hw_state`: hardware configuration for the DPLL stored in
  struct `intel_dpll_hw_state`.

**Description**

This structure holds an atomic state for the DPLL, that can represent
either its current state (in struct `intel_shared_dpll`) or a desired
future state which would be applied by an atomic mode set (stored in
a struct `intel_atomic_state`).

See also `intel_reserve_shared_dplls()` and `intel_release_shared_dplls()`.

#### <a id="c-struct-dpll_info"></a>`struct dpll_info`

display PLL platform specific info

**Definition**

```c
struct dpll_info {
    const char *name;
    const struct intel_dpll_funcs *funcs;
    enum intel_dpll_id id;
    enum intel_display_power_domain power_domain;
    bool always_on;
    bool is_alt_port_dpll;
};
```

**Members**

- `name`: DPLL name; used for logging
- `funcs`: platform specific hooks
- `id`: unique identifier for this DPLL
- `power_domain`: extra power domain required by the DPLL
- `always_on`: Inform the state checker that the DPLL is kept enabled even if
  not in use by any CRTC.
- `is_alt_port_dpll`: Inform the state checker that the DPLL can be used as a fallback
  (for TC->TBT fallback).

#### <a id="c-struct-intel_dpll"></a>`struct intel_dpll`

display PLL with tracked state and users

**Definition**

```c
struct intel_dpll {
    struct intel_dpll_state state;
    u8 index;
    u8 active_mask;
    bool on;
    const struct dpll_info *info;
    struct ref_tracker *wakeref;
};
```

**Members**

- `state`: Store the state for the pll, including its hw state
  and CRTCs using it.
- `index`: index for atomic state
- `active_mask`: mask of active pipes (i.e. DPMS on) using this DPLL
- `on`: is the PLL actually active? Disabled during modeset
- `info`: platform specific info
- `wakeref`: In some platforms a device-level runtime pm reference may
  need to be grabbed to disable DC states while this DPLL is enabled


<a id="rst-display-state-buffer"></a>

### Display State Buffer


A DSB (Display State Buffer) is a queue of MMIO instructions in the memory
which can be offloaded to DSB HW in Display Controller. DSB HW is a DMA
engine that can be programmed to download the DSB from memory.
It allows driver to batch submit display HW programming. This helps to
reduce loading time and CPU activity, thereby making the context switch
faster. DSB Support added from Gen12 Intel graphics based platform.

DSB's can access only the pipe, plane, and transcoder Data Island Packet
registers.

DSB HW can support only register writes (both indexed and direct MMIO
writes). There are no registers reads possible with DSB HW engine.



#### <a id="c-intel_dsb_reg_write_indexed"></a>`intel_dsb_reg_write_indexed()`

```c
void intel_dsb_reg_write_indexed(struct intel_dsb *dsb, i915_reg_t reg, u32 val)
```

Emit indexed register write to the DSB context

**Parameters**

- `struct intel_dsb *dsb`: DSB context
- `i915_reg_t reg`: register address.
- `u32 val`: value.

**Description**

This function is used for writing register-value pair in command
buffer of DSB.

Note that indexed writes are slower than normal MMIO writes
for a small number (less than 5 or so) of writes to the same
register.

#### <a id="c-intel_dsb_commit"></a>`intel_dsb_commit()`

```c
void intel_dsb_commit(struct intel_dsb *dsb)
```

Trigger workload execution of DSB.

**Parameters**

- `struct intel_dsb *dsb`: DSB context

**Description**

This function is used to do actual write to hardware using DSB.

#### <a id="c-intel_dsb_prepare"></a>`intel_dsb_prepare()`

```c
struct intel_dsb * intel_dsb_prepare(struct intel_atomic_state *state, struct intel_crtc *crtc, enum intel_dsb_id dsb_id, unsigned int max_cmds)
```

Allocate, pin and map the DSB command buffer.

**Parameters**

- `struct intel_atomic_state *state`: the atomic state
- `struct intel_crtc *crtc`: the CRTC
- `enum intel_dsb_id dsb_id`: the DSB engine to use
- `unsigned int max_cmds`: number of commands we need to fit into command buffer

**Description**

This function prepare the command buffer which is used to store dsb
instructions with data.

**Return**

DSB context, NULL on failure

#### <a id="c-intel_dsb_cleanup"></a>`intel_dsb_cleanup()`

```c
void intel_dsb_cleanup(struct intel_dsb *dsb)
```

To cleanup DSB context.

**Parameters**

- `struct intel_dsb *dsb`: DSB context

**Description**

This function cleanup the DSB context by unpinning and releasing
the VMA object associated with it.


<a id="rst-gt-programming"></a>

## GT Programming

<a id="rst-multicast-replicated-mcr-registers"></a>

### Multicast/Replicated (MCR) Registers


Some GT registers are designed as "multicast" or "replicated" registers:
multiple instances of the same register share a single MMIO offset.  MCR
registers are generally used when the hardware needs to potentially track
independent values of a register per hardware unit (e.g., per-subslice,
per-L3bank, etc.).  The specific types of replication that exist vary
per-platform.

MMIO accesses to MCR registers are controlled according to the settings
programmed in the platform's MCR_SELECTOR register(s).  MMIO writes to MCR
registers can be done in either a (i.e., a single write updates all
instances of the register to the same value) or unicast (a write updates only
one specific instance).  Reads of MCR registers always operate in a unicast
manner regardless of how the multicast/unicast bit is set in MCR_SELECTOR.
Selection of a specific MCR instance for unicast operations is referred to
as "steering."

If MCR register operations are steered toward a hardware unit that is
fused off or currently powered down due to power gating, the MMIO operation
is "terminated" by the hardware.  Terminated read operations will return a
value of zero and terminated unicast write operations will be silently
ignored.



#### <a id="c-intel_gt_mcr_lock"></a>`intel_gt_mcr_lock()`

```c
void intel_gt_mcr_lock(struct intel_gt *gt, unsigned long *flags)
```

Acquire MCR steering lock

**Parameters**

- `struct intel_gt *gt`: GT structure
- `unsigned long *flags`: storage to save IRQ flags to

**Description**

Performs locking to protect the steering for the duration of an MCR
operation.  On MTL and beyond, a hardware lock will also be taken to
serialize access not only for the driver, but also for external hardware and
firmware agents.

**Context**

Takes gt->mcr_lock.  uncore->lock should *not* be held when this
function is called, although it may be acquired after this
function call.

#### <a id="c-intel_gt_mcr_unlock"></a>`intel_gt_mcr_unlock()`

```c
void intel_gt_mcr_unlock(struct intel_gt *gt, unsigned long flags)
```

Release MCR steering lock

**Parameters**

- `struct intel_gt *gt`: GT structure
- `unsigned long flags`: IRQ flags to restore

**Description**

Releases the lock acquired by [`intel_gt_mcr_lock()`](#c-intel_gt_mcr_lock).

**Context**

Releases gt->mcr_lock

#### <a id="c-intel_gt_mcr_lock_sanitize"></a>`intel_gt_mcr_lock_sanitize()`

```c
void intel_gt_mcr_lock_sanitize(struct intel_gt *gt)
```

Sanitize MCR steering lock

**Parameters**

- `struct intel_gt *gt`: GT structure

**Description**

This will be used to sanitize the initial status of the hardware lock
during driver load and resume since there won't be any concurrent access
from other agents at those times, but it's possible that boot firmware
may have left the lock in a bad state.

#### <a id="c-intel_gt_mcr_read"></a>`intel_gt_mcr_read()`

```c
u32 intel_gt_mcr_read(struct intel_gt *gt, i915_mcr_reg_t reg, int group, int instance)
```

read a specific instance of an MCR register

**Parameters**

- `struct intel_gt *gt`: GT structure
- `i915_mcr_reg_t reg`: the MCR register to read
- `int group`: the MCR group
- `int instance`: the MCR instance

**Context**

Takes and releases gt->mcr_lock

**Description**

Returns the value read from an MCR register after steering toward a specific
group/instance.

#### <a id="c-intel_gt_mcr_unicast_write"></a>`intel_gt_mcr_unicast_write()`

```c
void intel_gt_mcr_unicast_write(struct intel_gt *gt, i915_mcr_reg_t reg, u32 value, int group, int instance)
```

write a specific instance of an MCR register

**Parameters**

- `struct intel_gt *gt`: GT structure
- `i915_mcr_reg_t reg`: the MCR register to write
- `u32 value`: value to write
- `int group`: the MCR group
- `int instance`: the MCR instance

**Description**

Write an MCR register in unicast mode after steering toward a specific
group/instance.

**Context**

Calls a function that takes and releases gt->mcr_lock

#### <a id="c-intel_gt_mcr_multicast_write"></a>`intel_gt_mcr_multicast_write()`

```c
void intel_gt_mcr_multicast_write(struct intel_gt *gt, i915_mcr_reg_t reg, u32 value)
```

write a value to all instances of an MCR register

**Parameters**

- `struct intel_gt *gt`: GT structure
- `i915_mcr_reg_t reg`: the MCR register to write
- `u32 value`: value to write

**Description**

Write an MCR register in multicast mode to update all instances.

**Context**

Takes and releases gt->mcr_lock

#### <a id="c-intel_gt_mcr_multicast_write_fw"></a>`intel_gt_mcr_multicast_write_fw()`

```c
void intel_gt_mcr_multicast_write_fw(struct intel_gt *gt, i915_mcr_reg_t reg, u32 value)
```

write a value to all instances of an MCR register

**Parameters**

- `struct intel_gt *gt`: GT structure
- `i915_mcr_reg_t reg`: the MCR register to write
- `u32 value`: value to write

**Description**

Write an MCR register in multicast mode to update all instances.  This
function assumes the caller is already holding any necessary forcewake
domains; use [`intel_gt_mcr_multicast_write()`](#c-intel_gt_mcr_multicast_write) in cases where forcewake should
be obtained automatically.

**Context**

The caller must hold gt->mcr_lock.

#### <a id="c-intel_gt_mcr_multicast_rmw"></a>`intel_gt_mcr_multicast_rmw()`

```c
u32 intel_gt_mcr_multicast_rmw(struct intel_gt *gt, i915_mcr_reg_t reg, u32 clear, u32 set)
```

Performs a multicast RMW operations

**Parameters**

- `struct intel_gt *gt`: GT structure
- `i915_mcr_reg_t reg`: the MCR register to read and write
- `u32 clear`: bits to clear during RMW
- `u32 set`: bits to set during RMW

**Description**

Performs a read-modify-write on an MCR register in a multicast manner.
This operation only makes sense on MCR registers where all instances are
expected to have the same value.  The read will target any non-terminated
instance and the write will be applied to all instances.

This function assumes the caller is already holding any necessary forcewake
domains; use [`intel_gt_mcr_multicast_rmw()`](#c-intel_gt_mcr_multicast_rmw) in cases where forcewake should
be obtained automatically.

Returns the old (unmodified) value read.

**Context**

Calls functions that take and release gt->mcr_lock

#### <a id="c-intel_gt_mcr_get_nonterminated_steering"></a>`intel_gt_mcr_get_nonterminated_steering()`

```c
void intel_gt_mcr_get_nonterminated_steering(struct intel_gt *gt, i915_mcr_reg_t reg, u8 *group, u8 *instance)
```

find group/instance values that will steer a register to a non-terminated instance

**Parameters**

- `struct intel_gt *gt`: GT structure
- `i915_mcr_reg_t reg`: register for which the steering is required
- `u8 *group`: return variable for group steering
- `u8 *instance`: return variable for instance steering

**Description**

This function returns a group/instance pair that is guaranteed to work for
read steering of the given register. Note that a value will be returned even
if the register is not replicated and therefore does not actually require
steering.

#### <a id="c-intel_gt_mcr_read_any_fw"></a>`intel_gt_mcr_read_any_fw()`

```c
u32 intel_gt_mcr_read_any_fw(struct intel_gt *gt, i915_mcr_reg_t reg)
```

reads one instance of an MCR register

**Parameters**

- `struct intel_gt *gt`: GT structure
- `i915_mcr_reg_t reg`: register to read

**Description**

Reads a GT MCR register.  The read will be steered to a non-terminated
instance (i.e., one that isn't fused off or powered down by power gating).
This function assumes the caller is already holding any necessary forcewake
domains; use [`intel_gt_mcr_read_any()`](#c-intel_gt_mcr_read_any) in cases where forcewake should be
obtained automatically.

Returns the value from a non-terminated instance of **reg**.

**Context**

The caller must hold gt->mcr_lock.

#### <a id="c-intel_gt_mcr_read_any"></a>`intel_gt_mcr_read_any()`

```c
u32 intel_gt_mcr_read_any(struct intel_gt *gt, i915_mcr_reg_t reg)
```

reads one instance of an MCR register

**Parameters**

- `struct intel_gt *gt`: GT structure
- `i915_mcr_reg_t reg`: register to read

**Description**

Reads a GT MCR register.  The read will be steered to a non-terminated
instance (i.e., one that isn't fused off or powered down by power gating).

Returns the value from a non-terminated instance of **reg**.

**Context**

Calls a function that takes and releases gt->mcr_lock.

#### <a id="c-intel_gt_mcr_get_ss_steering"></a>`intel_gt_mcr_get_ss_steering()`

```c
void intel_gt_mcr_get_ss_steering(struct intel_gt *gt, unsigned int dss, unsigned int *group, unsigned int *instance)
```

returns the group/instance steering for a SS

**Parameters**

- `struct intel_gt *gt`: GT structure
- `unsigned int dss`: DSS ID to obtain steering for
- `unsigned int *group`: pointer to storage for steering group ID
- `unsigned int *instance`: pointer to storage for steering instance ID

**Description**

Returns the steering IDs (via the **group** and **instance** parameters) that
correspond to a specific subslice/DSS ID.

#### <a id="c-intel_gt_mcr_wait_for_reg"></a>`intel_gt_mcr_wait_for_reg()`

```c
int intel_gt_mcr_wait_for_reg(struct intel_gt *gt, i915_mcr_reg_t reg, u32 mask, u32 value, unsigned int fast_timeout_us, unsigned int slow_timeout_ms)
```

wait until MCR register matches expected state

**Parameters**

- `struct intel_gt *gt`: GT structure
- `i915_mcr_reg_t reg`: the register to read
- `u32 mask`: mask to apply to register value
- `u32 value`: value to wait for
- `unsigned int fast_timeout_us`: fast timeout in microsecond for atomic/tight wait
- `unsigned int slow_timeout_ms`: slow timeout in millisecond

**Description**

This routine waits until the target register **reg** contains the expected
**value** after applying the **mask**, i.e. it waits until

```text
(intel_gt_mcr_read_any_fw(gt, reg) & mask) == value
```

Otherwise, the wait will timeout after **slow_timeout_ms** milliseconds.
For atomic context **slow_timeout_ms** must be zero and **fast_timeout_us**
must be not larger than 20,0000 microseconds.

This function is basically an MCR-friendly version of
[`__intel_wait_for_register_fw()`](#c-__intel_wait_for_register_fw).  Generally this function will only be used
on GAM registers which are a bit special --- although they're MCR registers,
reads (e.g., waiting for status updates) are always directed to the primary
instance.

Note that this routine assumes the caller holds forcewake asserted, it is
not suitable for very long waits.

**Context**

Calls a function that takes and releases gt->mcr_lock

**Return**

0 if the register matches the desired condition, or -ETIMEDOUT.


<a id="rst-memory-management-and-command-submission"></a>

## Memory Management and Command Submission

This sections covers all things related to the GEM implementation in the i915 driver.

<a id="rst-intel-gpu-basics"></a>

### Intel GPU Basics

An Intel GPU has multiple engines. There are several engine types:

- Render Command Streamer (RCS). An engine for rendering 3D and performing compute.

- Blitting Command Streamer (BCS). An engine for performing blitting and/or copying operations.

- Video Command Streamer. An engine used for video encoding and decoding. Also sometimes called 'BSD' in hardware documentation.

- Video Enhancement Command Streamer (VECS). An engine for video enhancement. Also sometimes called 'VEBOX' in hardware documentation.

- Compute Command Streamer (CCS). An engine that has access to the media and GPGPU pipelines, but not the 3D pipeline.

- Graphics Security Controller (GSCCS). A dedicated engine for internal communication with GSC controller on security related tasks like High-bandwidth Digital Content Protection (HDCP), Protected Xe Path (PXP), and HuC firmware authentication.

The Intel GPU family is a family of integrated GPU's using Unified Memory Access. For having the GPU "do work", user space will feed the GPU batch buffers via one of the ioctls `DRM_IOCTL_I915_GEM_EXECBUFFER2` or `DRM_IOCTL_I915_GEM_EXECBUFFER2_WR`. Most such batchbuffers will instruct the GPU to perform work (for example rendering) and that work needs memory from which to read and memory to which to write. All memory is encapsulated within GEM buffer objects (usually created with the ioctl `DRM_IOCTL_I915_GEM_CREATE`). An ioctl providing a batchbuffer for the GPU to create will also list all GEM buffer objects that the batchbuffer reads and/or writes. For implementation details of memory management see [GEM BO Management Implementation Details](<#rst-gem-bo-management-implementation-details>).

The i915 driver allows user space to create a context via the ioctl `DRM_IOCTL_I915_GEM_CONTEXT_CREATE` which is identified by a 32-bit integer. Such a context should be viewed by user-space as -loosely- analogous to the idea of a CPU process of an operating system. The i915 driver guarantees that commands issued to a fixed context are to be executed so that writes of a previously issued command are seen by reads of following commands. Actions issued between different contexts (even if from the same file descriptor) are NOT given that guarantee and the only way to synchronize across contexts (even from the same file descriptor) is through the use of fences. At least as far back as Gen4, also have that a context carries with it a GPU HW context; the HW context is essentially (most of at least) the state of a GPU. In addition to the ordering guarantees, the kernel will restore GPU state via HW context when commands are issued to a context, this saves user space the need to restore (most of at least) the GPU state at the start of each batchbuffer. The non-deprecated ioctls to submit batchbuffer work can pass that ID (in the lower bits of drm_i915_gem_execbuffer2::rsvd1) to identify what context to use with the command.

The GPU has its own memory management and address space. The kernel driver maintains the memory translation table for the GPU. For older GPUs (i.e. those before Gen8), there is a single global such translation table, a global Graphics Translation Table (GTT). For newer generation GPUs each context has its own translation table, called Per-Process Graphics Translation Table (PPGTT). Of important note, is that although PPGTT is named per-process it is actually per context. When user space submits a batchbuffer, the kernel walks the list of GEM buffer objects used by the batchbuffer and guarantees that not only is the memory of each such GEM buffer object resident but it is also present in the (PP)GTT. If the GEM buffer object is not yet placed in the (PP)GTT, then it is given an address. Two consequences of this are: the kernel needs to edit the batchbuffer submitted to write the correct value of the GPU address when a GEM BO is assigned a GPU address and the kernel might evict a different GEM BO from the (PP)GTT to make address room for another GEM BO. Consequently, the ioctls submitting a batchbuffer for execution also include a list of all locations within buffers that refer to GPU-addresses so that the kernel can edit the buffer correctly. This process is dubbed relocation.

<a id="rst-locking-guidelines"></a>

### Locking Guidelines

> [!NOTE]
>
> This is a description of how the locking should be after refactoring is done. Does not necessarily reflect what the locking looks like while WIP.

1. All locking rules and interface contracts with cross-driver interfaces (dma-buf, dma_fence) need to be followed.

2. dma_resv will be the outermost lock (when needed) and ww_acquire_ctx is to be hoisted at highest level and passed down within i915_gem_ctx in the call chain

3. While holding lru/memory manager (buddy, drm_mm, whatever) locks system memory allocations are not allowed

4. Do not nest different lru/memory manager locks within each other. Take them in turn to update memory allocations, relying on the object’s dma_resv ww_mutex to serialize against other operations.

5. The suggestion for lru/memory managers locks is that they are small enough to be spinlocks.

6. All features need to come with exhaustive kernel selftests and/or IGT tests when appropriate

7. All LMEM uAPI paths need to be fully restartable (\_interruptible() for all locks/waits/sleeps)

   > - Error handling validation through signal injection. Still the best strategy we have for validating GEM uAPI corner cases. Must be excessively used in the IGT, and we need to check that we really have full path coverage of all error cases.
   >
   > - -EDEADLK handling with ww_mutex

<a id="rst-gem-bo-management-implementation-details"></a>

### GEM BO Management Implementation Details


A VMA represents a GEM BO that is bound into an address space. Therefore, a
VMA's presence cannot be guaranteed before binding, or after unbinding the
object into/from the address space.

To make things as simple as possible (ie. no refcounting), a VMA's lifetime
will always be \<= an objects lifetime. So object refcounting should cover us.


<a id="rst-buffer-object-eviction"></a>

### Buffer Object Eviction

This section documents the interface functions for evicting buffer objects to make space available in the virtual gpu address spaces. Note that this is mostly orthogonal to shrinking buffer objects caches, which has the goal to make main memory (shared with the gpu through the unified memory architecture) available.


#### <a id="c-i915_gem_evict_something"></a>`i915_gem_evict_something()`

```c
int i915_gem_evict_something(struct i915_address_space *vm, struct i915_gem_ww_ctx *ww, u64 min_size, u64 alignment, unsigned long color, u64 start, u64 end, unsigned flags)
```

Evict vmas to make room for binding a new one

**Parameters**

- `struct i915_address_space *vm`: address space to evict from
- `struct i915_gem_ww_ctx *ww`: An optional struct i915_gem_ww_ctx.
- `u64 min_size`: size of the desired free space
- `u64 alignment`: alignment constraint of the desired free space
- `unsigned long color`: color for the desired space
- `u64 start`: start (inclusive) of the range from which to evict objects
- `u64 end`: end (exclusive) of the range from which to evict objects
- `unsigned flags`: additional flags to control the eviction algorithm

**Description**

This function will try to evict vmas until a free space satisfying the
requirements is found. Callers must check first whether any such hole exists
already before calling this function.

This function is used by the object/vma binding code.

Since this function is only used to free up virtual address space it only
ignores pinned vmas, and not object where the backing storage itself is
pinned. Hence obj->pages_pin_count does not protect against eviction.

To clarify: This is for freeing up virtual address space, not for freeing
memory in e.g. the shrinker.

#### <a id="c-i915_gem_evict_for_node"></a>`i915_gem_evict_for_node()`

```c
int i915_gem_evict_for_node(struct i915_address_space *vm, struct i915_gem_ww_ctx *ww, struct drm_mm_node *target, unsigned int flags)
```

Evict vmas to make room for binding a new one

**Parameters**

- `struct i915_address_space *vm`: address space to evict from
- `struct i915_gem_ww_ctx *ww`: An optional struct i915_gem_ww_ctx.
- `struct drm_mm_node *target`: range (and color) to evict for
- `unsigned int flags`: additional flags to control the eviction algorithm

**Description**

This function will try to evict vmas that overlap the target node.

To clarify: This is for freeing up virtual address space, not for freeing
memory in e.g. the shrinker.

#### <a id="c-i915_gem_evict_vm"></a>`i915_gem_evict_vm()`

```c
int i915_gem_evict_vm(struct i915_address_space *vm, struct i915_gem_ww_ctx *ww, struct drm_i915_gem_object **busy_bo)
```

Evict all idle vmas from a vm

**Parameters**

- `struct i915_address_space *vm`: Address space to cleanse
- `struct i915_gem_ww_ctx *ww`: An optional struct i915_gem_ww_ctx. If not NULL, i915_gem_evict_vm
  will be able to evict vma's locked by the ww as well.
- `struct drm_i915_gem_object **busy_bo`: Optional pointer to struct drm_i915_gem_object. If not NULL, then
  in the event [`i915_gem_evict_vm()`](#c-i915_gem_evict_vm) is unable to trylock an object for eviction,
  then **busy_bo** will point to it. -EBUSY is also returned. The caller must drop
  the vm->mutex, before trying again to acquire the contended lock. The caller
  also owns a reference to the object.

**Description**

This function evicts all vmas from a vm.

This is used by the execbuf code as a last-ditch effort to defragment the
address space.

To clarify: This is for freeing up virtual address space, not for freeing
memory in e.g. the shrinker.


<a id="rst-buffer-object-memory-shrinking"></a>

### Buffer Object Memory Shrinking

This section documents the interface function for shrinking memory usage of buffer object caches. Shrinking is used to make main memory available. Note that this is mostly orthogonal to evicting buffer objects, which has the goal to make space in gpu virtual address spaces.


#### <a id="c-i915_gem_shrink"></a>`i915_gem_shrink()`

```c
unsigned long i915_gem_shrink(struct i915_gem_ww_ctx *ww, struct drm_i915_private *i915, unsigned long target, unsigned long *nr_scanned, unsigned int shrink)
```

Shrink buffer object caches

**Parameters**

- `struct i915_gem_ww_ctx *ww`: i915 gem ww acquire ctx, or NULL
- `struct drm_i915_private *i915`: i915 device
- `unsigned long target`: amount of memory to make available, in pages
- `unsigned long *nr_scanned`: optional output for number of pages scanned (incremental)
- `unsigned int shrink`: control flags for selecting cache types

**Description**

This function is the main interface to the shrinker. It will try to release
up to **target** pages of main memory backing storage from buffer objects.
Selection of the specific caches can be done with **flags**. This is e.g. useful
when purgeable objects should be removed from caches preferentially.

Note that it's not guaranteed that released amount is actually available as
free system memory - the pages might still be in-used to due to other reasons
(like cpu mmaps) or the mm core has reused them before we could grab them.
Therefore code that needs to explicitly shrink buffer objects caches (e.g. to
avoid deadlocks in memory reclaim) must fall back to [`i915_gem_shrink_all()`](#c-i915_gem_shrink_all).

Also note that any kind of pinning (both per-vma address space pins and
backing storage pins at the buffer object level) result in the shrinker code
having to skip the object.

**Return**

The number of pages of backing storage actually released.

#### <a id="c-i915_gem_shrink_all"></a>`i915_gem_shrink_all()`

```c
unsigned long i915_gem_shrink_all(struct drm_i915_private *i915)
```

Shrink buffer object caches completely

**Parameters**

- `struct drm_i915_private *i915`: i915 device

**Description**

This is a simple wrapper around [`i915_gem_shrink()`](#c-i915_gem_shrink) to aggressively shrink all
caches completely. It also first waits for and retires all outstanding
requests to also be able to release backing storage for active objects.

This should only be used in code to intentionally quiescent the gpu or as a
last-ditch effort when memory seems to have run out.

**Return**

The number of pages of backing storage actually released.

#### <a id="c-i915_gem_object_make_unshrinkable"></a>`i915_gem_object_make_unshrinkable()`

```c
void i915_gem_object_make_unshrinkable(struct drm_i915_gem_object *obj)
```

Hide the object from the shrinker. By default all object types that support shrinking(see IS_SHRINKABLE), will also make the object visible to the shrinker after allocating the system memory pages.

**Parameters**

- `struct drm_i915_gem_object *obj`: The GEM object.

**Description**

This is typically used for special kernel internal objects that can't be
easily processed by the shrinker, like if they are perma-pinned.

#### <a id="c-__i915_gem_object_make_shrinkable"></a>`__i915_gem_object_make_shrinkable()`

```c
void __i915_gem_object_make_shrinkable(struct drm_i915_gem_object *obj)
```

Move the object to the tail of the shrinkable list. Objects on this list might be swapped out. Used with WILLNEED objects.

**Parameters**

- `struct drm_i915_gem_object *obj`: The GEM object.

**Description**

DO NOT USE. This is intended to be called on very special objects that don't
yet have mm.pages, but are guaranteed to have potentially reclaimable pages
underneath.

#### <a id="c-__i915_gem_object_make_purgeable"></a>`__i915_gem_object_make_purgeable()`

```c
void __i915_gem_object_make_purgeable(struct drm_i915_gem_object *obj)
```

Move the object to the tail of the purgeable list. Objects on this list might be swapped out. Used with DONTNEED objects.

**Parameters**

- `struct drm_i915_gem_object *obj`: The GEM object.

**Description**

DO NOT USE. This is intended to be called on very special objects that don't
yet have mm.pages, but are guaranteed to have potentially reclaimable pages
underneath.

#### <a id="c-i915_gem_object_make_shrinkable"></a>`i915_gem_object_make_shrinkable()`

```c
void i915_gem_object_make_shrinkable(struct drm_i915_gem_object *obj)
```

Move the object to the tail of the shrinkable list. Objects on this list might be swapped out. Used with WILLNEED objects.

**Parameters**

- `struct drm_i915_gem_object *obj`: The GEM object.

**Description**

MUST only be called on objects which have backing pages.

MUST be balanced with previous call to [`i915_gem_object_make_unshrinkable()`](#c-i915_gem_object_make_unshrinkable).

#### <a id="c-i915_gem_object_make_purgeable"></a>`i915_gem_object_make_purgeable()`

```c
void i915_gem_object_make_purgeable(struct drm_i915_gem_object *obj)
```

Move the object to the tail of the purgeable list. Used with DONTNEED objects. Unlike with shrinkable objects, the shrinker will attempt to discard the backing pages, instead of trying to swap them out.

**Parameters**

- `struct drm_i915_gem_object *obj`: The GEM object.

**Description**

MUST only be called on objects which have backing pages.

MUST be balanced with previous call to [`i915_gem_object_make_unshrinkable()`](#c-i915_gem_object_make_unshrinkable).


<a id="rst-batchbuffer-parsing"></a>

### Batchbuffer Parsing


Motivation:
Certain OpenGL features (e.g. transform feedback, performance monitoring)
require userspace code to submit batches containing commands such as
MI_LOAD_REGISTER_IMM to access various registers. Unfortunately, some
generations of the hardware will noop these commands in "unsecure" batches
(which includes all userspace batches submitted via i915) even though the
commands may be safe and represent the intended programming model of the
device.

The software command parser is similar in operation to the command parsing
done in hardware for unsecure batches. However, the software parser allows
some operations that would be noop'd by hardware, if the parser determines
the operation is safe, and submits the batch as "secure" to prevent hardware
parsing.

Threats:
At a high level, the hardware (and software) checks attempt to prevent
granting userspace undue privileges. There are three categories of privilege.

First, commands which are explicitly defined as privileged or which should
only be used by the kernel driver. The parser rejects such commands

Second, commands which access registers. To support correct/enhanced
userspace functionality, particularly certain OpenGL extensions, the parser
provides a whitelist of registers which userspace may safely access

Third, commands which access privileged memory (i.e. GGTT, HWS page, etc).
The parser always rejects such commands.

The majority of the problematic commands fall in the MI_* range, with only a
few specific commands on each engine (e.g. PIPE_CONTROL and MI_FLUSH_DW).

Implementation:
Each engine maintains tables of commands and registers which the parser
uses in scanning batch buffers submitted to that engine.

Since the set of commands that the parser must check for is significantly
smaller than the number of commands supported, the parser tables contain only
those commands required by the parser. This generally works because command
opcode ranges have standard command length encodings. So for commands that
the parser does not need to check, it can easily skip them. This is
implemented via a per-engine length decoding vfunc.

Unfortunately, there are a number of commands that do not follow the standard
length encoding for their opcode range, primarily amongst the MI_* commands.
To handle this, the parser provides a way to define explicit "skip" entries
in the per-engine command tables.

Other command table entries map fairly directly to high level categories
mentioned above: rejected, register whitelist. The parser implements a number
of checks, including the privileged memory checks, via a general bitmasking
mechanism.



#### <a id="c-intel_engine_init_cmd_parser"></a>`intel_engine_init_cmd_parser()`

```c
int intel_engine_init_cmd_parser(struct intel_engine_cs *engine)
```

set cmd parser related fields for an engine

**Parameters**

- `struct intel_engine_cs *engine`: the engine to initialize

**Description**

Optionally initializes fields related to batch buffer command parsing in the
struct intel_engine_cs based on whether the platform requires software
command parsing.

#### <a id="c-intel_engine_cleanup_cmd_parser"></a>`intel_engine_cleanup_cmd_parser()`

```c
void intel_engine_cleanup_cmd_parser(struct intel_engine_cs *engine)
```

clean up cmd parser related fields

**Parameters**

- `struct intel_engine_cs *engine`: the engine to clean up

**Description**

Releases any resources related to command parsing that may have been
initialized for the specified engine.

#### <a id="c-intel_engine_cmd_parser"></a>`intel_engine_cmd_parser()`

```c
int intel_engine_cmd_parser(struct intel_engine_cs *engine, struct i915_vma *batch, unsigned long batch_offset, unsigned long batch_length, struct i915_vma *shadow, bool trampoline)
```

parse a batch buffer for privilege violations

**Parameters**

- `struct intel_engine_cs *engine`: the engine on which the batch is to execute
- `struct i915_vma *batch`: the batch buffer in question
- `unsigned long batch_offset`: byte offset in the batch at which execution starts
- `unsigned long batch_length`: length of the commands in batch_obj
- `struct i915_vma *shadow`: validated copy of the batch buffer in question
- `bool trampoline`: true if we need to trampoline into privileged execution

**Description**

Parses the specified batch buffer looking for privilege violations as
described in the overview.

**Return**

non-zero if the parser finds violations or otherwise fails; -EACCES
if the batch appears legal but should use hardware parsing

#### <a id="c-i915_cmd_parser_get_version"></a>`i915_cmd_parser_get_version()`

```c
int i915_cmd_parser_get_version(struct drm_i915_private *dev_priv)
```

get the cmd parser version number

**Parameters**

- `struct drm_i915_private *dev_priv`: i915 device private

**Description**

The cmd parser maintains a simple increasing integer version number suitable
for passing to userspace clients to determine what operations are permitted.

**Return**

the current version number of the cmd parser


<a id="rst-user-batchbuffer-execution"></a>

### User Batchbuffer Execution


#### <a id="c-struct-i915_gem_engines"></a>`struct i915_gem_engines`

A set of engines

**Definition**

```c
struct i915_gem_engines {
    union {
        struct list_head link;
        struct rcu_head rcu;
    };
    struct i915_sw_fence fence;
    struct i915_gem_context *ctx;
    unsigned int num_engines;
    struct intel_context *engines[];
};
```

**Members**

- `{unnamed_union}`: anonymous
- `link`: Link in i915_gem_context::stale::engines
- `rcu`: RCU to use when freeing
- `fence`: Fence used for delayed destruction of engines
- `ctx`: i915_gem_context backpointer
- `num_engines`: Number of engines in this set
- `engines`: Array of engines

#### <a id="c-struct-i915_gem_engines_iter"></a>`struct i915_gem_engines_iter`

Iterator for an i915_gem_engines set

**Definition**

```c
struct i915_gem_engines_iter {
    unsigned int idx;
    const struct i915_gem_engines *engines;
};
```

**Members**

- `idx`: Index into i915_gem_engines::engines
- `engines`: Engine set being iterated

#### <a id="c-enum-i915_gem_engine_type"></a>`enum i915_gem_engine_type`

Describes the type of an i915_gem_proto_engine

**Constants**

- `I915_GEM_ENGINE_TYPE_INVALID`: An invalid engine
- `I915_GEM_ENGINE_TYPE_PHYSICAL`: A single physical engine
- `I915_GEM_ENGINE_TYPE_BALANCED`: A load-balanced engine set
- `I915_GEM_ENGINE_TYPE_PARALLEL`: A parallel engine set

#### <a id="c-struct-i915_gem_proto_engine"></a>`struct i915_gem_proto_engine`

prototype engine

**Definition**

```c
struct i915_gem_proto_engine {
    enum i915_gem_engine_type type;
    struct intel_engine_cs *engine;
    unsigned int num_siblings;
    unsigned int width;
    struct intel_engine_cs **siblings;
    struct intel_sseu sseu;
};
```

**Members**

- `type`: Type of this engine
- `engine`: Engine, for physical
- `num_siblings`: Number of balanced or parallel siblings
- `width`: Width of each sibling
- `siblings`: Balanced siblings or num_siblings * width for parallel
- `sseu`: Client-set SSEU parameters

**Description**

This struct describes an engine that a context may contain.  Engines
have four types:

- I915_GEM_ENGINE_TYPE_INVALID: Invalid engines can be created but they
  show up as a NULL in i915_gem_engines::engines\[i\] and any attempt to
  use them by the user results in -EINVAL.  They are also useful during
  proto-context construction because the client may create invalid
  engines and then set them up later as virtual engines.

- I915_GEM_ENGINE_TYPE_PHYSICAL: A single physical engine, described by
  i915_gem_proto_engine::engine.

- I915_GEM_ENGINE_TYPE_BALANCED: A load-balanced engine set, described
  i915_gem_proto_engine::num_siblings and i915_gem_proto_engine::siblings.

- I915_GEM_ENGINE_TYPE_PARALLEL: A parallel submission engine set, described
  i915_gem_proto_engine::width, i915_gem_proto_engine::num_siblings, and
  i915_gem_proto_engine::siblings.

#### <a id="c-struct-i915_gem_proto_context"></a>`struct i915_gem_proto_context`

prototype context

**Definition**

```c
struct i915_gem_proto_context {
    struct drm_i915_file_private *fpriv;
    struct i915_address_space *vm;
    unsigned long user_flags;
    struct i915_sched_attr sched;
    int num_user_engines;
    struct i915_gem_proto_engine *user_engines;
    struct intel_sseu legacy_rcs_sseu;
    bool single_timeline;
    bool uses_protected_content;
    intel_wakeref_t pxp_wakeref;
};
```

**Members**

- `fpriv`: Client which creates the context
- `vm`: See [`i915_gem_context.vm`](#c-struct-i915_gem_context)
- `user_flags`: See [`i915_gem_context.user_flags`](#c-struct-i915_gem_context)
- `sched`: See [`i915_gem_context.sched`](#c-struct-i915_gem_context)
- `num_user_engines`: Number of user-specified engines or -1
- `user_engines`: User-specified engines
- `legacy_rcs_sseu`: Client-set SSEU parameters for the legacy RCS
- `single_timeline`: See See [`i915_gem_context.syncobj`](#c-struct-i915_gem_context)
- `uses_protected_content`: See [`i915_gem_context.uses_protected_content`](#c-struct-i915_gem_context)
- `pxp_wakeref`: See [`i915_gem_context.pxp_wakeref`](#c-struct-i915_gem_context)

**Description**

The struct i915_gem_proto_context represents the creation parameters for
a struct i915_gem_context.  This is used to gather parameters provided
either through creation flags or via SET_CONTEXT_PARAM so that, when we
create the final i915_gem_context, those parameters can be immutable.

The context uAPI allows for two methods of setting context parameters:
SET_CONTEXT_PARAM and CONTEXT_CREATE_EXT_SETPARAM.  The former is
allowed to be called at any time while the later happens as part of
GEM_CONTEXT_CREATE.  When these were initially added, Currently,
everything settable via one is settable via the other.  While some
params are fairly simple and setting them on a live context is harmless
such the context priority, others are far trickier such as the VM or the
set of engines.  To avoid some truly nasty race conditions, we don't
allow setting the VM or the set of engines on live contexts.

The way we dealt with this without breaking older userspace that sets
the VM or engine set via SET_CONTEXT_PARAM is to delay the creation of
the actual context until after the client is done configuring it with
SET_CONTEXT_PARAM.  From the perspective of the client, it has the same
u32 context ID the whole time.  From the perspective of i915, however,
it's an i915_gem_proto_context right up until the point where we attempt
to do something which the proto-context can't handle at which point the
real context gets created.

This is accomplished via a little xarray dance.  When GEM_CONTEXT_CREATE
is called, we create a proto-context, reserve a slot in context_xa but
leave it NULL, the proto-context in the corresponding slot in
proto_context_xa.  Then, whenever we go to look up a context, we first
check context_xa.  If it's there, we return the i915_gem_context and
we're done.  If it's not, we look in proto_context_xa and, if we find it
there, we create the actual context and kill the proto-context.

At the time we made this change (April, 2021), we did a fairly complete
audit of existing userspace to ensure this wouldn't break anything:

- Mesa/i965 didn't use the engines or VM APIs at all

- Mesa/ANV used the engines API but via CONTEXT_CREATE_EXT_SETPARAM and
  didn't use the VM API.

- Mesa/iris didn't use the engines or VM APIs at all

- The open-source compute-runtime didn't yet use the engines API but
  did use the VM API via SET_CONTEXT_PARAM.  However, CONTEXT_SETPARAM
  was always the second ioctl on that context, immediately following
  GEM_CONTEXT_CREATE.

- The media driver sets engines and bonding/balancing via
  SET_CONTEXT_PARAM.  However, CONTEXT_SETPARAM to set the VM was
  always the second ioctl on that context, immediately following
  GEM_CONTEXT_CREATE and setting engines immediately followed that.

In order for this dance to work properly, any modification to an
i915_gem_proto_context that is exposed to the client via
drm_i915_file_private::proto_context_xa must be guarded by
drm_i915_file_private::proto_context_lock.  The exception is when a
proto-context has not yet been exposed such as when handling
CONTEXT_CREATE_SET_PARAM during GEM_CONTEXT_CREATE.

#### <a id="c-struct-i915_gem_context"></a>`struct i915_gem_context`

client state

**Definition**

```c
struct i915_gem_context {
        struct drm_i915_private *i915;
        struct drm_i915_file_private *file_priv;
        struct i915_gem_engines  *engines;
        struct mutex engines_mutex;
        struct drm_syncobj *syncobj;
        struct i915_address_space *vm;
        struct pid *pid;
        struct list_head link;
        struct i915_drm_client *client;
        struct list_head client_link;
        struct kref ref;
        struct work_struct release_work;
        struct rcu_head rcu;
        unsigned long user_flags;
    #define UCONTEXT_NO_ERROR_CAPTURE       1;
    #define UCONTEXT_BANNABLE               2;
    #define UCONTEXT_RECOVERABLE            3;
    #define UCONTEXT_PERSISTENCE            4;
    #define UCONTEXT_LOW_LATENCY            5;
        unsigned long flags;
    #define CONTEXT_CLOSED                  0;
    #define CONTEXT_USER_ENGINES            1;
        bool uses_protected_content;
        intel_wakeref_t pxp_wakeref;
        struct mutex mutex;
        struct i915_sched_attr sched;
        atomic_t guilty_count;
        atomic_t active_count;
        unsigned long hang_timestamp[2];
    #define CONTEXT_FAST_HANG_JIFFIES (120 * HZ);
        u8 remap_slice;
        struct radix_tree_root handles_vma;
        struct mutex lut_mutex;
        char name[TASK_COMM_LEN + 8];
        struct {
            spinlock_t lock;
            struct list_head engines;
        } stale;
};
```

**Members**

- `i915`: i915 device backpointer
- `file_priv`: owning file descriptor
- `engines`: User defined engines for this context

  Various uAPI offer the ability to lookup up an
  index from this array to select an engine operate on.

  Multiple logically distinct instances of the same engine
  may be defined in the array, as well as composite virtual
  engines.

  Execbuf uses the I915_EXEC_RING_MASK as an index into this
  array to select which HW context + engine to execute on. For
  the default array, the user_ring_map\[\] is used to translate
  the legacy uABI onto the appropriate index (e.g. both
  I915_EXEC_DEFAULT and I915_EXEC_RENDER select the same
  context, and I915_EXEC_BSD is weird). For a user defined
  array, execbuf uses I915_EXEC_RING_MASK as a plain index.

  User defined by I915_CONTEXT_PARAM_ENGINE (when the
  CONTEXT_USER_ENGINES flag is set).
- `engines_mutex`: guards writes to engines
- `syncobj`: Shared timeline syncobj

  When the SHARED_TIMELINE flag is set on context creation, we
  emulate a single timeline across all engines using this syncobj.
  For every execbuffer2 call, this syncobj is used as both an in-
  and out-fence.  Unlike the real intel_timeline, this doesn't
  provide perfect atomic in-order guarantees if the client races
  with itself by calling execbuffer2 twice concurrently.  However,
  if userspace races with itself, that's not likely to yield well-
  defined results anyway so we choose to not care.
- `vm`: unique address space (GTT)

  In full-ppgtt mode, each context has its own address space ensuring
  complete separation of one client from all others.

  In other modes, this is a NULL pointer with the expectation that
  the caller uses the shared global GTT.
- `pid`: process id of creator

  Note that who created the context may not be the principle user,
  as the context may be shared across a local socket. However,
  that should only affect the default context, all contexts created
  explicitly by the client are expected to be isolated.
- `link`: place with `drm_i915_private.context_list`
- `client`: struct i915_drm_client
- `client_link`: for linking onto `i915_drm_client.ctx_list`
- `ref`: reference count

  A reference to a context is held by both the client who created it
  and on each request submitted to the hardware using the request
  (to ensure the hardware has access to the state until it has
  finished all pending writes). See `i915_gem_context_get()` and
  `i915_gem_context_put()` for access.
- `release_work`: Work item for deferred cleanup, since `i915_gem_context_put()` tends to
  be called from hardirq context.

  FIXME: The only real reason for this is [`i915_gem_engines.fence`](#c-struct-i915_gem_engines), all
  other callers are from process context and need at most some mild
  shuffling to pull the `i915_gem_context_put()` call out of a spinlock.
- `rcu`: rcu_head for deferred freeing.
- `user_flags`: small set of booleans controlled by the user
- `flags`: small set of booleans
- `uses_protected_content`: context uses PXP-encrypted objects.

  This flag can only be set at ctx creation time and it's immutable for
  the lifetime of the context. See I915_CONTEXT_PARAM_PROTECTED_CONTENT
  in uapi/drm/i915_drm.h for more info on setting restrictions and
  expected behaviour of marked contexts.
- `pxp_wakeref`: wakeref to keep the device awake when PXP is in use

  PXP sessions are invalidated when the device is suspended, which in
  turns invalidates all contexts and objects using it. To keep the
  flow simple, we keep the device awake when contexts using PXP objects
  are in use. It is expected that the userspace application only uses
  PXP when the display is on, so taking a wakeref here shouldn't worsen
  our power metrics.
- `mutex`: guards everything that isn't engines or handles_vma
- `sched`: scheduler parameters
- `guilty_count`: How many times this context has caused a GPU hang.
- `active_count`: How many times this context was active during a GPU
  hang, but did not cause it.
- `hang_timestamp`: The last time(s) this context caused a GPU hang
- `remap_slice`: Bitmask of cache lines that need remapping
- `handles_vma`: rbtree to look up our context specific obj/vma for
  the user handle. (user handles are per fd, but the binding is
  per vm, which may be one per context or shared with the global GTT)
- `lut_mutex`: Locks handles_vma
- `name`: arbitrary name, used for user debug

  A name is constructed for the context from the creator's process
  name, pid and user handle in order to uniquely identify the
  context in messages.
- `stale`: tracks stale engines to be destroyed
- `stale.lock`: guards engines
- `stale.engines`: list of stale engines

**Description**

The struct i915_gem_context represents the combined view of the driver and
logical hardware state for a particular client.



Userspace submits commands to be executed on the GPU as an instruction
stream within a GEM object we call a batchbuffer. This instructions may
refer to other GEM objects containing auxiliary state such as kernels,
samplers, render targets and even secondary batchbuffers. Userspace does
not know where in the GPU memory these objects reside and so before the
batchbuffer is passed to the GPU for execution, those addresses in the
batchbuffer and auxiliary objects are updated. This is known as relocation,
or patching. To try and avoid having to relocate each object on the next
execution, userspace is told the location of those objects in this pass,
but this remains just a hint as the kernel may choose a new location for
any object in the future.

At the level of talking to the hardware, submitting a batchbuffer for the
GPU to execute is to add content to a buffer from which the HW
command streamer is reading.

1. Add a command to load the HW context. For Logical Ring Contexts, i.e.
   Execlists, this command is not placed on the same buffer as the
   remaining items.

2. Add a command to invalidate caches to the buffer.

3. Add a batchbuffer start command to the buffer; the start command is
   essentially a token together with the GPU address of the batchbuffer
   to be executed.

4. Add a pipeline flush to the buffer.

5. Add a memory write command to the buffer to record when the GPU
   is done executing the batchbuffer. The memory write writes the
   global sequence number of the request, `i915_request::global_seqno`;
   the i915 driver uses the current value in the register to determine
   if the GPU has completed the batchbuffer.

6. Add a user interrupt command to the buffer. This command instructs
   the GPU to issue an interrupt when the command, pipeline flush and
   memory write are completed.

7. Inform the hardware of the additional commands added to the buffer
   (by updating the tail pointer).

Processing an execbuf ioctl is conceptually split up into a few phases.

1. Validation - Ensure all the pointers, handles and flags are valid.
2. Reservation - Assign GPU address space for every object
3. Relocation - Update any addresses to point to the final locations
4. Serialisation - Order the request with respect to its dependencies
5. Construction - Construct a request to execute the batchbuffer
6. Submission (at some point in the future execution)

Reserving resources for the execbuf is the most complicated phase. We
neither want to have to migrate the object in the address space, nor do
we want to have to update any relocations pointing to this object. Ideally,
we want to leave the object where it is and for all the existing relocations
to match. If the object is given a new address, or if userspace thinks the
object is elsewhere, we have to parse all the relocation entries and update
the addresses. Userspace can set the I915_EXEC_NO_RELOC flag to hint that
all the target addresses in all of its objects match the value in the
relocation entries and that they all match the presumed offsets given by the
list of execbuffer objects. Using this knowledge, we know that if we haven't
moved any buffers, all the relocation entries are valid and we can skip
the update. (If userspace is wrong, the likely outcome is an impromptu GPU
hang.) The requirement for using I915_EXEC_NO_RELOC are:

The addresses written in the objects must match the corresponding
reloc.presumed_offset which in turn must match the corresponding
execobject.offset.

Any render targets written to in the batch must be flagged with
EXEC_OBJECT_WRITE.

To avoid stalling, execobject.offset should match the current
address of that object within the active context.

The reservation is done is multiple phases. First we try and keep any
object already bound in its current location - so as long as meets the
constraints imposed by the new execbuffer. Any object left unbound after the
first pass is then fitted into any available idle space. If an object does
not fit, all objects are removed from the reservation and the process rerun
after sorting the objects into a priority order (more difficult to fit
objects are tried first). Failing that, the entire VM is cleared and we try
to fit the execbuf once last time before concluding that it simply will not
fit.

A small complication to all of this is that we allow userspace not only to
specify an alignment and a size for the object in the address space, but
we also allow userspace to specify the exact offset. This objects are
simpler to place (the location is known a priori) all we have to do is make
sure the space is available.

Once all the objects are in place, patching up the buried pointers to point
to the final locations is a fairly simple job of walking over the relocation
entry arrays, looking up the right address and rewriting the value into
the object. Simple! ... The relocation entries are stored in user memory
and so to access them we have to copy them into a local buffer. That copy
has to avoid taking any pagefaults as they may lead back to a GEM object
requiring the vm->mutex (i.e. recursive deadlock). So once again we split
the relocation into multiple passes. First we try to do everything within an
atomic context (avoid the pagefaults) which requires that we never wait. If
we detect that we may wait, or if we need to fault, then we have to fallback
to a slower path. The slowpath has to drop the mutex. (Can you hear alarm
bells yet?) Dropping the mutex means that we lose all the state we have
built up so far for the execbuf and we must reset any global data. However,
we do leave the objects pinned in their final locations - which is a
potential issue for concurrent execbufs. Once we have left the mutex, we can
allocate and copy all the relocation entries into a large array at our
leisure, reacquire the mutex, reclaim all the objects and other state and
then proceed to update any incorrect addresses with the objects.

As we process the relocation entries, we maintain a record of whether the
object is being written to. Using NORELOC, we expect userspace to provide
this information instead. We also check whether we can skip the relocation
by comparing the expected value inside the relocation entry with the target's
final address. If they differ, we have to map the current object and rewrite
the 4 or 8 byte pointer within.

Serialising an execbuf is quite simple according to the rules of the GEM
ABI. Execution within each context is ordered by the order of submission.
Writes to any GEM object are in order of submission and are exclusive. Reads
from a GEM object are unordered with respect to other reads, but ordered by
writes. A write submitted after a read cannot occur before the read, and
similarly any read submitted after a write cannot occur before the write.
Writes are ordered between engines such that only one write occurs at any
time (completing any reads beforehand) - using semaphores where available
and CPU serialisation otherwise. Other GEM access obey the same rules, any
write (either via mmaps using set-domain, or via pwrite) must flush all GPU
reads before starting, and any read (either using set-domain or pread) must
flush all GPU writes before starting. (Note we only employ a barrier before,
we currently rely on userspace not concurrently starting a new execution
whilst reading or writing to an object. This may be an advantage or not
depending on how much you trust userspace not to shoot themselves in the
foot.) Serialisation may just result in the request being inserted into
a DAG awaiting its turn, but most simple is to wait on the CPU until
all dependencies are resolved.

After all of that, is just a matter of closing the request and handing it to
the hardware (well, leaving it in a queue to be executed). However, we also
offer the ability for batchbuffers to be run with elevated privileges so
that they access otherwise hidden registers. (Used to adjust L3 cache etc.)
Before any batch is given extra privileges we first must check that it
contains no nefarious instructions, we check that each instruction is from
our whitelist and all registers are also from an allowed list. We first
copy the user's batchbuffer to a shadow (so that the user doesn't have
access to it, either by the CPU or GPU as we scan it) and then parse each
instruction. If everything is ok, we set a flag telling the hardware to run
the batchbuffer in trusted mode, otherwise the ioctl is rejected.


<a id="rst-scheduling"></a>

### Scheduling


#### <a id="c-struct-i915_sched_engine"></a>`struct i915_sched_engine`

scheduler engine

**Definition**

```c
struct i915_sched_engine {
    struct kref ref;
    spinlock_t lock;
    struct list_head requests;
    struct list_head hold;
    struct tasklet_struct tasklet;
    struct i915_priolist default_priolist;
    int queue_priority_hint;
    struct rb_root_cached queue;
    bool no_priolist;
    void *private_data;
    void (*destroy)(struct kref *kref);
    bool (*disabled)(struct i915_sched_engine *sched_engine);
    void (*kick_backend)(const struct i915_request *rq, int prio);
    void (*bump_inflight_request_prio)(struct i915_request *rq, int prio);
    void (*retire_inflight_request_prio)(struct i915_request *rq);
    void (*schedule)(struct i915_request *request, const struct i915_sched_attr *attr);
};
```

**Members**

- `ref`: reference count of schedule engine object
- `lock`: protects requests in priority lists, requests, hold and
  tasklet while running
- `requests`: list of requests inflight on this schedule engine
- `hold`: list of ready requests, but on hold
- `tasklet`: softirq tasklet for submission
- `default_priolist`: priority list for I915_PRIORITY_NORMAL
- `queue_priority_hint`: Highest pending priority.

  When we add requests into the queue, or adjust the priority of
  executing requests, we compute the maximum priority of those
  pending requests. We can then use this value to determine if
  we need to preempt the executing requests to service the queue.
  However, since the we may have recorded the priority of an inflight
  request we wanted to preempt but since completed, at the time of
  dequeuing the priority hint may no longer may match the highest
  available request priority.
- `queue`: queue of requests, in priority lists
- `no_priolist`: priority lists disabled
- `private_data`: private data of the submission backend
- `destroy`: destroy schedule engine / cleanup in backend
- `disabled`: check if backend has disabled submission
- `kick_backend`: kick backend after a request's priority has changed
- `bump_inflight_request_prio`: update priority of an inflight request
- `retire_inflight_request_prio`: indicate request is retired to
  priority tracking
- `schedule`: adjust priority of request

  Call when the priority on a request has changed and it and its
  dependencies may need rescheduling. Note the request itself may
  not be ready to run!

**Description**

A schedule engine represents a submission queue with different priority
bands. It contains all the common state (relative to the backend) to queue,
track, and submit a request.

This object at the moment is quite i915 specific but will transition into a
container for the drm_gpu_scheduler plus a few other variables once the i915
is integrated with the DRM scheduler.


<a id="rst-logical-rings-logical-ring-contexts-and-execlists"></a>

### Logical Rings, Logical Ring Contexts and Execlists


Motivation:
GEN8 brings an expansion of the HW contexts: "Logical Ring Contexts".
These expanded contexts enable a number of new abilities, especially
"Execlists" (also implemented in this file).

One of the main differences with the legacy HW contexts is that logical
ring contexts incorporate many more things to the context's state, like
PDPs or ringbuffer control registers:

The reason why PDPs are included in the context is straightforward: as
PPGTTs (per-process GTTs) are actually per-context, having the PDPs
contained there mean you don't need to do a ppgtt->switch_mm yourself,
instead, the GPU will do it for you on the context switch.

But, what about the ringbuffer control registers (head, tail, etc..)?
shouldn't we just need a set of those per engine command streamer? This is
where the name "Logical Rings" starts to make sense: by virtualizing the
rings, the engine cs shifts to a new "ring buffer" with every context
switch. When you want to submit a workload to the GPU you: A) choose your
context, B) find its appropriate virtualized ring, C) write commands to it
and then, finally, D) tell the GPU to switch to that context.

Instead of the legacy MI_SET_CONTEXT, the way you tell the GPU to switch
to a contexts is via a context execution list, ergo "Execlists".

LRC implementation:
Regarding the creation of contexts, we have:

- One global default context.
- One local default context for each opened fd.
- One local extra context for each context create ioctl call.

Now that ringbuffers belong per-context (and not per-engine, like before)
and that contexts are uniquely tied to a given engine (and not reusable,
like before) we need:

- One ringbuffer per-engine inside each context.
- One backing object per-engine inside each context.

The global default context starts its life with these new objects fully
allocated and populated. The local default context for each opened fd is
more complex, because we don't know at creation time which engine is going
to use them. To handle this, we have implemented a deferred creation of LR
contexts:

The local context starts its life as a hollow or blank holder, that only
gets populated for a given engine once we receive an execbuffer. If later
on we receive another execbuffer ioctl for the same context but a different
engine, we allocate/populate a new ringbuffer and context backing object and
so on.

Finally, regarding local contexts created using the ioctl call: as they are
only allowed with the render ring, we can allocate & populate them right
away (no need to defer anything, at least for now).

Execlists implementation:
Execlists are the new method by which, on gen8+ hardware, workloads are
submitted for execution (as opposed to the legacy, ringbuffer-based, method).
This method works as follows:

When a request is committed, its commands (the BB start and any leading or
trailing commands, like the seqno breadcrumbs) are placed in the ringbuffer
for the appropriate context. The tail pointer in the hardware context is not
updated at this time, but instead, kept by the driver in the ringbuffer
structure. A structure representing this request is added to a request queue
for the appropriate engine: this structure contains a copy of the context's
tail after the request was written to the ring buffer and a pointer to the
context itself.

If the engine's request queue was empty before the request was added, the
queue is processed immediately. Otherwise the queue will be processed during
a context switch interrupt. In any case, elements on the queue will get sent
(in pairs) to the GPU's ExecLists Submit Port (ELSP, for short) with a
globally unique 20-bits submission ID.

When execution of a request completes, the GPU updates the context status
buffer with a context complete event and generates a context switch interrupt.
During the interrupt handling, the driver examines the events in the buffer:
for each context complete event, if the announced ID matches that on the head
of the request queue, then that request is retired and removed from the queue.

After processing, if any requests were retired and the queue is not empty
then a new execution list can be submitted. The two requests at the front of
the queue are next to be submitted but since a context may not occur twice in
an execution list, if subsequent requests have the same ID as the first then
the two requests must be combined. This is done simply by discarding requests
at the head of the queue until either only one requests is left (in which case
we use a NULL second context) or the first two requests have unique IDs.

By always executing the first two requests in the queue the driver ensures
that the GPU is kept as busy as possible. In the case where a single context
completes but a second context is still executing, the request for this second
context will be at the head of the queue when we remove the first one. This
request will then be resubmitted along with a new request for a different context,
which will cause the hardware to continue executing the second request and queue
the new request (the GPU detects the condition of a context getting preempted
with the same context and optimizes the context switch flow by not doing
preemption, but just sampling the new tail pointer).


<a id="rst-global-gtt-views"></a>

### Global GTT views


Background and previous state

Historically objects could exists (be bound) in global GTT space only as
singular instances with a view representing all of the object's backing pages
in a linear fashion. This view will be called a normal view.

To support multiple views of the same object, where the number of mapped
pages is not equal to the backing store, or where the layout of the pages
is not linear, concept of a GGTT view was added.

One example of an alternative view is a stereo display driven by a single
image. In this case we would have a framebuffer looking like this
(2x2 pages):

12
34

Above would represent a normal GGTT view as normally mapped for GPU or CPU
rendering. In contrast, fed to the display engine would be an alternative
view which could look something like this:

1212
3434

In this example both the size and layout of pages in the alternative view is
different from the normal view.

Implementation and usage

GGTT views are implemented using VMAs and are distinguished via enum
i915_gtt_view_type and struct i915_gtt_view.

A new flavour of core GEM functions which work with GGTT bound objects were
added with the _ggtt_ infix, and sometimes with _view postfix to avoid
renaming  in large amounts of code. They take the struct i915_gtt_view
parameter encapsulating all metadata required to implement a view.

As a helper for callers which are only interested in the normal view,
globally const i915_gtt_view_normal singleton instance exists. All old core
GEM API functions, the ones not taking the view parameter, are operating on,
or with the normal GGTT view.

Code wanting to add or use a new GGTT view needs to:

1. Add a new enum with a suitable name.
2. Extend the metadata in the i915_gtt_view structure if required.
3. Add support to `i915_get_vma_pages()`.

New views are required to build a scatter-gather table from within the
i915_get_vma_pages function. This table is stored in the vma.gtt_view and
exists for the lifetime of an VMA.

Core API is designed to have copy semantics which means that passed in
struct i915_gtt_view does not need to be persistent (left around after
calling the core API functions).



#### <a id="c-i915_gem_gtt_reserve"></a>`i915_gem_gtt_reserve()`

```c
int i915_gem_gtt_reserve(struct i915_address_space *vm, struct i915_gem_ww_ctx *ww, struct drm_mm_node *node, u64 size, u64 offset, unsigned long color, unsigned int flags)
```

reserve a node in an address_space (GTT)

**Parameters**

- `struct i915_address_space *vm`: the `struct i915_address_space`
- `struct i915_gem_ww_ctx *ww`: An optional struct i915_gem_ww_ctx.
- `struct drm_mm_node *node`: the [`struct drm_mm_node`](/kernel/hardware/gpu/drm-mm.md#c-struct-drm_mm_node) (typically i915_vma.node)
- `u64 size`: how much space to allocate inside the GTT,
  must be #I915_GTT_PAGE_SIZE aligned
- `u64 offset`: where to insert inside the GTT,
  must be #I915_GTT_MIN_ALIGNMENT aligned, and the node
  (**offset** + **size**) must fit within the address space
- `unsigned long color`: color to apply to node, if this node is not from a VMA,
  color must be #I915_COLOR_UNEVICTABLE
- `unsigned int flags`: control search and eviction behaviour

**Description**

[`i915_gem_gtt_reserve()`](#c-i915_gem_gtt_reserve) tries to insert the **node** at the exact **offset** inside
the address space (using **size** and **color**). If the **node** does not fit, it
tries to evict any overlapping nodes from the GTT, including any
neighbouring nodes if the colors do not match (to ensure guard pages between
differing domains). See [`i915_gem_evict_for_node()`](#c-i915_gem_evict_for_node) for the gory details
on the eviction algorithm. #PIN_NONBLOCK may used to prevent waiting on
evicting active overlapping objects, and any overlapping node that is pinned
or marked as unevictable will also result in failure.

**Return**

0 on success, -ENOSPC if no suitable hole is found, -EINTR if
asked to wait for eviction and interrupted.

#### <a id="c-i915_gem_gtt_insert"></a>`i915_gem_gtt_insert()`

```c
int i915_gem_gtt_insert(struct i915_address_space *vm, struct i915_gem_ww_ctx *ww, struct drm_mm_node *node, u64 size, u64 alignment, unsigned long color, u64 start, u64 end, unsigned int flags)
```

insert a node into an address_space (GTT)

**Parameters**

- `struct i915_address_space *vm`: the `struct i915_address_space`
- `struct i915_gem_ww_ctx *ww`: An optional struct i915_gem_ww_ctx.
- `struct drm_mm_node *node`: the [`struct drm_mm_node`](/kernel/hardware/gpu/drm-mm.md#c-struct-drm_mm_node) (typically i915_vma.node)
- `u64 size`: how much space to allocate inside the GTT,
  must be #I915_GTT_PAGE_SIZE aligned
- `u64 alignment`: required alignment of starting offset, may be 0 but
  if specified, this must be a power-of-two and at least
  \#I915_GTT_MIN_ALIGNMENT
- `unsigned long color`: color to apply to node
- `u64 start`: start of any range restriction inside GTT (0 for all),
  must be #I915_GTT_PAGE_SIZE aligned
- `u64 end`: end of any range restriction inside GTT (U64_MAX for all),
  must be #I915_GTT_PAGE_SIZE aligned if not U64_MAX
- `unsigned int flags`: control search and eviction behaviour

**Description**

[`i915_gem_gtt_insert()`](#c-i915_gem_gtt_insert) first searches for an available hole into which
is can insert the node. The hole address is aligned to **alignment** and
its **size** must then fit entirely within the \[**start**, **end**\] bounds. The
nodes on either side of the hole must match **color**, or else a guard page
will be inserted between the two nodes (or the node evicted). If no
suitable hole is found, first a victim is randomly selected and tested
for eviction, otherwise then the LRU list of objects within the GTT
is scanned to find the first set of replacement nodes to create the hole.
Those old overlapping nodes are evicted from the GTT (and so must be
rebound before any future use). Any node that is currently pinned cannot
be evicted (see `i915_vma_pin()`). Similar if the node's VMA is currently
active and #PIN_NONBLOCK is specified, that node is also skipped when
searching for an eviction candidate. See [`i915_gem_evict_something()`](#c-i915_gem_evict_something) for
the gory details on the eviction algorithm.

**Return**

0 on success, -ENOSPC if no suitable hole is found, -EINTR if
asked to wait for eviction and interrupted.


<a id="rst-gtt-fences-and-swizzling"></a>

### GTT Fences and Swizzling


#### <a id="c-i915_vma_revoke_fence"></a>`i915_vma_revoke_fence()`

```c
void i915_vma_revoke_fence(struct i915_vma *vma)
```

force-remove fence for a VMA

**Parameters**

- `struct i915_vma *vma`: vma to map linearly (not through a fence reg)

**Description**

This function force-removes any fence from the given object, which is useful
if the kernel wants to do untiled GTT access.

#### <a id="c-i915_vma_pin_fence"></a>`i915_vma_pin_fence()`

```c
int i915_vma_pin_fence(struct i915_vma *vma)
```

set up fencing for a vma

**Parameters**

- `struct i915_vma *vma`: vma to map through a fence reg

**Description**

When mapping objects through the GTT, userspace wants to be able to write
to them without having to worry about swizzling if the object is tiled.
This function walks the fence regs looking for a free one for **obj**,
stealing one if it can't find any.

It then sets up the reg based on the object's properties: address, pitch
and tiling format.

For an untiled surface, this removes any existing fence.

**Return**

0 on success, negative error code on failure.

#### <a id="c-i915_reserve_fence"></a>`i915_reserve_fence()`

```c
struct i915_fence_reg * i915_reserve_fence(struct i915_ggtt *ggtt)
```

Reserve a fence for vGPU

**Parameters**

- `struct i915_ggtt *ggtt`: Global GTT

**Description**

This function walks the fence regs looking for a free one and remove
it from the fence_list. It is used to reserve fence for vGPU to use.

#### <a id="c-i915_unreserve_fence"></a>`i915_unreserve_fence()`

```c
void i915_unreserve_fence(struct i915_fence_reg *fence)
```

Reclaim a reserved fence

**Parameters**

- `struct i915_fence_reg *fence`: the fence reg

**Description**

This function add a reserved fence register from vGPU to the fence_list.

#### <a id="c-intel_ggtt_restore_fences"></a>`intel_ggtt_restore_fences()`

```c
void intel_ggtt_restore_fences(struct i915_ggtt *ggtt)
```

restore fence state

**Parameters**

- `struct i915_ggtt *ggtt`: Global GTT

**Description**

Restore the hw fence state to match the software tracking again, to be called
after a gpu reset and on resume. Note that on runtime suspend we only cancel
the fences, to be reacquired by the user later.

#### <a id="c-detect_bit_6_swizzle"></a>`detect_bit_6_swizzle()`

```c
void detect_bit_6_swizzle(struct i915_ggtt *ggtt)
```

detect bit 6 swizzling pattern

**Parameters**

- `struct i915_ggtt *ggtt`: Global GGTT

**Description**

Detects bit 6 swizzling of address lookup between IGD access and CPU
access through main memory.

#### <a id="c-i915_gem_object_do_bit_17_swizzle"></a>`i915_gem_object_do_bit_17_swizzle()`

```c
void i915_gem_object_do_bit_17_swizzle(struct drm_i915_gem_object *obj, struct sg_table *pages)
```

fixup bit 17 swizzling

**Parameters**

- `struct drm_i915_gem_object *obj`: i915 GEM buffer object
- `struct sg_table *pages`: the scattergather list of physical pages

**Description**

This function fixes up the swizzling in case any page frame number for this
object has changed in bit 17 since that state has been saved with
[`i915_gem_object_save_bit_17_swizzle()`](#c-i915_gem_object_save_bit_17_swizzle).

This is called when pinning backing storage again, since the kernel is free
to move unpinned backing storage around (either by directly moving pages or
by swapping them out and back in again).

#### <a id="c-i915_gem_object_save_bit_17_swizzle"></a>`i915_gem_object_save_bit_17_swizzle()`

```c
void i915_gem_object_save_bit_17_swizzle(struct drm_i915_gem_object *obj, struct sg_table *pages)
```

save bit 17 swizzling

**Parameters**

- `struct drm_i915_gem_object *obj`: i915 GEM buffer object
- `struct sg_table *pages`: the scattergather list of physical pages

**Description**

This function saves the bit 17 of each page frame number so that swizzling
can be fixed up later on with [`i915_gem_object_do_bit_17_swizzle()`](#c-i915_gem_object_do_bit_17_swizzle). This must
be called before the backing storage can be unpinned.


<a id="rst-global-gtt-fence-handling"></a>

#### Global GTT Fence Handling


Important to avoid confusions: "fences" in the i915 driver are not execution
fences used to track command completion but hardware detiler objects which
wrap a given range of the global GTT. Each platform has only a fairly limited
set of these objects.

Fences are used to detile GTT memory mappings. They're also connected to the
hardware frontbuffer render tracking and hence interact with frontbuffer
compression. Furthermore on older platforms fences are required for tiled
objects used by the display engine. They can also be used by the render
engine - they're required for blitter commands and are optional for render
commands. But on gen4+ both display (with the exception of fbc) and rendering
have their own tiling state bits and don't need fences.

Also note that fences only support X and Y tiling and hence can't be used for
the fancier new tiling formats like W, Ys and Yf.

Finally note that because fences are such a restricted resource they're
dynamically associated with objects. Furthermore fence state is committed to
the hardware lazily to avoid unnecessary stalls on gen2/3. Therefore code must
explicitly call `i915_gem_object_get_fence()` to synchronize fencing status
for cpu access. Also note that some code wants an unfenced view, for those
cases the fence can be removed forcefully with `i915_gem_object_put_fence()`.

Internally these functions will synchronize with userspace access by removing
CPU ptes into GTT mmaps (not the GTT ptes themselves) as needed.


<a id="rst-hardware-tiling-and-swizzling-details"></a>

#### Hardware Tiling and Swizzling Details


The idea behind tiling is to increase cache hit rates by rearranging
pixel data so that a group of pixel accesses are in the same cacheline.
Performance improvement from doing this on the back/depth buffer are on
the order of 30%.

Intel architectures make this somewhat more complicated, though, by
adjustments made to addressing of data when the memory is in interleaved
mode (matched pairs of DIMMS) to improve memory bandwidth.
For interleaved memory, the CPU sends every sequential 64 bytes
to an alternate memory channel so it can get the bandwidth from both.

The GPU also rearranges its accesses for increased bandwidth to interleaved
memory, and it matches what the CPU does for non-tiled.  However, when tiled
it does it a little differently, since one walks addresses not just in the
X direction but also Y.  So, along with alternating channels when bit
6 of the address flips, it also alternates when other bits flip --  Bits 9
(every 512 bytes, an X tile scanline) and 10 (every two X tile scanlines)
are common to both the 915 and 965-class hardware.

The CPU also sometimes XORs in higher bits as well, to improve
bandwidth doing strided access like we do so frequently in graphics.  This
is called "Channel XOR Randomization" in the MCH documentation.  The result
is that the CPU is XORing in either bit 11 or bit 17 to bit 6 of its address
decode.

All of this bit 6 XORing has an effect on our memory management,
as we need to make sure that the 3d driver can correctly address object
contents.

If we don't have interleaved memory, all tiling is safe and no swizzling is
required.

When bit 17 is XORed in, we simply refuse to tile at all.  Bit
17 is not just a page offset, so as we page an object out and back in,
individual pages in it will have different bit 17 addresses, resulting in
each 64 bytes being swapped with its neighbor!

Otherwise, if interleaved, we have to tell the 3d driver what the address
swizzling it needs to do is, since it's writing with the CPU to the pages
(bit 6 and potentially bit 11 XORed in), and the GPU is reading from the
pages (bit 6, 9, and 10 XORed in), resulting in a cumulative bit swizzling
required by the CPU of XORing in bit 6, 9, 10, and potentially 11, in order
to match what the GPU expects.


<a id="rst-object-tiling-ioctls"></a>

### Object Tiling IOCTLs


#### <a id="c-i915_gem_fence_size"></a>`i915_gem_fence_size()`

```c
u32 i915_gem_fence_size(struct drm_i915_private *i915, u32 size, unsigned int tiling, unsigned int stride)
```

required global GTT size for a fence

**Parameters**

- `struct drm_i915_private *i915`: i915 device
- `u32 size`: object size
- `unsigned int tiling`: tiling mode
- `unsigned int stride`: tiling stride

**Description**

Return the required global GTT size for a fence (view of a tiled object),
taking into account potential fence register mapping.

#### <a id="c-i915_gem_fence_alignment"></a>`i915_gem_fence_alignment()`

```c
u32 i915_gem_fence_alignment(struct drm_i915_private *i915, u32 size, unsigned int tiling, unsigned int stride)
```

required global GTT alignment for a fence

**Parameters**

- `struct drm_i915_private *i915`: i915 device
- `u32 size`: object size
- `unsigned int tiling`: tiling mode
- `unsigned int stride`: tiling stride

**Description**

Return the required global GTT alignment for a fence (a view of a tiled
object), taking into account potential fence register mapping.

#### <a id="c-i915_gem_set_tiling_ioctl"></a>`i915_gem_set_tiling_ioctl()`

```c
int i915_gem_set_tiling_ioctl(struct drm_device *dev, void *data, struct drm_file *file)
```

IOCTL handler to set tiling mode

**Parameters**

- `struct drm_device *dev`: DRM device
- `void *data`: data pointer for the ioctl
- `struct drm_file *file`: DRM file for the ioctl call

**Description**

Sets the tiling mode of an object, returning the required swizzling of
bit 6 of addresses in the object.

Called by the user via ioctl.

**Return**

Zero on success, negative errno on failure.

#### <a id="c-i915_gem_get_tiling_ioctl"></a>`i915_gem_get_tiling_ioctl()`

```c
int i915_gem_get_tiling_ioctl(struct drm_device *dev, void *data, struct drm_file *file)
```

IOCTL handler to get tiling mode

**Parameters**

- `struct drm_device *dev`: DRM device
- `void *data`: data pointer for the ioctl
- `struct drm_file *file`: DRM file for the ioctl call

**Description**

Returns the current tiling mode and required bit 6 swizzling for the object.

Called by the user via ioctl.

**Return**

Zero on success, negative errno on failure.



[`i915_gem_set_tiling_ioctl()`](#c-i915_gem_set_tiling_ioctl) and [`i915_gem_get_tiling_ioctl()`](#c-i915_gem_get_tiling_ioctl) is the userspace
interface to declare fence register requirements.

In principle GEM doesn't care at all about the internal data layout of an
object, and hence it also doesn't care about tiling or swizzling. There's two
exceptions:

- For X and Y tiling the hardware provides detilers for CPU access, so called
  fences. Since there's only a limited amount of them the kernel must manage
  these, and therefore userspace must tell the kernel the object tiling if it
  wants to use fences for detiling.
- On gen3 and gen4 platforms have a swizzling pattern for tiled objects which
  depends upon the physical page frame number. When swapping such objects the
  page frame number might change and the kernel must be able to fix this up
  and hence now the tiling. Note that on a subset of platforms with
  asymmetric memory channel population the swizzling pattern changes in an
  unknown way, and for those the kernel simply forbids swapping completely.

Since neither of this applies for new tiling layouts on modern platforms like
W, Ys and Yf tiling GEM only allows object tiling to be set to X or Y tiled.
Anything else can be handled in userspace entirely without the kernel's
involvement.


<a id="rst-protected-objects"></a>

### Protected Objects


PXP (Protected Xe Path) is a feature available in Gen12 and newer platforms.
It allows execution and flip to display of protected (i.e. encrypted)
objects. The SW support is enabled via the CONFIG_DRM_I915_PXP kconfig.

Objects can opt-in to PXP encryption at creation time via the
I915_GEM_CREATE_EXT_PROTECTED_CONTENT create_ext flag. For objects to be
correctly protected they must be used in conjunction with a context created
with the I915_CONTEXT_PARAM_PROTECTED_CONTENT flag. See the documentation
of those two uapi flags for details and restrictions.

Protected objects are tied to a pxp session; currently we only support one
session, which i915 manages and whose index is available in the uapi
(I915_PROTECTED_CONTENT_DEFAULT_SESSION) for use in instructions targeting
protected objects.
The session is invalidated by the HW when certain events occur (e.g.
suspend/resume). When this happens, all the objects that were used with the
session are marked as invalid and all contexts marked as using protected
content are banned. Any further attempt at using them in an execbuf call is
rejected, while flips are converted to black frames.

Some of the PXP setup operations are performed by the Management Engine,
which is handled by the mei driver; communication between i915 and mei is
performed via the mei_pxp component module.



#### <a id="c-struct-intel_pxp"></a>`struct intel_pxp`

pxp state

**Definition**

```c
struct intel_pxp {
        struct intel_gt *ctrl_gt;
        bool platform_cfg_is_bad;
        u32 kcr_base;
        struct gsccs_session_resources {
            u64 host_session_handle;
            struct intel_context *ce;
            struct i915_vma *pkt_vma;
            void *pkt_vaddr;
            struct i915_vma *bb_vma;
            void *bb_vaddr;
        } gsccs_res;
        struct i915_pxp_component *pxp_component;
        struct device_link *dev_link;
        bool pxp_component_added;
        struct intel_context *ce;
        struct mutex arb_mutex;
        bool arb_is_valid;
        u32 key_instance;
        struct mutex tee_mutex;
        struct {
            struct drm_i915_gem_object *obj;
            void *vaddr;
        } stream_cmd;
        bool hw_state_invalidated;
        bool irq_enabled;
        struct completion termination;
        struct work_struct session_work;
        u32 session_events;
    #define PXP_TERMINATION_REQUEST  BIT(0);
    #define PXP_TERMINATION_COMPLETE BIT(1);
    #define PXP_INVAL_REQUIRED       BIT(2);
    #define PXP_EVENT_TYPE_IRQ       BIT(3);
};
```

**Members**

- `ctrl_gt`: pointer to the tile that owns the controls for PXP subsystem assets that
  the VDBOX, the KCR engine (and GSC CS depending on the platform)
- `platform_cfg_is_bad`: used to track if any prior arb session creation resulted
  in a failure that was caused by a platform configuration issue, meaning that
  failure will not get resolved without a change to the platform (not kernel)
  such as BIOS configuration, firwmware update, etc. This bool gets reflected when
  GET_PARAM:I915_PARAM_PXP_STATUS is called.
- `kcr_base`: base mmio offset for the KCR engine which is different on legacy platforms
  vs newer platforms where the KCR is inside the media-tile.
- `gsccs_res`: resources for request submission for platforms that have a GSC engine.
- `pxp_component`: i915_pxp_component struct of the bound mei_pxp
  module. Only set and cleared inside component bind/unbind functions,
  which are protected by `tee_mutex`.
- `dev_link`: Enforce module relationship for power management ordering.
- `pxp_component_added`: track if the pxp component has been added.
  Set and cleared in tee init and fini functions respectively.
- `ce`: kernel-owned context used for PXP operations
- `arb_mutex`: protects arb session start
- `arb_is_valid`: tracks arb session status.
  After a teardown, the arb session can still be in play on the HW
  even if the keys are gone, so we can't rely on the HW state of the
  session to know if it's valid and need to track the status in SW.
- `key_instance`: tracks which key instance we're on, so we can use it
  to determine if an object was created using the current key or a
  previous one.
- `tee_mutex`: protects the tee channel binding and messaging.
- `stream_cmd`: LMEM obj used to send stream PXP commands to the GSC
- `hw_state_invalidated`: if the HW perceives an attack on the integrity
  of the encryption it will invalidate the keys and expect SW to
  re-initialize the session. We keep track of this state to make sure
  we only re-start the arb session when required.
- `irq_enabled`: tracks the status of the kcr irqs
- `termination`: tracks the status of a pending termination. Only
  re-initialized under gt->irq_lock and completed in `session_work`.
- `session_work`: worker that manages session events.
- `session_events`: pending session events, protected with gt->irq_lock.


<a id="rst-microcontrollers"></a>

## Microcontrollers

Starting from gen9, three microcontrollers are available on the HW: the graphics microcontroller (GuC), the HEVC/H.265 microcontroller (HuC) and the display microcontroller (DMC). The driver is responsible for loading the firmwares on the microcontrollers; the GuC and HuC firmwares are transferred to WOPCM using the DMA engine, while the DMC firmware is written through MMIO.

<a id="rst-wopcm"></a>

### WOPCM

<a id="rst-wopcm-layout"></a>

#### WOPCM Layout


The layout of the WOPCM will be fixed after writing to GuC WOPCM size and
offset registers whose values are calculated and determined by HuC/GuC
firmware size and set of hardware requirements/restrictions as shown below:

```text
  +=========> +====================+ <== WOPCM Top
  ^           |  HW contexts RSVD  |
  |     +===> +====================+ <== GuC WOPCM Top
  |     ^     |                    |
  |     |     |                    |
  |     |     |                    |
  |    GuC    |                    |
  |   WOPCM   |                    |
  |    Size   +--------------------+
WOPCM   |     |    GuC FW RSVD     |
  |     |     +--------------------+
  |     |     |   GuC Stack RSVD   |
  |     |     +------------------- +
  |     v     |   GuC WOPCM RSVD   |
  |     +===> +====================+ <== GuC WOPCM base
  |           |     WOPCM RSVD     |
  |           +------------------- + <== HuC Firmware Top
  v           |      HuC FW        |
  +=========> +====================+ <== WOPCM Base
```

GuC accessible WOPCM starts at GuC WOPCM base and ends at GuC WOPCM top.
The top part of the WOPCM is reserved for hardware contexts (e.g. RC6
context).


<a id="rst-guc"></a>

### GuC


The GuC is a microcontroller inside the GT HW, introduced in gen9. The GuC is
designed to offload some of the functionality usually performed by the host
driver; currently the main operations it can take care of are:

- Authentication of the HuC, which is required to fully enable HuC usage.
- Low latency graphics context scheduling (a.k.a. GuC submission).
- GT Power management.

The enable_guc module parameter can be used to select which of those
operations to enable within GuC. Note that not all the operations are
supported on all gen9+ platforms.

Enabling the GuC is not mandatory and therefore the firmware is only loaded
if at least one of the operations is selected. However, not loading the GuC
might result in the loss of some features that do require the GuC (currently
just the HuC, but more are expected to land in the future).



#### <a id="c-struct-intel_guc"></a>`struct intel_guc`

Top level structure of GuC.

**Definition**

```c
struct intel_guc {
        struct intel_uc_fw fw;
        struct intel_guc_log log;
        struct intel_guc_ct ct;
        struct intel_guc_slpc slpc;
        struct intel_guc_state_capture *capture;
        struct dentry *dbgfs_node;
        struct i915_sched_engine *sched_engine;
        struct i915_request *stalled_request;
        enum {
            STALL_NONE,
            STALL_REGISTER_CONTEXT,
            STALL_MOVE_LRC_TAIL,
            STALL_ADD_REQUEST,
        } submission_stall_reason;
        spinlock_t irq_lock;
        unsigned int msg_enabled_mask;
        atomic_t outstanding_submission_g2h;
        struct xarray tlb_lookup;
        u32 serial_slot;
        u32 next_seqno;
        struct {
            bool enabled;
            void (*reset)(struct intel_guc *guc);
            void (*enable)(struct intel_guc *guc);
            void (*disable)(struct intel_guc *guc);
        } interrupts;
        struct {
            spinlock_t lock;
            struct ida guc_ids;
            int num_guc_ids;
            unsigned long *guc_ids_bitmap;
            struct list_head guc_id_list;
            unsigned int guc_ids_in_use;
            struct list_head destroyed_contexts;
            struct work_struct destroyed_worker;
            struct work_struct reset_fail_worker;
            intel_engine_mask_t reset_fail_mask;
            unsigned int sched_disable_delay_ms;
            unsigned int sched_disable_gucid_threshold;
        } submission_state;
        bool submission_supported;
        bool submission_selected;
        bool submission_initialized;
        struct intel_uc_fw_ver submission_version;
        bool rc_supported;
        bool rc_selected;
        struct i915_vma *ads_vma;
        struct iosys_map ads_map;
        u32 ads_regset_size;
        u32 ads_regset_count[I915_NUM_ENGINES];
        struct guc_mmio_reg *ads_regset;
        u32 ads_golden_ctxt_size;
        u32 ads_waklv_size;
        u32 ads_capture_size;
        struct i915_vma *lrc_desc_pool_v69;
        void *lrc_desc_pool_vaddr_v69;
        struct xarray context_lookup;
        u32 params[GUC_CTL_MAX_DWORDS];
        struct {
            u32 base;
            unsigned int count;
            enum forcewake_domains fw_domains;
        } send_regs;
        i915_reg_t notify_reg;
        u32 mmio_msg;
        struct mutex send_mutex;
        struct {
            spinlock_t lock;
            u64 gt_stamp;
            unsigned long ping_delay;
            struct delayed_work work;
            u32 shift;
            unsigned long last_stat_jiffies;
        } timestamp;
        struct work_struct dead_guc_worker;
        unsigned long last_dead_guc_jiffies;
    #ifdef CONFIG_DRM_I915_SELFTEST;
        int number_guc_id_stolen;
        u32 fast_response_selftest;
    #endif;
};
```

**Members**

- `fw`: the GuC firmware
- `log`: sub-structure containing GuC log related data and objects
- `ct`: the command transport communication channel
- `slpc`: sub-structure containing SLPC related data and objects
- `capture`: the error-state-capture module's data and objects
- `dbgfs_node`: debugfs node
- `sched_engine`: Global engine used to submit requests to GuC
- `stalled_request`: if GuC can't process a request for any reason, we
  save it until GuC restarts processing. No other request can be
  submitted until the stalled request is processed.
- `submission_stall_reason`: reason why submission is stalled
- `irq_lock`: protects GuC irq state
- `msg_enabled_mask`: mask of events that are processed when receiving
  an INTEL_GUC_ACTION_DEFAULT G2H message.
- `outstanding_submission_g2h`: number of outstanding GuC to Host
  responses related to GuC submission, used to determine if the GT is
  idle
- `tlb_lookup`: xarray to store all pending TLB invalidation requests
- `serial_slot`: id to the initial waiter created in tlb_lookup,
  which is used only when failed to allocate new waiter.
- `next_seqno`: the next id (sequence number) to allocate.
- `interrupts`: pointers to GuC interrupt-managing functions.
- `submission_state`: sub-structure for submission state protected by
  single lock
- `submission_state.lock`: protects everything in
  submission_state, ce->guc_id.id, and ce->guc_id.ref
  when transitioning in and out of zero
- `submission_state.guc_ids`: used to allocate new
  guc_ids, single-lrc
- `submission_state.num_guc_ids`: Number of guc_ids, selftest
  feature to be able to reduce this number while testing.
- `submission_state.guc_ids_bitmap`: used to allocate
  new guc_ids, multi-lrc
- `submission_state.guc_id_list`: list of intel_context
  with valid guc_ids but no refs
- `submission_state.guc_ids_in_use`: Number single-lrc
  guc_ids in use
- `submission_state.destroyed_contexts`: list of contexts
  waiting to be destroyed (deregistered with the GuC)
- `submission_state.destroyed_worker`: worker to deregister
  contexts, need as we need to take a GT PM reference and
  can't from destroy function as it might be in an atomic
  context (no sleeping)
- `submission_state.reset_fail_worker`: worker to trigger
  a GT reset after an engine reset fails
- `submission_state.reset_fail_mask`: mask of engines that
  failed to reset
- `submission_state.sched_disable_delay_ms`: schedule
  disable delay, in ms, for contexts
- `submission_state.sched_disable_gucid_threshold`: threshold of min remaining available guc_ids before
  we start bypassing the schedule disable delay
- `submission_supported`: tracks whether we support GuC submission on
  the current platform
- `submission_selected`: tracks whether the user enabled GuC submission
- `submission_initialized`: tracks whether GuC submission has been initialised
- `submission_version`: Submission API version of the currently loaded firmware
- `rc_supported`: tracks whether we support GuC rc on the current platform
- `rc_selected`: tracks whether the user enabled GuC rc
- `ads_vma`: object allocated to hold the GuC ADS
- `ads_map`: contents of the GuC ADS
- `ads_regset_size`: size of the save/restore regsets in the ADS
- `ads_regset_count`: number of save/restore registers in the ADS for
  each engine
- `ads_regset`: save/restore regsets in the ADS
- `ads_golden_ctxt_size`: size of the golden contexts in the ADS
- `ads_waklv_size`: size of workaround KLVs
- `ads_capture_size`: size of register lists in the ADS used for error capture
- `lrc_desc_pool_v69`: object allocated to hold the GuC LRC descriptor pool
- `lrc_desc_pool_vaddr_v69`: contents of the GuC LRC descriptor pool
- `context_lookup`: used to resolve intel_context from guc_id, if a
  context is present in this structure it is registered with the GuC
- `params`: Control params for fw initialization
- `send_regs`: GuC's FW specific registers used for sending MMIO H2G
- `notify_reg`: register used to send interrupts to the GuC FW
- `mmio_msg`: notification bitmask that the GuC writes in one of its
  registers when the CT channel is disabled, to be processed when the
  channel is back up.
- `send_mutex`: used to serialize the intel_guc_send actions
- `timestamp`: GT timestamp object that stores a copy of the timestamp
  and adjusts it for overflow using a worker.
- `timestamp.lock`: Lock protecting the below fields and
  the engine stats.
- `timestamp.gt_stamp`: 64-bit extended value of the GT
  timestamp.
- `timestamp.ping_delay`: Period for polling the GT
  timestamp for overflow.
- `timestamp.work`: Periodic work to adjust GT timestamp,
  engine and context usage for overflows.
- `timestamp.shift`: Right shift value for the gpm timestamp
- `timestamp.last_stat_jiffies`: jiffies at last actual
  stats collection time. We use this timestamp to ensure
  we don't oversample the stats because runtime power
  management events can trigger stats collection at much
  higher rates than required.
- `dead_guc_worker`: Asynchronous worker thread for forcing a GuC reset.
  Specifically used when the G2H handler wants to issue a reset. Resets
  require flushing the G2H queue. So, the G2H processing itself must not
  trigger a reset directly. Instead, go via this worker.
- `last_dead_guc_jiffies`: timestamp of previous 'dead guc' occurrence
  used to prevent a fundamentally broken system from continuously
  reloading the GuC.
- `number_guc_id_stolen`: The number of guc_ids that have been stolen
- `fast_response_selftest`: Backdoor to CT handler for fast response selftest

**Description**

It handles firmware loading and manages client pool. intel_guc owns an
i915_sched_engine for submission.

#### <a id="c-intel_guc_ggtt_offset"></a>`intel_guc_ggtt_offset()`

```c
u32 intel_guc_ggtt_offset(struct intel_guc *guc, struct i915_vma *vma)
```

Get and validate the GGTT offset of **vma**

**Parameters**

- `struct intel_guc *guc`: intel_guc structure.
- `struct i915_vma *vma`: i915 graphics virtual memory area.

**Description**

GuC does not allow any gfx GGTT address that falls into range
\[0, ggtt.pin_bias), which is reserved for Boot ROM, SRAM and WOPCM.
Currently, in order to exclude \[0, ggtt.pin_bias) address space from
GGTT, all gfx objects used by GuC are allocated with [`intel_guc_allocate_vma()`](#c-intel_guc_allocate_vma)
and pinned with PIN_OFFSET_BIAS along with the value of ggtt.pin_bias.

**Return**

GGTT offset of the **vma**.


<a id="rst-guc-firmware-layout"></a>

#### GuC Firmware Layout


The GuC/HuC firmware layout looks like this:

```text
+======================================================================+
|  Firmware blob                                                       |
+===============+===============+============+============+============+
|  CSS header   |     uCode     |  RSA key   |  modulus   |  exponent  |
+===============+===============+============+============+============+
 <-header size->                 <---header size continued ----------->
 <--- size ----------------------------------------------------------->
                                 <-key size->
                                              <-mod size->
                                                           <-exp size->
```

The firmware may or may not have modulus key and exponent data. The header,
uCode and RSA signature are must-have components that will be used by driver.
Length of each components, which is all in dwords, can be found in header.
In the case that modulus and exponent are not present in fw, a.k.a truncated
image, the length value still appears in header.

Driver will do some basic fw size validation based on the following rules:

1. Header, uCode and RSA are must-have components.
2. All firmware components, if they present, are in the sequence illustrated
   in the layout table above.
3. Length info of each component can be found in header, in dwords.
4. Modulus and exponent key are not required by driver. They may not appear
   in fw. So driver will load a truncated firmware in this case.

Starting from DG2, the HuC is loaded by the GSC instead of i915. The GSC
firmware performs all the required integrity checks, we just need to check
the version. Note that the header for GSC-managed blobs is different from the
CSS used for dma-loaded firmwares.


<a id="rst-guc-memory-management"></a>

#### GuC Memory Management


GuC can't allocate any memory for its own usage, so all the allocations must
be handled by the host driver. GuC accesses the memory via the GGTT, with the
exception of the top and bottom parts of the 4GB address space, which are
instead re-mapped by the GuC HW to memory location of the FW itself (WOPCM)
or other parts of the HW. The driver must take care not to place objects that
the GuC is going to access in these reserved ranges. The layout of the GuC
address space is shown below:

```text
   +===========> +====================+ <== FFFF_FFFF
   ^             |      Reserved      |
   |             +====================+ <== GUC_GGTT_TOP
   |             |                    |
   |             |        DRAM        |
  GuC            |                    |
Address    +===> +====================+ <== GuC ggtt_pin_bias
 Space     ^     |                    |
   |       |     |                    |
   |      GuC    |        GuC         |
   |     WOPCM   |       WOPCM        |
   |      Size   |                    |
   |       |     |                    |
   v       v     |                    |
   +=======+===> +====================+ <== 0000_0000
```

The lower part of GuC Address Space \[0, ggtt_pin_bias) is mapped to GuC WOPCM
while upper part of GuC Address Space \[ggtt_pin_bias, GUC_GGTT_TOP) is mapped
to DRAM. The value of the GuC ggtt_pin_bias is the GuC WOPCM size.



#### <a id="c-intel_guc_allocate_vma"></a>`intel_guc_allocate_vma()`

```c
struct i915_vma * intel_guc_allocate_vma(struct intel_guc *guc, u32 size)
```

Allocate a GGTT VMA for GuC usage

**Parameters**

- `struct intel_guc *guc`: the guc
- `u32 size`: size of area to allocate (both virtual space and memory)

**Description**

This is a wrapper to create an object for use with the GuC. In order to
use it inside the GuC, an object needs to be pinned lifetime, so we allocate
both some backing storage and a range inside the Global GTT. We must pin
it in the GGTT somewhere other than than \[0, GUC ggtt_pin_bias) because that
range is reserved inside GuC.

**Return**

A i915_vma if successful, otherwise an ERR_PTR.


<a id="rst-guc-specific-firmware-loader"></a>

#### GuC-specific firmware loader


#### <a id="c-intel_guc_fw_upload"></a>`intel_guc_fw_upload()`

```c
int intel_guc_fw_upload(struct intel_guc *guc)
```

load GuC uCode to device

**Parameters**

- `struct intel_guc *guc`: intel_guc structure

**Description**

Called from `intel_uc_init_hw()` during driver load, resume from sleep and
after a GPU reset.

The firmware image should have already been fetched into memory, so only
check that fetch succeeded, and then transfer the image to the h/w.

**Return**

non-zero code on error


<a id="rst-guc-based-command-submission"></a>

#### GuC-based command submission


The Scratch registers:
There are 16 MMIO-based registers start from 0xC180. The kernel driver writes
a value to the action register (SOFT_SCRATCH_0) along with any data. It then
triggers an interrupt on the GuC via another register write (0xC4C8).
Firmware writes a success/fail code back to the action register after
processes the request. The kernel driver polls waiting for this update and
then proceeds.

Command Transport buffers (CTBs):
Covered in detail in other sections but CTBs (Host to GuC - H2G, GuC to Host
- G2H) are a message interface between the i915 and GuC.

Context registration:
Before a context can be submitted it must be registered with the GuC via a
H2G. A unique guc_id is associated with each context. The context is either
registered at request creation time (normal operation) or at submission time
(abnormal operation, e.g. after a reset).

Context submission:
The i915 updates the LRC tail value in memory. The i915 must enable the
scheduling of the context within the GuC for the GuC to actually consider it.
Therefore, the first time a disabled context is submitted we use a schedule
enable H2G, while follow up submissions are done via the context submit H2G,
which informs the GuC that a previously enabled context has new work
available.

Context unpin:
To unpin a context a H2G is used to disable scheduling. When the
corresponding G2H returns indicating the scheduling disable operation has
completed it is safe to unpin the context. While a disable is in flight it
isn't safe to resubmit the context so a fence is used to stall all future
requests of that context until the G2H is returned. Because this interaction
with the GuC takes a non-zero amount of time we delay the disabling of
scheduling after the pin count goes to zero by a configurable period of time
(see SCHED_DISABLE_DELAY_MS). The thought is this gives the user a window of
time to resubmit something on the context before doing this costly operation.
This delay is only done if the context isn't closed and the guc_id usage is
less than a threshold (see NUM_SCHED_DISABLE_GUC_IDS_THRESHOLD).

Context deregistration:
Before a context can be destroyed or if we steal its guc_id we must
deregister the context with the GuC via H2G. If stealing the guc_id it isn't
safe to submit anything to this guc_id until the deregister completes so a
fence is used to stall all requests associated with this guc_id until the
corresponding G2H returns indicating the guc_id has been deregistered.

submission_state.guc_ids:
Unique number associated with private GuC context data passed in during
context registration / submission / deregistration. 64k available. Simple ida
is used for allocation.

Stealing guc_ids:
If no guc_ids are available they can be stolen from another context at
request creation time if that context is unpinned. If a guc_id can't be found
we punt this problem to the user as we believe this is near impossible to hit
during normal use cases.

Locking:
In the GuC submission code we have 3 basic spin locks which protect
everything. Details about each below.

sched_engine->lock
This is the submission lock for all contexts that share an i915 schedule
engine (sched_engine), thus only one of the contexts which share a
sched_engine can be submitting at a time. Currently only one sched_engine is
used for all of GuC submission but that could change in the future.

guc->submission_state.lock
Global lock for GuC submission state. Protects guc_ids and destroyed contexts
list.

ce->guc_state.lock
Protects everything under ce->guc_state. Ensures that a context is in the
correct state before issuing a H2G. e.g. We don't issue a schedule disable
on a disabled context (bad idea), we don't issue a schedule enable when a
schedule disable is in flight, etc... Also protects list of inflight requests
on the context and the priority management state. Lock is individual to each
context.

Lock ordering rules:
sched_engine->lock -> ce->guc_state.lock
guc->submission_state.lock -> ce->guc_state.lock

Reset races:
When a full GT reset is triggered it is assumed that some G2H responses to
H2Gs can be lost as the GuC is also reset. Losing these G2H can prove to be
fatal as we do certain operations upon receiving a G2H (e.g. destroy
contexts, release guc_ids, etc...). When this occurs we can scrub the
context state and cleanup appropriately, however this is quite racey.
To avoid races, the reset code must disable submission before scrubbing for
the missing G2H, while the submission code must check for submission being
disabled and skip sending H2Gs and updating context states when it is. Both
sides must also make sure to hold the relevant locks.


<a id="rst-guc-abi"></a>

#### GuC ABI


**HXG Message**

All messages exchanged with GuC are defined using 32 bit dwords.
First dword is treated as a message header. Remaining dwords are optional.

```text
+---+-------+--------------------------------------------------------------+
|   | Bits  | Description                                                  |
+===+=======+==============================================================+
|   |       |                                                              |
| 0 |    31 | **ORIGIN** - originator of the message                       |
|   |       |   - _`GUC_HXG_ORIGIN_HOST` = 0                               |
|   |       |   - _`GUC_HXG_ORIGIN_GUC` = 1                                |
|   |       |                                                              |
|   +-------+--------------------------------------------------------------+
|   | 30:28 | **TYPE** - message type                                      |
|   |       |   - _`GUC_HXG_TYPE_REQUEST` = 0                              |
|   |       |   - _`GUC_HXG_TYPE_EVENT` = 1                                |
|   |       |   - _`GUC_HXG_TYPE_FAST_REQUEST` = 2                         |
|   |       |   - _`GUC_HXG_TYPE_NO_RESPONSE_BUSY` = 3                     |
|   |       |   - _`GUC_HXG_TYPE_NO_RESPONSE_RETRY` = 5                    |
|   |       |   - _`GUC_HXG_TYPE_RESPONSE_FAILURE` = 6                     |
|   |       |   - _`GUC_HXG_TYPE_RESPONSE_SUCCESS` = 7                     |
|   +-------+--------------------------------------------------------------+
|   |  27:0 | **AUX** - auxiliary data (depends on TYPE)                   |
+---+-------+--------------------------------------------------------------+
| 1 |  31:0 |                                                              |
+---+-------+                                                              |
|...|       | **PAYLOAD** - optional payload (depends on TYPE)             |
+---+-------+                                                              |
| n |  31:0 |                                                              |
+---+-------+--------------------------------------------------------------+
```

**HXG Request**

The `HXG Request` message should be used to initiate synchronous activity
for which confirmation or return data is expected.

The recipient of this message shall use `HXG Response`, `HXG Failure`
or `HXG Retry` message as a definite reply, and may use `HXG Busy`
message as a intermediate reply.

Format of **DATA0** and all **DATAn** fields depends on the **ACTION** code.

```text
+---+-------+--------------------------------------------------------------+
|   | Bits  | Description                                                  |
+===+=======+==============================================================+
| 0 |    31 | ORIGIN                                                       |
|   +-------+--------------------------------------------------------------+
|   | 30:28 | TYPE = GUC_HXG_TYPE_REQUEST_                                 |
|   +-------+--------------------------------------------------------------+
|   | 27:16 | **DATA0** - request data (depends on ACTION)                 |
|   +-------+--------------------------------------------------------------+
|   |  15:0 | **ACTION** - requested action code                           |
+---+-------+--------------------------------------------------------------+
| 1 |  31:0 |                                                              |
+---+-------+                                                              |
|...|       | **DATAn** - optional data (depends on ACTION)                |
+---+-------+                                                              |
| n |  31:0 |                                                              |
+---+-------+--------------------------------------------------------------+
```

**HXG Fast Request**

The `HXG Request` message should be used to initiate asynchronous activity
for which confirmation or return data is not expected.

If confirmation is required then `HXG Request` shall be used instead.

The recipient of this message may only use `HXG Failure` message if it was
unable to accept this request (like invalid data).

Format of `HXG Fast Request` message is same as `HXG Request` except **TYPE**.

```text
+---+-------+--------------------------------------------------------------+
|   | Bits  | Description                                                  |
+===+=======+==============================================================+
| 0 |    31 | ORIGIN - see `HXG Message`_                                  |
|   +-------+--------------------------------------------------------------+
|   | 30:28 | TYPE = `GUC_HXG_TYPE_FAST_REQUEST`_                          |
|   +-------+--------------------------------------------------------------+
|   | 27:16 | DATA0 - see `HXG Request`_                                   |
|   +-------+--------------------------------------------------------------+
|   |  15:0 | ACTION - see `HXG Request`_                                  |
+---+-------+--------------------------------------------------------------+
|...|       | DATAn - see `HXG Request`_                                   |
+---+-------+--------------------------------------------------------------+
```

**HXG Event**

The `HXG Event` message should be used to initiate asynchronous activity
that does not involves immediate confirmation nor data.

Format of **DATA0** and all **DATAn** fields depends on the **ACTION** code.

```text
+---+-------+--------------------------------------------------------------+
|   | Bits  | Description                                                  |
+===+=======+==============================================================+
| 0 |    31 | ORIGIN                                                       |
|   +-------+--------------------------------------------------------------+
|   | 30:28 | TYPE = GUC_HXG_TYPE_EVENT_                                   |
|   +-------+--------------------------------------------------------------+
|   | 27:16 | **DATA0** - event data (depends on ACTION)                   |
|   +-------+--------------------------------------------------------------+
|   |  15:0 | **ACTION** - event action code                               |
+---+-------+--------------------------------------------------------------+
| 1 |  31:0 |                                                              |
+---+-------+                                                              |
|...|       | **DATAn** - optional event  data (depends on ACTION)         |
+---+-------+                                                              |
| n |  31:0 |                                                              |
+---+-------+--------------------------------------------------------------+
```

**HXG Busy**

The `HXG Busy` message may be used to acknowledge reception of the `HXG Request`
message if the recipient expects that it processing will be longer than default
timeout.

The **COUNTER** field may be used as a progress indicator.

```text
+---+-------+--------------------------------------------------------------+
|   | Bits  | Description                                                  |
+===+=======+==============================================================+
| 0 |    31 | ORIGIN                                                       |
|   +-------+--------------------------------------------------------------+
|   | 30:28 | TYPE = GUC_HXG_TYPE_NO_RESPONSE_BUSY_                        |
|   +-------+--------------------------------------------------------------+
|   |  27:0 | **COUNTER** - progress indicator                             |
+---+-------+--------------------------------------------------------------+
```

**HXG Retry**

The `HXG Retry` message should be used by recipient to indicate that the
`HXG Request` message was dropped and it should be resent again.

The **REASON** field may be used to provide additional information.

```text
+---+-------+--------------------------------------------------------------+
|   | Bits  | Description                                                  |
+===+=======+==============================================================+
| 0 |    31 | ORIGIN                                                       |
|   +-------+--------------------------------------------------------------+
|   | 30:28 | TYPE = GUC_HXG_TYPE_NO_RESPONSE_RETRY_                       |
|   +-------+--------------------------------------------------------------+
|   |  27:0 | **REASON** - reason for retry                                |
|   |       |  - _`GUC_HXG_RETRY_REASON_UNSPECIFIED` = 0                   |
+---+-------+--------------------------------------------------------------+
```

**HXG Failure**

The `HXG Failure` message shall be used as a reply to the `HXG Request`
message that could not be processed due to an error.

```text
+---+-------+--------------------------------------------------------------+
|   | Bits  | Description                                                  |
+===+=======+==============================================================+
| 0 |    31 | ORIGIN                                                       |
|   +-------+--------------------------------------------------------------+
|   | 30:28 | TYPE = GUC_HXG_TYPE_RESPONSE_FAILURE_                        |
|   +-------+--------------------------------------------------------------+
|   | 27:16 | **HINT** - additional error hint                             |
|   +-------+--------------------------------------------------------------+
|   |  15:0 | **ERROR** - error/result code                                |
+---+-------+--------------------------------------------------------------+
```

**HXG Response**

The `HXG Response` message shall be used as a reply to the `HXG Request`
message that was successfully processed without an error.

```text
+---+-------+--------------------------------------------------------------+
|   | Bits  | Description                                                  |
+===+=======+==============================================================+
| 0 |    31 | ORIGIN                                                       |
|   +-------+--------------------------------------------------------------+
|   | 30:28 | TYPE = GUC_HXG_TYPE_RESPONSE_SUCCESS_                        |
|   +-------+--------------------------------------------------------------+
|   |  27:0 | **DATA0** - data (depends on ACTION from `HXG Request`_)     |
+---+-------+--------------------------------------------------------------+
| 1 |  31:0 |                                                              |
+---+-------+                                                              |
|...|       | **DATAn** - data (depends on ACTION from `HXG Request`_)     |
+---+-------+                                                              |
| n |  31:0 |                                                              |
+---+-------+--------------------------------------------------------------+
```



**GuC MMIO based communication**

The MMIO based communication between Host and GuC relies on special
hardware registers which format could be defined by the software
(so called scratch registers).

Each MMIO based message, both Host to GuC (H2G) and GuC to Host (G2H)
messages, which maximum length depends on number of available scratch
registers, is directly written into those scratch registers.

For Gen9+, there are 16 software scratch registers 0xC180-0xC1B8,
but no H2G command takes more than 4 parameters and the GuC firmware
itself uses an 4-element array to store the H2G message.

For Gen11+, there are additional 4 registers 0x190240-0x19024C, which
are, regardless on lower count, preferred over legacy ones.

The MMIO based communication is mainly used during driver initialization
phase to setup the `CTB based communication` that will be used afterwards.

**MMIO HXG Message**

Format of the MMIO messages follows definitions of `HXG Message`.

```text
+---+-------+--------------------------------------------------------------+
|   | Bits  | Description                                                  |
+===+=======+==============================================================+
| 0 |  31:0 |                                                              |
+---+-------+                                                              |
|...|       | [Embedded `HXG Message`_]                                    |
+---+-------+                                                              |
| n |  31:0 |                                                              |
+---+-------+--------------------------------------------------------------+
```



**CT Buffer**

Circular buffer used to send `CTB Message`

**CTB Descriptor**

```text
+---+-------+--------------------------------------------------------------+
|   | Bits  | Description                                                  |
+===+=======+==============================================================+
| 0 |  31:0 | **HEAD** - offset (in dwords) to the last dword that was     |
|   |       | read from the `CT Buffer`_.                                  |
|   |       | It can only be updated by the receiver.                      |
+---+-------+--------------------------------------------------------------+
| 1 |  31:0 | **TAIL** - offset (in dwords) to the last dword that was     |
|   |       | written to the `CT Buffer`_.                                 |
|   |       | It can only be updated by the sender.                        |
+---+-------+--------------------------------------------------------------+
| 2 |  31:0 | **STATUS** - status of the CTB                               |
|   |       |                                                              |
|   |       |   - _`GUC_CTB_STATUS_NO_ERROR` = 0 (normal operation)        |
|   |       |   - _`GUC_CTB_STATUS_OVERFLOW` = 1 (head/tail too large)     |
|   |       |   - _`GUC_CTB_STATUS_UNDERFLOW` = 2 (truncated message)      |
|   |       |   - _`GUC_CTB_STATUS_MISMATCH` = 4 (head/tail modified)      |
|   |       |   - _`GUC_CTB_STATUS_UNUSED` = 8 (CTB is not in use)         |
+---+-------+--------------------------------------------------------------+
|...|       | RESERVED = MBZ                                               |
+---+-------+--------------------------------------------------------------+
| 15|  31:0 | RESERVED = MBZ                                               |
+---+-------+--------------------------------------------------------------+
```

**CTB Message**

```text
+---+-------+--------------------------------------------------------------+
|   | Bits  | Description                                                  |
+===+=======+==============================================================+
| 0 | 31:16 | **FENCE** - message identifier                               |
|   +-------+--------------------------------------------------------------+
|   | 15:12 | **FORMAT** - format of the CTB message                       |
|   |       |  - _`GUC_CTB_FORMAT_HXG` = 0 - see `CTB HXG Message`_        |
|   +-------+--------------------------------------------------------------+
|   |  11:8 | **RESERVED**                                                 |
|   +-------+--------------------------------------------------------------+
|   |   7:0 | **NUM_DWORDS** - length of the CTB message (w/o header)      |
+---+-------+--------------------------------------------------------------+
| 1 |  31:0 | optional (depends on FORMAT)                                 |
+---+-------+                                                              |
|...|       |                                                              |
+---+-------+                                                              |
| n |  31:0 |                                                              |
+---+-------+--------------------------------------------------------------+
```

**CTB HXG Message**

```text
+---+-------+--------------------------------------------------------------+
|   | Bits  | Description                                                  |
+===+=======+==============================================================+
| 0 | 31:16 | FENCE                                                        |
|   +-------+--------------------------------------------------------------+
|   | 15:12 | FORMAT = GUC_CTB_FORMAT_HXG_                                 |
|   +-------+--------------------------------------------------------------+
|   |  11:8 | RESERVED = MBZ                                               |
|   +-------+--------------------------------------------------------------+
|   |   7:0 | NUM_DWORDS = length (in dwords) of the embedded HXG message  |
+---+-------+--------------------------------------------------------------+
| 1 |  31:0 |                                                              |
+---+-------+                                                              |
|...|       | [Embedded `HXG Message`_]                                    |
+---+-------+                                                              |
| n |  31:0 |                                                              |
+---+-------+--------------------------------------------------------------+
```

**CTB based communication**

The CTB (command transport buffer) communication between Host and GuC
is based on u32 data stream written to the shared buffer. One buffer can
be used to transmit data only in one direction (one-directional channel).

Current status of the each buffer is stored in the buffer descriptor.
Buffer descriptor holds tail and head fields that represents active data
stream. The tail field is updated by the data producer (sender), and head
field is updated by the data consumer (receiver):

```text
+------------+
| DESCRIPTOR |          +=================+============+========+
+============+          |                 | MESSAGE(s) |        |
| address    |--------->+=================+============+========+
+------------+
| head       |          ^-----head--------^
+------------+
| tail       |          ^---------tail-----------------^
+------------+
| size       |          ^---------------size--------------------^
+------------+
```

Each message in data stream starts with the single u32 treated as a header,
followed by optional set of u32 data that makes message specific payload:

```text
+------------+---------+---------+---------+
|         MESSAGE                          |
+------------+---------+---------+---------+
|   msg[0]   |   [1]   |   ...   |  [n-1]  |
+------------+---------+---------+---------+
|   MESSAGE  |       MESSAGE PAYLOAD       |
+   HEADER   +---------+---------+---------+
|            |    0    |   ...   |    n    |
+======+=====+=========+=========+=========+
| 31:16| code|         |         |         |
+------+-----+         |         |         |
|  15:5|flags|         |         |         |
+------+-----+         |         |         |
|   4:0|  len|         |         |         |
+------+-----+---------+---------+---------+

             ^-------------len-------------^
```

The message header consists of:

- **len**, indicates length of the message payload (in u32)
- **code**, indicates message code
- **flags**, holds various bits to control message handling



**HOST2GUC_SELF_CFG**

This message is used by Host KMD to setup of the `GuC Self Config KLVs`.

This message must be sent as `MMIO HXG Message`.

```text
+---+-------+--------------------------------------------------------------+
|   | Bits  | Description                                                  |
+===+=======+==============================================================+
| 0 |    31 | ORIGIN = GUC_HXG_ORIGIN_HOST_                                |
|   +-------+--------------------------------------------------------------+
|   | 30:28 | TYPE = GUC_HXG_TYPE_REQUEST_                                 |
|   +-------+--------------------------------------------------------------+
|   | 27:16 | DATA0 = MBZ                                                  |
|   +-------+--------------------------------------------------------------+
|   |  15:0 | ACTION = _`GUC_ACTION_HOST2GUC_SELF_CFG` = 0x0508            |
+---+-------+--------------------------------------------------------------+
| 1 | 31:16 | **KLV_KEY** - KLV key, see `GuC Self Config KLVs`_           |
|   +-------+--------------------------------------------------------------+
|   |  15:0 | **KLV_LEN** - KLV length                                     |
|   |       |                                                              |
|   |       |   - 32 bit KLV = 1                                           |
|   |       |   - 64 bit KLV = 2                                           |
+---+-------+--------------------------------------------------------------+
| 2 |  31:0 | **VALUE32** - Bits 31-0 of the KLV value                     |
+---+-------+--------------------------------------------------------------+
| 3 |  31:0 | **VALUE64** - Bits 63-32 of the KLV value (**KLV_LEN** = 2)  |
+---+-------+--------------------------------------------------------------+
```

```text
+---+-------+--------------------------------------------------------------+
|   | Bits  | Description                                                  |
+===+=======+==============================================================+
| 0 |    31 | ORIGIN = GUC_HXG_ORIGIN_GUC_                                 |
|   +-------+--------------------------------------------------------------+
|   | 30:28 | TYPE = GUC_HXG_TYPE_RESPONSE_SUCCESS_                        |
|   +-------+--------------------------------------------------------------+
|   |  27:0 | DATA0 = **NUM** - 1 if KLV was parsed, 0 if not recognized   |
+---+-------+--------------------------------------------------------------+
```

**HOST2GUC_CONTROL_CTB**

This H2G action allows Vf Host to enable or disable H2G and G2H `CT Buffer`.

This message must be sent as `MMIO HXG Message`.

```text
+---+-------+--------------------------------------------------------------+
|   | Bits  | Description                                                  |
+===+=======+==============================================================+
| 0 |    31 | ORIGIN = GUC_HXG_ORIGIN_HOST_                                |
|   +-------+--------------------------------------------------------------+
|   | 30:28 | TYPE = GUC_HXG_TYPE_REQUEST_                                 |
|   +-------+--------------------------------------------------------------+
|   | 27:16 | DATA0 = MBZ                                                  |
|   +-------+--------------------------------------------------------------+
|   |  15:0 | ACTION = _`GUC_ACTION_HOST2GUC_CONTROL_CTB` = 0x4509         |
+---+-------+--------------------------------------------------------------+
| 1 |  31:0 | **CONTROL** - control `CTB based communication`_             |
|   |       |                                                              |
|   |       |   - _`GUC_CTB_CONTROL_DISABLE` = 0                           |
|   |       |   - _`GUC_CTB_CONTROL_ENABLE` = 1                            |
+---+-------+--------------------------------------------------------------+
```

```text
+---+-------+--------------------------------------------------------------+
|   | Bits  | Description                                                  |
+===+=======+==============================================================+
| 0 |    31 | ORIGIN = GUC_HXG_ORIGIN_GUC_                                 |
|   +-------+--------------------------------------------------------------+
|   | 30:28 | TYPE = GUC_HXG_TYPE_RESPONSE_SUCCESS_                        |
|   +-------+--------------------------------------------------------------+
|   |  27:0 | DATA0 = MBZ                                                  |
+---+-------+--------------------------------------------------------------+
```



**GuC KLV**

```text
+---+-------+--------------------------------------------------------------+
|   | Bits  | Description                                                  |
+===+=======+==============================================================+
| 0 | 31:16 | **KEY** - KLV key identifier                                 |
|   |       |   - `GuC Self Config KLVs`_                                  |
|   |       |                                                              |
|   +-------+--------------------------------------------------------------+
|   |  15:0 | **LEN** - length of VALUE (in 32bit dwords)                  |
+---+-------+--------------------------------------------------------------+
| 1 |  31:0 | **VALUE** - actual value of the KLV (format depends on KEY)  |
+---+-------+                                                              |
|...|       |                                                              |
+---+-------+                                                              |
| n |  31:0 |                                                              |
+---+-------+--------------------------------------------------------------+
```

**GuC Self Config KLVs**

`GuC KLV` keys available for use with HOST2GUC_SELF_CFG_.

- _`GUC_KLV_SELF_CFG_H2G_CTB_ADDR` : 0x0902

  Refers to 64 bit Global Gfx address of H2G `CT Buffer`.
  Should be above WOPCM address but below APIC base address for native mode.

- _`GUC_KLV_SELF_CFG_H2G_CTB_DESCRIPTOR_ADDR` : 0x0903

  Refers to 64 bit Global Gfx address of H2G `CTB Descriptor`.
  Should be above WOPCM address but below APIC base address for native mode.

- _`GUC_KLV_SELF_CFG_H2G_CTB_SIZE` : 0x0904

  Refers to size of H2G `CT Buffer` in bytes.
  Should be a multiple of 4K.

- _`GUC_KLV_SELF_CFG_G2H_CTB_ADDR` : 0x0905

  Refers to 64 bit Global Gfx address of G2H `CT Buffer`.
  Should be above WOPCM address but below APIC base address for native mode.

- _`GUC_KLV_SELF_CFG_G2H_CTB_DESCRIPTOR_ADDR` : 0x0906

  Refers to 64 bit Global Gfx address of G2H `CTB Descriptor`.
  Should be above WOPCM address but below APIC base address for native mode.

- _`GUC_KLV_SELF_CFG_G2H_CTB_SIZE` : 0x0907

  Refers to size of G2H `CT Buffer` in bytes.
  Should be a multiple of 4K.


<a id="rst-huc"></a>

### HuC


The HuC is a dedicated microcontroller for usage in media HEVC (High
Efficiency Video Coding) operations. Userspace can directly use the firmware
capabilities by adding HuC specific commands to batch buffers.

The kernel driver is only responsible for loading the HuC firmware and
triggering its security authentication. This is done differently depending
on the platform:

- older platforms (from Gen9 to most Gen12s): the load is performed via DMA
  and the authentication via GuC
- DG2: load and authentication are both performed via GSC.
- MTL and newer platforms: the load is performed via DMA (same as with
  not-DG2 older platforms), while the authentication is done in 2-steps,
  a first auth for clear-media workloads via GuC and a second one for all
  workloads via GSC.

On platforms where the GuC does the authentication, to correctly do so the
HuC binary must be loaded before the GuC one.
Loading the HuC is optional; however, not using the HuC might negatively
impact power usage and/or performance of media workloads, depending on the
use-cases.
HuC must be reloaded on events that cause the WOPCM to lose its contents
(S3/S4, FLR); on older platforms the HuC must also be reloaded on GuC/GT
reset, while on newer ones it will survive that.

See https://github.com/intel/media-driver for the latest details on HuC
functionality.



#### <a id="c-intel_huc_auth"></a>`intel_huc_auth()`

```c
int intel_huc_auth(struct intel_huc *huc, enum intel_huc_authentication_type type)
```

Authenticate HuC uCode

**Parameters**

- `struct intel_huc *huc`: intel_huc structure
- `enum intel_huc_authentication_type type`: authentication type (via GuC or via GSC)

**Description**

Called after HuC and GuC firmware loading during `intel_uc_init_hw()`.

This function invokes the GuC action to authenticate the HuC firmware,
passing the offset of the RSA signature to `intel_guc_auth_huc()`. It then
waits for up to 50ms for firmware verification ACK.


<a id="rst-huc-memory-management"></a>

#### HuC Memory Management


Similarly to the GuC, the HuC can't do any memory allocations on its own,
with the difference being that the allocations for HuC usage are handled by
the userspace driver instead of the kernel one. The HuC accesses the memory
via the PPGTT belonging to the context loaded on the VCS executing the
HuC-specific commands.


<a id="rst-huc-firmware-layout"></a>

#### HuC Firmware Layout

The HuC FW layout is the same as the GuC one, see [GuC Firmware Layout](<#rst-guc-firmware-layout>)

<a id="rst-dmc"></a>

### DMC

See [DMC Firmware Support](<#rst-dmc-firmware-support>)

<a id="rst-tracing"></a>

## Tracing

This sections covers all things related to the tracepoints implemented in the i915 driver.

<a id="rst-i915-ppgtt-create-and-i915-ppgtt-release"></a>

### i915_ppgtt_create and i915_ppgtt_release


With full ppgtt enabled each process using drm will allocate at least one
translation table. With these traces it is possible to keep track of the
allocation and of the lifetime of the tables; this can be used during
testing/debug to verify that we are not leaking ppgtts.
These traces identify the ppgtt through the vm pointer, which is also printed
by the i915_vma_bind and i915_vma_unbind tracepoints.


<a id="rst-i915-context-create-and-i915-context-free"></a>

### i915_context_create and i915_context_free


These tracepoints are used to track creation and deletion of contexts.
If full ppgtt is enabled, they also print the address of the vm assigned to
the context.


<a id="rst-perf"></a>

## Perf

<a id="rst-overview"></a>

### Overview


Gen graphics supports a large number of performance counters that can help
driver and application developers understand and optimize their use of the
GPU.

This i915 perf interface enables userspace to configure and open a file
descriptor representing a stream of GPU metrics which can then be `read()` as
a stream of sample records.

The interface is particularly suited to exposing buffered metrics that are
captured by DMA from the GPU, unsynchronized with and unrelated to the CPU.

Streams representing a single context are accessible to applications with a
corresponding drm file descriptor, such that OpenGL can use the interface
without special privileges. Access to system-wide metrics requires root
privileges by default, unless changed via the dev.i915.perf_event_paranoid
sysctl option.


<a id="rst-comparison-with-core-perf"></a>

### Comparison with Core Perf


The interface was initially inspired by the core Perf infrastructure but
some notable differences are:

i915 perf file descriptors represent a "stream" instead of an "event"; where
a perf event primarily corresponds to a single 64bit value, while a stream
might sample sets of tightly-coupled counters, depending on the
configuration.  For example the Gen OA unit isn't designed to support
orthogonal configurations of individual counters; it's configured for a set
of related counters. Samples for an i915 perf stream capturing OA metrics
will include a set of counter values packed in a compact HW specific format.
The OA unit supports a number of different packing formats which can be
selected by the user opening the stream. Perf has support for grouping
events, but each event in the group is configured, validated and
authenticated individually with separate system calls.

i915 perf stream configurations are provided as an array of u64 (key,value)
pairs, instead of a fixed struct with multiple miscellaneous config members,
interleaved with event-type specific members.

i915 perf doesn't support exposing metrics via an mmap'd circular buffer.
The supported metrics are being written to memory by the GPU unsynchronized
with the CPU, using HW specific packing formats for counter sets. Sometimes
the constraints on HW configuration require reports to be filtered before it
would be acceptable to expose them to unprivileged applications - to hide
the metrics of other processes/contexts. For these use cases a `read()` based
interface is a good fit, and provides an opportunity to filter data as it
gets copied from the GPU mapped buffers to userspace buffers.

**Issues hit with first prototype based on Core Perf**

The first prototype of this driver was based on the core perf
infrastructure, and while we did make that mostly work, with some changes to
perf, we found we were breaking or working around too many assumptions baked
into perf's currently cpu centric design.

In the end we didn't see a clear benefit to making perf's implementation and
interface more complex by changing design assumptions while we knew we still
wouldn't be able to use any existing perf based userspace tools.

Also considering the Gen specific nature of the Observability hardware and
how userspace will sometimes need to combine i915 perf OA metrics with
side-band OA data captured via MI_REPORT_PERF_COUNT commands; we're
expecting the interface to be used by a platform specific userspace such as
OpenGL or tools. This is to say; we aren't inherently missing out on having
a standard vendor/architecture agnostic interface by not using perf.

For posterity, in case we might re-visit trying to adapt core perf to be
better suited to exposing i915 metrics these were the main pain points we
hit:

- The perf based OA PMU driver broke some significant design assumptions:

  Existing perf pmus are used for profiling work on a cpu and we were
  introducing the idea of _IS_DEVICE pmus with different security
  implications, the need to fake cpu-related data (such as user/kernel
  registers) to fit with perf's current design, and adding _DEVICE records
  as a way to forward device-specific status records.

  The OA unit writes reports of counters into a circular buffer, without
  involvement from the CPU, making our PMU driver the first of a kind.

  Given the way we were periodically forward data from the GPU-mapped, OA
  buffer to perf's buffer, those bursts of sample writes looked to perf like
  we were sampling too fast and so we had to subvert its throttling checks.

  Perf supports groups of counters and allows those to be read via
  transactions internally but transactions currently seem designed to be
  explicitly initiated from the cpu (say in response to a userspace `read()`)
  and while we could pull a report out of the OA buffer we can't
  trigger a report from the cpu on demand.

  Related to being report based; the OA counters are configured in HW as a
  set while perf generally expects counter configurations to be orthogonal.
  Although counters can be associated with a group leader as they are
  opened, there's no clear precedent for being able to provide group-wide
  configuration attributes (for example we want to let userspace choose the
  OA unit report format used to capture all counters in a set, or specify a
  GPU context to filter metrics on). We avoided using perf's grouping
  feature and forwarded OA reports to userspace via perf's 'raw' sample
  field. This suited our userspace well considering how coupled the counters
  are when dealing with normalizing. It would be inconvenient to split
  counters up into separate events, only to require userspace to recombine
  them. For Mesa it's also convenient to be forwarded raw, periodic reports
  for combining with the side-band raw reports it captures using
  MI_REPORT_PERF_COUNT commands.

  - As a side note on perf's grouping feature; there was also some concern
    that using PERF_FORMAT_GROUP as a way to pack together counter values
    would quite drastically inflate our sample sizes, which would likely
    lower the effective sampling resolutions we could use when the available
    memory bandwidth is limited.

    With the OA unit's report formats, counters are packed together as 32
    or 40bit values, with the largest report size being 256 bytes.

    PERF_FORMAT_GROUP values are 64bit, but there doesn't appear to be a
    documented ordering to the values, implying PERF_FORMAT_ID must also be
    used to add a 64bit ID before each value; giving 16 bytes per counter.

  Related to counter orthogonality; we can't time share the OA unit, while
  event scheduling is a central design idea within perf for allowing
  userspace to open + enable more events than can be configured in HW at any
  one time.  The OA unit is not designed to allow re-configuration while in
  use. We can't reconfigure the OA unit without losing internal OA unit
  state which we can't access explicitly to save and restore. Reconfiguring
  the OA unit is also relatively slow, involving ~100 register writes. From
  userspace Mesa also depends on a stable OA configuration when emitting
  MI_REPORT_PERF_COUNT commands and importantly the OA unit can't be
  disabled while there are outstanding MI_RPC commands lest we hang the
  command streamer.

  The contents of sample records aren't extensible by device drivers (i.e.
  the sample_type bits). As an example; Sourab Gupta had been looking to
  attach GPU timestamps to our OA samples. We were shoehorning OA reports
  into sample records by using the 'raw' field, but it's tricky to pack more
  than one thing into this field because events/core.c currently only lets a
  pmu give a single raw data pointer plus len which will be copied into the
  ring buffer. To include more than the OA report we'd have to copy the
  report into an intermediate larger buffer. I'd been considering allowing a
  vector of data+len values to be specified for copying the raw data, but
  it felt like a kludge to being using the raw field for this purpose.

- It felt like our perf based PMU was making some technical compromises
  just for the sake of using perf:

  `perf_event_open()` requires events to either relate to a pid or a specific
  cpu core, while our device pmu related to neither.  Events opened with a
  pid will be automatically enabled/disabled according to the scheduling of
  that process - so not appropriate for us. When an event is related to a
  cpu id, perf ensures pmu methods will be invoked via an inter process
  interrupt on that core. To avoid invasive changes our userspace opened OA
  perf events for a specific cpu. This was workable but it meant the
  majority of the OA driver ran in atomic context, including all OA report
  forwarding, which wasn't really necessary in our case and seems to make
  our locking requirements somewhat complex as we handled the interaction
  with the rest of the i915 driver.


<a id="rst-i915-driver-entry-points"></a>

### i915 Driver Entry Points

This section covers the entrypoints exported outside of i915_perf.c to integrate with drm/i915 and to handle the `DRM_I915_PERF_OPEN` ioctl.


#### <a id="c-i915_perf_init"></a>`i915_perf_init()`

```c
int i915_perf_init(struct drm_i915_private *i915)
```

initialize i915-perf state on module bind

**Parameters**

- `struct drm_i915_private *i915`: i915 device instance

**Description**

Initializes i915-perf state without exposing anything to userspace.

**Note**

i915-perf initialization is split into an 'init' and 'register'
phase with the [`i915_perf_register()`](#c-i915_perf_register) exposing state to userspace.



#### <a id="c-i915_perf_fini"></a>`i915_perf_fini()`

```c
void i915_perf_fini(struct drm_i915_private *i915)
```

Counter part to [`i915_perf_init()`](#c-i915_perf_init)

**Parameters**

- `struct drm_i915_private *i915`: i915 device instance



#### <a id="c-i915_perf_register"></a>`i915_perf_register()`

```c
void i915_perf_register(struct drm_i915_private *i915)
```

exposes i915-perf to userspace

**Parameters**

- `struct drm_i915_private *i915`: i915 device instance

**Description**

In particular OA metric sets are advertised under a sysfs metrics/
directory allowing userspace to enumerate valid IDs that can be
used to open an i915-perf stream.



#### <a id="c-i915_perf_unregister"></a>`i915_perf_unregister()`

```c
void i915_perf_unregister(struct drm_i915_private *i915)
```

hide i915-perf from userspace

**Parameters**

- `struct drm_i915_private *i915`: i915 device instance

**Description**

i915-perf state cleanup is split up into an 'unregister' and
'deinit' phase where the interface is first hidden from
userspace by [`i915_perf_unregister()`](#c-i915_perf_unregister) before cleaning up
remaining state in [`i915_perf_fini()`](#c-i915_perf_fini).



#### <a id="c-i915_perf_open_ioctl"></a>`i915_perf_open_ioctl()`

```c
int i915_perf_open_ioctl(struct drm_device *dev, void *data, struct drm_file *file)
```

DRM `ioctl()` for userspace to open a stream FD

**Parameters**

- `struct drm_device *dev`: drm device
- `void *data`: ioctl data copied from userspace (unvalidated)
- `struct drm_file *file`: drm file

**Description**

Validates the stream open parameters given by userspace including flags
and an array of u64 key, value pair properties.

Very little is assumed up front about the nature of the stream being
opened (for instance we don't assume it's for periodic OA unit metrics). An
i915-perf stream is expected to be a suitable interface for other forms of
buffered data written by the GPU besides periodic OA metrics.

Note we copy the properties from userspace outside of the i915 perf
mutex to avoid an awkward lockdep with mmap_lock.

Most of the implementation details are handled by
[`i915_perf_open_ioctl_locked()`](#c-i915_perf_open_ioctl_locked) after taking the `gt->perf`.lock
mutex for serializing with any non-file-operation driver hooks.

**Return**

A newly opened i915 Perf stream file descriptor or negative
error code on failure.



#### <a id="c-i915_perf_release"></a>`i915_perf_release()`

```c
int i915_perf_release(struct inode *inode, struct file *file)
```

handles userspace `close()` of a stream file

**Parameters**

- `struct inode *inode`: anonymous inode associated with file
- `struct file *file`: An i915 perf stream file

**Description**

Cleans up any resources associated with an open i915 perf stream file.

NB: `close()` can't really fail from the userspace point of view.

**Return**

zero on success or a negative error code.



#### <a id="c-i915_perf_add_config_ioctl"></a>`i915_perf_add_config_ioctl()`

```c
int i915_perf_add_config_ioctl(struct drm_device *dev, void *data, struct drm_file *file)
```

DRM `ioctl()` for userspace to add a new OA config

**Parameters**

- `struct drm_device *dev`: drm device
- `void *data`: ioctl data (pointer to struct drm_i915_perf_oa_config) copied from
  userspace (unvalidated)
- `struct drm_file *file`: drm file

**Description**

Validates the submitted OA register to be saved into a new OA config that
can then be used for programming the OA unit and its NOA network.

**Return**

A new allocated config number to be used with the perf open ioctl
or a negative error code on failure.



#### <a id="c-i915_perf_remove_config_ioctl"></a>`i915_perf_remove_config_ioctl()`

```c
int i915_perf_remove_config_ioctl(struct drm_device *dev, void *data, struct drm_file *file)
```

DRM `ioctl()` for userspace to remove an OA config

**Parameters**

- `struct drm_device *dev`: drm device
- `void *data`: ioctl data (pointer to u64 integer) copied from userspace
- `struct drm_file *file`: drm file

**Description**

Configs can be removed while being used, the will stop appearing in sysfs
and their content will be freed when the stream using the config is closed.

**Return**

0 on success or a negative error code on failure.


<a id="rst-i915-perf-stream"></a>

### i915 Perf Stream

This section covers the stream-semantics-agnostic structures and functions for representing an i915 perf stream FD and associated file operations.


#### <a id="c-struct-i915_perf_stream"></a>`struct i915_perf_stream`

state for a single open stream FD

**Definition**

```c
struct i915_perf_stream {
    struct i915_perf *perf;
    struct intel_uncore *uncore;
    struct intel_engine_cs *engine;
    struct mutex lock;
    u32 sample_flags;
    int sample_size;
    struct i915_gem_context *ctx;
    bool enabled;
    bool hold_preemption;
    const struct i915_perf_stream_ops *ops;
    struct i915_oa_config *oa_config;
    struct llist_head oa_config_bos;
    struct intel_context *pinned_ctx;
    u32 specific_ctx_id;
    u32 specific_ctx_id_mask;
    struct hrtimer poll_check_timer;
    wait_queue_head_t poll_wq;
    bool pollin;
    bool periodic;
    int period_exponent;
    struct {
        const struct i915_oa_format *format;
        struct i915_vma *vma;
        u8 *vaddr;
        u32 last_ctx_id;
        spinlock_t ptr_lock;
        u32 head;
        u32 tail;
    } oa_buffer;
    struct i915_vma *noa_wait;
    u64 poll_oa_period;
};
```

**Members**

- `perf`: i915_perf backpointer
- `uncore`: mmio access path
- `engine`: Engine associated with this performance stream.
- `lock`: Lock associated with operations on stream
- `sample_flags`: Flags representing the `DRM_I915_PERF_PROP_SAMPLE_*`
  properties given when opening a stream, representing the contents
  of a single sample as `read()` by userspace.
- `sample_size`: Considering the configured contents of a sample
  combined with the required header size, this is the total size
  of a single sample record.
- `ctx`: `NULL` if measuring system-wide across all contexts or a
  specific context that is being monitored.
- `enabled`: Whether the stream is currently enabled, considering
  whether the stream was opened in a disabled state and based
  on `I915_PERF_IOCTL_ENABLE` and `I915_PERF_IOCTL_DISABLE` calls.
- `hold_preemption`: Whether preemption is put on hold for command
  submissions done on the **ctx**. This is useful for some drivers that
  cannot easily post process the OA buffer context to subtract delta
  of performance counters not associated with **ctx**.
- `ops`: The callbacks providing the implementation of this specific
  type of configured stream.
- `oa_config`: The OA configuration used by the stream.
- `oa_config_bos`: A list of struct i915_oa_config_bo allocated lazily
  each time **oa_config** changes.
- `pinned_ctx`: The OA context specific information.
- `specific_ctx_id`: The id of the specific context.
- `specific_ctx_id_mask`: The mask used to masking specific_ctx_id bits.
- `poll_check_timer`: High resolution timer that will periodically
  check for data in the circular OA buffer for notifying userspace
  (e.g. during a `read()` or `poll()`).
- `poll_wq`: The wait queue that hrtimer callback wakes when it
  sees data ready to read in the circular OA buffer.
- `pollin`: Whether there is data available to read.
- `periodic`: Whether periodic sampling is currently enabled.
- `period_exponent`: The OA unit sampling frequency is derived from this.
- `oa_buffer`: State of the OA buffer.
- `oa_buffer.ptr_lock`: Locks reads and writes to all
  head/tail state

  Consider: the head and tail pointer state needs to be read
  consistently from a hrtimer callback (atomic context) and
  `read()` fop (user context) with tail pointer updates happening
  in atomic context and head updates in user context and the
  (unlikely) possibility of `read()` errors needing to reset all
  head/tail state.

  Note: Contention/performance aren't currently a significant
  concern here considering the relatively low frequency of
  hrtimer callbacks (5ms period) and that reads typically only
  happen in response to a hrtimer event and likely complete
  before the next callback.

  Note: This lock is not held *while* reading and copying data
  to userspace so the value of head observed in htrimer
  callbacks won't represent any partial consumption of data.
- `oa_buffer.head`: Although we can always read back
  the head pointer register,
  we prefer to avoid trusting the HW state, just to avoid any
  risk that some hardware condition could * somehow bump the
  head pointer unpredictably and cause us to forward the wrong
  OA buffer data to userspace.
- `oa_buffer.tail`: The last verified tail that can be
  read by userspace.
- `noa_wait`: A batch buffer doing a wait on the GPU for the NOA logic to be
  reprogrammed.
- `poll_oa_period`: The period in nanoseconds at which the OA
  buffer should be checked for available data.



#### <a id="c-struct-i915_perf_stream_ops"></a>`struct i915_perf_stream_ops`

the OPs to support a specific stream type

**Definition**

```c
struct i915_perf_stream_ops {
    void (*enable)(struct i915_perf_stream *stream);
    void (*disable)(struct i915_perf_stream *stream);
    void (*poll_wait)(struct i915_perf_stream *stream, struct file *file, poll_table *wait);
    int (*wait_unlocked)(struct i915_perf_stream *stream);
    int (*read)(struct i915_perf_stream *stream, char __user *buf, size_t count, size_t *offset);
    void (*destroy)(struct i915_perf_stream *stream);
};
```

**Members**

- `enable`: Enables the collection of HW samples, either in response to
  `I915_PERF_IOCTL_ENABLE` or implicitly called when stream is opened
  without `I915_PERF_FLAG_DISABLED`.
- `disable`: Disables the collection of HW samples, either in response
  to `I915_PERF_IOCTL_DISABLE` or implicitly called before destroying
  the stream.
- `poll_wait`: Call poll_wait, passing a wait queue that will be woken
  once there is something ready to `read()` for the stream
- `wait_unlocked`: For handling a blocking read, wait until there is
  something to ready to `read()` for the stream. E.g. wait on the same
  wait queue that would be passed to `poll_wait()`.
- `read`: Copy buffered metrics as records to userspace
  **buf**: the userspace, destination buffer
  **count**: the number of bytes to copy, requested by userspace
  **offset**: zero at the start of the read, updated as the read
  proceeds, it represents how many bytes have been copied so far and
  the buffer offset for copying the next record.

  Copy as many buffered i915 perf samples and records for this stream
  to userspace as will fit in the given buffer.

  Only write complete records; returning -`ENOSPC` if there isn't room
  for a complete record.

  Return any error condition that results in a short read such as
  -`ENOSPC` or -`EFAULT`, even though these may be squashed before
  returning to userspace.
- `destroy`: Cleanup any stream specific resources.

  The stream will always be disabled before this is called.



#### <a id="c-read_properties_unlocked"></a>`read_properties_unlocked()`

```c
int read_properties_unlocked(struct i915_perf *perf, u64 __user *uprops, u32 n_props, struct perf_open_properties *props)
```

validate + copy userspace stream open properties

**Parameters**

- `struct i915_perf *perf`: i915 perf instance
- `u64 __user *uprops`: The array of u64 key value pairs given by userspace
- `u32 n_props`: The number of key value pairs expected in **uprops**
- `struct perf_open_properties *props`: The stream configuration built up while validating properties

**Description**

Note this function only validates properties in isolation it doesn't
validate that the combination of properties makes sense or that all
properties necessary for a particular kind of stream have been set.

Note that there currently aren't any ordering requirements for properties so
we shouldn't validate or assume anything about ordering here. This doesn't
rule out defining new properties with ordering requirements in the future.



#### <a id="c-i915_perf_open_ioctl_locked"></a>`i915_perf_open_ioctl_locked()`

```c
int i915_perf_open_ioctl_locked(struct i915_perf *perf, struct drm_i915_perf_open_param *param, struct perf_open_properties *props, struct drm_file *file)
```

DRM `ioctl()` for userspace to open a stream FD

**Parameters**

- `struct i915_perf *perf`: i915 perf instance
- `struct drm_i915_perf_open_param *param`: The open parameters passed to 'DRM_I915_PERF_OPEN`
- `struct perf_open_properties *props`: individually validated u64 property value pairs
- `struct drm_file *file`: drm file

**Description**

See `i915_perf_ioctl_open()` for interface details.

Implements further stream config validation and stream initialization on
behalf of [`i915_perf_open_ioctl()`](#c-i915_perf_open_ioctl) with the `gt->perf`.lock mutex
taken to serialize with any non-file-operation driver hooks.

**Note**

at this point the **props** have only been validated in isolation and
it's still necessary to validate that the combination of properties makes
sense.

In the case where userspace is interested in OA unit metrics then further
config validation and stream initialization details will be handled by
[`i915_oa_stream_init()`](#c-i915_oa_stream_init). The code here should only validate config state that
will be relevant to all stream types / backends.

**Return**

zero on success or a negative error code.



#### <a id="c-i915_perf_destroy_locked"></a>`i915_perf_destroy_locked()`

```c
void i915_perf_destroy_locked(struct i915_perf_stream *stream)
```

destroy an i915 perf stream

**Parameters**

- `struct i915_perf_stream *stream`: An i915 perf stream

**Description**

Frees all resources associated with the given i915 perf **stream**, disabling
any associated data capture in the process.

**Note**

The `gt->perf`.lock mutex has been taken to serialize
with any non-file-operation driver hooks.



#### <a id="c-i915_perf_read"></a>`i915_perf_read()`

```c
ssize_t i915_perf_read(struct file *file, char __user *buf, size_t count, loff_t *ppos)
```

handles `read()` FOP for i915 perf stream FDs

**Parameters**

- `struct file *file`: An i915 perf stream file
- `char __user *buf`: destination buffer given by userspace
- `size_t count`: the number of bytes userspace wants to read
- `loff_t *ppos`: (inout) file seek position (unused)

**Description**

The entry point for handling a `read()` on a stream file descriptor from
userspace. Most of the work is left to the `i915_perf_read_locked()` and
[`i915_perf_stream_ops->read`](#c-struct-i915_perf_stream_ops) but to save having stream implementations (of
which we might have multiple later) we handle blocking read here.

We can also consistently treat trying to read from a disabled stream
as an IO error so implementations can assume the stream is enabled
while reading.

**Return**

The number of bytes copied or a negative error code on failure.



#### <a id="c-i915_perf_ioctl"></a>`i915_perf_ioctl()`

```c
long i915_perf_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
```

support `ioctl()` usage with i915 perf stream FDs

**Parameters**

- `struct file *file`: An i915 perf stream file
- `unsigned int cmd`: the ioctl request
- `unsigned long arg`: the ioctl data

**Description**

Implementation deferred to [`i915_perf_ioctl_locked()`](#c-i915_perf_ioctl_locked).

**Return**

zero on success or a negative error code. Returns -EINVAL for
an unknown ioctl request.



#### <a id="c-i915_perf_enable_locked"></a>`i915_perf_enable_locked()`

```c
void i915_perf_enable_locked(struct i915_perf_stream *stream)
```

handle `I915_PERF_IOCTL_ENABLE` ioctl

**Parameters**

- `struct i915_perf_stream *stream`: A disabled i915 perf stream

**Description**

\[Re\]enables the associated capture of data for this stream.

If a stream was previously enabled then there's currently no intention
to provide userspace any guarantee about the preservation of previously
buffered data.



#### <a id="c-i915_perf_disable_locked"></a>`i915_perf_disable_locked()`

```c
void i915_perf_disable_locked(struct i915_perf_stream *stream)
```

handle `I915_PERF_IOCTL_DISABLE` ioctl

**Parameters**

- `struct i915_perf_stream *stream`: An enabled i915 perf stream

**Description**

Disables the associated capture of data for this stream.

The intention is that disabling an re-enabling a stream will ideally be
cheaper than destroying and re-opening a stream with the same configuration,
though there are no formal guarantees about what state or buffered data
must be retained between disabling and re-enabling a stream.

**Note**

while a stream is disabled it's considered an error for userspace
to attempt to read from the stream (-EIO).



#### <a id="c-i915_perf_poll"></a>`i915_perf_poll()`

```c
__poll_t i915_perf_poll(struct file *file, poll_table *wait)
```

call `poll_wait()` with a suitable wait queue for stream

**Parameters**

- `struct file *file`: An i915 perf stream file
- `poll_table *wait`: `poll()` state table

**Description**

For handling userspace polling on an i915 perf stream, this ensures
`poll_wait()` gets called with a wait queue that will be woken for new stream
data.

**Note**

Implementation deferred to [`i915_perf_poll_locked()`](#c-i915_perf_poll_locked)

**Return**

any poll events that are ready without sleeping



#### <a id="c-i915_perf_poll_locked"></a>`i915_perf_poll_locked()`

```c
__poll_t i915_perf_poll_locked(struct i915_perf_stream *stream, struct file *file, poll_table *wait)
```

`poll_wait()` with a suitable wait queue for stream

**Parameters**

- `struct i915_perf_stream *stream`: An i915 perf stream
- `struct file *file`: An i915 perf stream file
- `poll_table *wait`: `poll()` state table

**Description**

For handling userspace polling on an i915 perf stream, this calls through to
[`i915_perf_stream_ops->poll_wait`](#c-struct-i915_perf_stream_ops) to call `poll_wait()` with a wait queue that
will be woken for new stream data.

**Return**

any poll events that are ready without sleeping


<a id="rst-i915-perf-observation-architecture-stream"></a>

### i915 Perf Observation Architecture Stream


#### <a id="c-struct-i915_oa_ops"></a>`struct i915_oa_ops`

Gen specific implementation of an OA unit stream

**Definition**

```c
struct i915_oa_ops {
    bool (*is_valid_b_counter_reg)(struct i915_perf *perf, u32 addr);
    bool (*is_valid_mux_reg)(struct i915_perf *perf, u32 addr);
    bool (*is_valid_flex_reg)(struct i915_perf *perf, u32 addr);
    int (*enable_metric_set)(struct i915_perf_stream *stream, struct i915_active *active);
    void (*disable_metric_set)(struct i915_perf_stream *stream);
    void (*oa_enable)(struct i915_perf_stream *stream);
    void (*oa_disable)(struct i915_perf_stream *stream);
    int (*read)(struct i915_perf_stream *stream, char __user *buf, size_t count, size_t *offset);
    u32 (*oa_hw_tail_read)(struct i915_perf_stream *stream);
};
```

**Members**

- `is_valid_b_counter_reg`: Validates register's address for
  programming boolean counters for a particular platform.
- `is_valid_mux_reg`: Validates register's address for programming mux
  for a particular platform.
- `is_valid_flex_reg`: Validates register's address for programming
  flex EU filtering for a particular platform.
- `enable_metric_set`: Selects and applies any MUX configuration to set
  up the Boolean and Custom (B/C) counters that are part of the
  counter reports being sampled. May apply system constraints such as
  disabling EU clock gating as required.
- `disable_metric_set`: Remove system constraints associated with using
  the OA unit.
- `oa_enable`: Enable periodic sampling
- `oa_disable`: Disable periodic sampling
- `read`: Copy data from the circular OA buffer into a given userspace
  buffer.
- `oa_hw_tail_read`: read the OA tail pointer register

  In particular this enables us to share all the fiddly code for
  handling the OA unit tail pointer race that affects multiple
  generations.



#### <a id="c-i915_oa_stream_init"></a>`i915_oa_stream_init()`

```c
int i915_oa_stream_init(struct i915_perf_stream *stream, struct drm_i915_perf_open_param *param, struct perf_open_properties *props)
```

validate combined props for OA stream and init

**Parameters**

- `struct i915_perf_stream *stream`: An i915 perf stream
- `struct drm_i915_perf_open_param *param`: The open parameters passed to `DRM_I915_PERF_OPEN`
- `struct perf_open_properties *props`: The property state that configures stream (individually validated)

**Description**

While [`read_properties_unlocked()`](#c-read_properties_unlocked) validates properties in isolation it
doesn't ensure that the combination necessarily makes sense.

At this point it has been determined that userspace wants a stream of
OA metrics, but still we need to further validate the combined
properties are OK.

If the configuration makes sense then we can allocate memory for
a circular OA buffer and apply the requested metric set configuration.

**Return**

zero on success or a negative error code.



#### <a id="c-i915_oa_read"></a>`i915_oa_read()`

```c
int i915_oa_read(struct i915_perf_stream *stream, char __user *buf, size_t count, size_t *offset)
```

just calls through to [`i915_oa_ops->read`](#c-struct-i915_oa_ops)

**Parameters**

- `struct i915_perf_stream *stream`: An i915-perf stream opened for OA metrics
- `char __user *buf`: destination buffer given by userspace
- `size_t count`: the number of bytes userspace wants to read
- `size_t *offset`: (inout): the current position for writing into **buf**

**Description**

Updates **offset** according to the number of bytes successfully copied into
the userspace buffer.

**Return**

zero on success or a negative error code



#### <a id="c-i915_oa_stream_enable"></a>`i915_oa_stream_enable()`

```c
void i915_oa_stream_enable(struct i915_perf_stream *stream)
```

handle `I915_PERF_IOCTL_ENABLE` for OA stream

**Parameters**

- `struct i915_perf_stream *stream`: An i915 perf stream opened for OA metrics

**Description**

\[Re\]enables hardware periodic sampling according to the period configured
when opening the stream. This also starts a hrtimer that will periodically
check for data in the circular OA buffer for notifying userspace (e.g.
during a `read()` or `poll()`).



#### <a id="c-i915_oa_stream_disable"></a>`i915_oa_stream_disable()`

```c
void i915_oa_stream_disable(struct i915_perf_stream *stream)
```

handle `I915_PERF_IOCTL_DISABLE` for OA stream

**Parameters**

- `struct i915_perf_stream *stream`: An i915 perf stream opened for OA metrics

**Description**

Stops the OA unit from periodically writing counter reports into the
circular OA buffer. This also stops the hrtimer that periodically checks for
data in the circular OA buffer, for notifying userspace.



#### <a id="c-i915_oa_wait_unlocked"></a>`i915_oa_wait_unlocked()`

```c
int i915_oa_wait_unlocked(struct i915_perf_stream *stream)
```

handles blocking IO until OA data available

**Parameters**

- `struct i915_perf_stream *stream`: An i915-perf stream opened for OA metrics

**Description**

Called when userspace tries to `read()` from a blocking stream FD opened
for OA metrics. It waits until the hrtimer callback finds a non-empty
OA buffer and wakes us.

**Note**

it's acceptable to have this return with some false positives
since any subsequent read handling will return -EAGAIN if there isn't
really data ready for userspace yet.

**Return**

zero on success or a negative error code



#### <a id="c-i915_oa_poll_wait"></a>`i915_oa_poll_wait()`

```c
void i915_oa_poll_wait(struct i915_perf_stream *stream, struct file *file, poll_table *wait)
```

call `poll_wait()` for an OA stream `poll()`

**Parameters**

- `struct i915_perf_stream *stream`: An i915-perf stream opened for OA metrics
- `struct file *file`: An i915 perf stream file
- `poll_table *wait`: `poll()` state table

**Description**

For handling userspace polling on an i915 perf stream opened for OA metrics,
this starts a poll_wait with the wait queue that our hrtimer callback wakes
when it sees data ready to read in the circular OA buffer.


<a id="rst-other-i915-perf-internals"></a>

### Other i915 Perf Internals

This section simply includes all other currently documented i915 perf internals, in no particular order, but may include some more minor utilities or platform specific details than found in the more high-level sections.


#### <a id="c-struct-perf_open_properties"></a>`struct perf_open_properties`

for validated properties given to open a stream

**Definition**

```c
struct perf_open_properties {
    u32 sample_flags;
    u64 single_context:1;
    u64 hold_preemption:1;
    u64 ctx_handle;
    int metrics_set;
    int oa_format;
    bool oa_periodic;
    int oa_period_exponent;
    struct intel_engine_cs *engine;
    bool has_sseu;
    struct intel_sseu sseu;
    u64 poll_oa_period;
};
```

**Members**

- `sample_flags`: `DRM_I915_PERF_PROP_SAMPLE_*` properties are tracked as flags
- `single_context`: Whether a single or all gpu contexts should be monitored
- `hold_preemption`: Whether the preemption is disabled for the filtered
  context
- `ctx_handle`: A gem ctx handle for use with **single_context**
- `metrics_set`: An ID for an OA unit metric set advertised via sysfs
- `oa_format`: An OA unit HW report format
- `oa_periodic`: Whether to enable periodic OA unit sampling
- `oa_period_exponent`: The OA unit sampling period is derived from this
- `engine`: The engine (typically rcs0) being monitored by the OA unit
- `has_sseu`: Whether **sseu** was specified by userspace
- `sseu`: internal SSEU configuration computed either from the userspace
  specified configuration in the opening parameters or a default value
  (see `get_default_sseu_config()`)
- `poll_oa_period`: The period in nanoseconds at which the CPU will check for OA
  data availability

**Description**

As [`read_properties_unlocked()`](#c-read_properties_unlocked) enumerates and validates the properties given
to open a stream of metrics the configuration is built up in the structure
which starts out zero initialized.

#### <a id="c-oa_buffer_check_unlocked"></a>`oa_buffer_check_unlocked()`

```c
bool oa_buffer_check_unlocked(struct i915_perf_stream *stream)
```

check for data and update tail ptr state

**Parameters**

- `struct i915_perf_stream *stream`: i915 stream instance

**Description**

This is either called via fops (for blocking reads in user ctx) or the poll
check hrtimer (atomic ctx) to check the OA buffer tail pointer and check
if there is data available for userspace to read.

This function is central to providing a workaround for the OA unit tail
pointer having a race with respect to what data is visible to the CPU.
It is responsible for reading tail pointers from the hardware and giving
the pointers time to 'age' before they are made available for reading.
(See description of OA_TAIL_MARGIN_NSEC above for further details.)

Besides returning true when there is data available to `read()` this function
also updates the tail in the oa_buffer object.

**Note**

It's safe to read OA config state here unlocked, assuming that this is
only called while the stream is enabled, while the global OA configuration
can't be modified.

**Return**

`true` if the OA buffer contains data, else `false`

#### <a id="c-append_oa_status"></a>`append_oa_status()`

```c
int append_oa_status(struct i915_perf_stream *stream, char __user *buf, size_t count, size_t *offset, enum drm_i915_perf_record_type type)
```

Appends a status record to a userspace `read()` buffer.

**Parameters**

- `struct i915_perf_stream *stream`: An i915-perf stream opened for OA metrics
- `char __user *buf`: destination buffer given by userspace
- `size_t count`: the number of bytes userspace wants to read
- `size_t *offset`: (inout): the current position for writing into **buf**
- `enum drm_i915_perf_record_type type`: The kind of status to report to userspace

**Description**

Writes a status record (such as `DRM_I915_PERF_RECORD_OA_REPORT_LOST`)
into the userspace `read()` buffer.

The **buf** **offset** will only be updated on success.

**Return**

0 on success, negative error code on failure.

#### <a id="c-append_oa_sample"></a>`append_oa_sample()`

```c
int append_oa_sample(struct i915_perf_stream *stream, char __user *buf, size_t count, size_t *offset, const u8 *report)
```

Copies single OA report into userspace `read()` buffer.

**Parameters**

- `struct i915_perf_stream *stream`: An i915-perf stream opened for OA metrics
- `char __user *buf`: destination buffer given by userspace
- `size_t count`: the number of bytes userspace wants to read
- `size_t *offset`: (inout): the current position for writing into **buf**
- `const u8 *report`: A single OA report to (optionally) include as part of the sample

**Description**

The contents of a sample are configured through `DRM_I915_PERF_PROP_SAMPLE_*`
properties when opening a stream, tracked as `stream->sample_flags`. This
function copies the requested components of a single sample to the given
`read()` **buf**.

The **buf** **offset** will only be updated on success.

**Return**

0 on success, negative error code on failure.

#### <a id="c-gen8_append_oa_reports"></a>`gen8_append_oa_reports()`

```c
int gen8_append_oa_reports(struct i915_perf_stream *stream, char __user *buf, size_t count, size_t *offset)
```

Copies all buffered OA reports into userspace `read()` buffer.

**Parameters**

- `struct i915_perf_stream *stream`: An i915-perf stream opened for OA metrics
- `char __user *buf`: destination buffer given by userspace
- `size_t count`: the number of bytes userspace wants to read
- `size_t *offset`: (inout): the current position for writing into **buf**

**Description**

Notably any error condition resulting in a short read (-`ENOSPC` or
-`EFAULT`) will be returned even though one or more records may
have been successfully copied. In this case it's up to the caller
to decide if the error should be squashed before returning to
userspace.

**Note**

reports are consumed from the head, and appended to the
tail, so the tail chases the head?... If you think that's mad
and back-to-front you're not alone, but this follows the
Gen PRM naming convention.

**Return**

0 on success, negative error code on failure.

#### <a id="c-gen8_oa_read"></a>`gen8_oa_read()`

```c
int gen8_oa_read(struct i915_perf_stream *stream, char __user *buf, size_t count, size_t *offset)
```

copy status records then buffered OA reports

**Parameters**

- `struct i915_perf_stream *stream`: An i915-perf stream opened for OA metrics
- `char __user *buf`: destination buffer given by userspace
- `size_t count`: the number of bytes userspace wants to read
- `size_t *offset`: (inout): the current position for writing into **buf**

**Description**

Checks OA unit status registers and if necessary appends corresponding
status records for userspace (such as for a buffer full condition) and then
initiate appending any buffered OA reports.

Updates **offset** according to the number of bytes successfully copied into
the userspace buffer.

NB: some data may be successfully copied to the userspace buffer
even if an error is returned, and this is reflected in the
updated **offset**.

**Return**

zero on success or a negative error code

#### <a id="c-gen7_append_oa_reports"></a>`gen7_append_oa_reports()`

```c
int gen7_append_oa_reports(struct i915_perf_stream *stream, char __user *buf, size_t count, size_t *offset)
```

Copies all buffered OA reports into userspace `read()` buffer.

**Parameters**

- `struct i915_perf_stream *stream`: An i915-perf stream opened for OA metrics
- `char __user *buf`: destination buffer given by userspace
- `size_t count`: the number of bytes userspace wants to read
- `size_t *offset`: (inout): the current position for writing into **buf**

**Description**

Notably any error condition resulting in a short read (-`ENOSPC` or
-`EFAULT`) will be returned even though one or more records may
have been successfully copied. In this case it's up to the caller
to decide if the error should be squashed before returning to
userspace.

**Note**

reports are consumed from the head, and appended to the
tail, so the tail chases the head?... If you think that's mad
and back-to-front you're not alone, but this follows the
Gen PRM naming convention.

**Return**

0 on success, negative error code on failure.

#### <a id="c-gen7_oa_read"></a>`gen7_oa_read()`

```c
int gen7_oa_read(struct i915_perf_stream *stream, char __user *buf, size_t count, size_t *offset)
```

copy status records then buffered OA reports

**Parameters**

- `struct i915_perf_stream *stream`: An i915-perf stream opened for OA metrics
- `char __user *buf`: destination buffer given by userspace
- `size_t count`: the number of bytes userspace wants to read
- `size_t *offset`: (inout): the current position for writing into **buf**

**Description**

Checks Gen 7 specific OA unit status registers and if necessary appends
corresponding status records for userspace (such as for a buffer full
condition) and then initiate appending any buffered OA reports.

Updates **offset** according to the number of bytes successfully copied into
the userspace buffer.

**Return**

zero on success or a negative error code

#### <a id="c-oa_get_render_ctx_id"></a>`oa_get_render_ctx_id()`

```c
int oa_get_render_ctx_id(struct i915_perf_stream *stream)
```

determine and hold ctx hw id

**Parameters**

- `struct i915_perf_stream *stream`: An i915-perf stream opened for OA metrics

**Description**

Determine the render context hw id, and ensure it remains fixed for the
lifetime of the stream. This ensures that we don't have to worry about
updating the context ID in OACONTROL on the fly.

**Return**

zero on success or a negative error code

#### <a id="c-oa_put_render_ctx_id"></a>`oa_put_render_ctx_id()`

```c
void oa_put_render_ctx_id(struct i915_perf_stream *stream)
```

counterpart to oa_get_render_ctx_id releases hold

**Parameters**

- `struct i915_perf_stream *stream`: An i915-perf stream opened for OA metrics

**Description**

In case anything needed doing to ensure the context HW ID would remain valid
for the lifetime of the stream, then that can be undone here.

#### <a id="c-i915_perf_ioctl_locked"></a>`i915_perf_ioctl_locked()`

```c
long i915_perf_ioctl_locked(struct i915_perf_stream *stream, unsigned int cmd, unsigned long arg)
```

support `ioctl()` usage with i915 perf stream FDs

**Parameters**

- `struct i915_perf_stream *stream`: An i915 perf stream
- `unsigned int cmd`: the ioctl request
- `unsigned long arg`: the ioctl data

**Return**

zero on success or a negative error code. Returns -EINVAL for
an unknown ioctl request.

#### <a id="c-i915_perf_ioctl_version"></a>`i915_perf_ioctl_version()`

```c
int i915_perf_ioctl_version(struct drm_i915_private *i915)
```

Version of the i915-perf subsystem

**Parameters**

- `struct drm_i915_private *i915`: The i915 device

**Description**

This version number is used by userspace to detect available features.


<a id="rst-style"></a>

## Style

The drm/i915 driver codebase has some style rules in addition to (and, in some cases, deviating from) the kernel coding style.

<a id="rst-register-macro-definition-style"></a>

### Register macro definition style

The style guide for `i915_reg.h`.


Follow the style described here for new macros, and while changing existing
macros. Do **not** mass change existing definitions just to update the style.

**File Layout**

Keep helper macros near the top. For example, `_PIPE()` and friends.

Prefix macros that generally should not be used outside of this file with
underscore '_'. For example, `_PIPE()` and friends, single instances of
registers that are defined solely for the use by function-like macros.

Avoid using the underscore prefixed macros outside of this file. There are
exceptions, but keep them to a minimum.

There are two basic types of register definitions: Single registers and
register groups. Register groups are registers which have two or more
instances, for example one per pipe, port, transcoder, etc. Register groups
should be defined using function-like macros.

For single registers, define the register offset first, followed by register
contents.

For register groups, define the register instance offsets first, prefixed
with underscore, followed by a function-like macro choosing the right
instance based on the parameter, followed by register contents.

Define the register contents (i.e. bit and bit field macros) from most
significant to least significant bit. Indent the register content macros
using two extra spaces between `#define` and the macro name.

Define bit fields using `REG_GENMASK(h, l)`. Define bit field contents
using `REG_FIELD_PREP(mask, value)`. This will define the values already
shifted in place, so they can be directly OR'd together. For convenience,
function-like macros may be used to define bit fields, but do note that the
macros may be needed to read as well as write the register contents.

Define bits using `REG_BIT(N)`. Do **not** add `_BIT` suffix to the name.

Group the register and its contents together without blank lines, separate
from other registers and their contents with one blank line.

Indent macro values from macro names using TABs. Align values vertically. Use
braces in macro values as needed to avoid unintended precedence after macro
substitution. Use spaces in macro values according to kernel coding
style. Use lower case in hexadecimal values.

**Naming**

Try to name registers according to the specs. If the register name changes in
the specs from platform to another, stick to the original name.

Try to reuse existing register macro definitions. Only add new macros for
new register offsets, or when the register contents have changed enough to
warrant a full redefinition.

When a register macro changes for a new platform, prefix the new macro using
the platform acronym or generation. For example, `SKL_` or `GEN8_`. The
prefix signifies the start platform/generation using the register.

When a bit (field) macro changes or gets added for a new platform, while
retaining the existing register macro, add a platform acronym or generation
suffix to the name. For example, `_SKL` or `_GEN8`.

**Examples**

(Note that the values in the example are indented using spaces instead of
TABs to avoid misalignment in generated documentation. Use TABs in the
definitions.):

```text
#define _FOO_A                      0xf000
#define _FOO_B                      0xf001
#define FOO(pipe)                   _MMIO_PIPE(pipe, _FOO_A, _FOO_B)
#define   FOO_ENABLE                REG_BIT(31)
#define   FOO_MODE_MASK             REG_GENMASK(19, 16)
#define   FOO_MODE_BAR              REG_FIELD_PREP(FOO_MODE_MASK, 0)
#define   FOO_MODE_BAZ              REG_FIELD_PREP(FOO_MODE_MASK, 1)
#define   FOO_MODE_QUX_SNB          REG_FIELD_PREP(FOO_MODE_MASK, 2)

#define BAR                         _MMIO(0xb000)
#define GEN8_BAR                    _MMIO(0xb888)
```


<a id="rst-i915-drm-client-usage-stats-implementation"></a>
<a id="rst-i915-usage-stats"></a>

## i915 DRM client usage stats implementation

The drm/i915 driver implements the DRM client usage stats specification as documented in [DRM client usage stats](</kernel/hardware/gpu/drm-usage-stats.md#rst-drm-client-usage-stats>).

Example of the output showing the implemented key value pairs and entirety of the currently possible format options:



```text
pos:    0
flags:  0100002
mnt_id: 21
drm-driver: i915
drm-pdev:   0000:00:02.0
drm-client-id:      7
drm-engine-render:  9288864723 ns
drm-engine-copy:    2035071108 ns
drm-engine-video:   0 ns
drm-engine-capacity-video:   2
drm-engine-video-enhance:   0 ns
```

Possible `drm-engine-` key names are: `render`, `copy`, `video` and `video-enhance`.

---

# Misc DRM driver uAPI- and feature implementation guidelines

_Peios Kernel / Hardware and drivers / Graphics_

> Reference for Misc DRM driver uAPI- and feature implementation guidelines.

<a id="rst-misc-drm-driver-uapi-and-feature-implementation-guidelines"></a>

<!-- SPDX-License-Identifier: (GPL-2.0+ OR MIT) -->

- [Asynchronous VM_BIND](</kernel/hardware/gpu/drm-vm-bind-async.md>)
- [VM_BIND locking](</kernel/hardware/gpu/drm-vm-bind-locking.md>)

---

# Introduction

_Peios Kernel / Hardware and drivers / Graphics_

> The Linux DRM layer contains code intended to support the needs of complex graphics devices, usually containing programmable pipelines well suited to 3D graphics acceleration. Graphics drivers in the kernel may make use of DRM functions to…

<a id="rst-introduction"></a>

The Linux DRM layer contains code intended to support the needs of complex graphics devices, usually containing programmable pipelines well suited to 3D graphics acceleration. Graphics drivers in the kernel may make use of DRM functions to make tasks like memory management, interrupt handling and DMA easier, and provide a uniform interface to applications.

A note on versions: this guide covers features found in the DRM tree, including the TTM memory manager, output configuration and mode setting, and the new vblank internals, in addition to all the regular features found in current kernels.

\[Insert diagram of typical DRM stack here\]

<a id="rst-style-guidelines"></a>

## Style Guidelines

For consistency this documentation uses American English. Abbreviations are written as all-uppercase, for example: DRM, KMS, IOCTL, CRTC, and so on. To aid in reading, documentations make full use of the markup characters kerneldoc provides: @parameter for function parameters, @member for structure members (within the same structure), &amp;struct structure to reference structures and function() for functions. These all get automatically hyperlinked if kerneldoc for the referenced objects exists. When referencing entries in function vtables (and structure members in general) please use &amp;vtable_name.vfunc. Unfortunately this does not yet yield a direct link to the member, only the structure.

Except in special situations (to separate locked from unlocked variants) locking requirements for functions aren't documented in the kerneldoc. Instead locking should be check at runtime using e.g. `WARN_ON(!mutex_is_locked(...));`. Since it's much easier to ignore documentation than runtime noise this provides more value. And on top of that runtime checks do need to be updated when the locking rules change, increasing the chances that they're correct. Within the documentation the locking rules should be explained in the relevant structures: Either in the comment for the lock explaining what it protects, or data fields need a note about which lock protects them, or both.

Functions which have a non-`void` return value should have a section called "Returns" explaining the expected return values in different cases and their meanings. Currently there's no consensus whether that section name should be all upper-case or not, and whether it should end in a colon or not. Go with the file-local style. Other common section names are "Notes" with information for dangerous or tricky corner cases, and "FIXME" where the interface could be cleaned up.

Also read the [guidelines for the kernel documentation at large](</kernel/development/doc-guide/index.md#rst-doc-guide>).

<a id="rst-documentation-requirements-for-kapi"></a>

### Documentation Requirements for kAPI

All kernel APIs exported to other modules must be documented, including their datastructures and at least a short introductory section explaining the overall concepts. Documentation should be put into the code itself as kerneldoc comments as much as reasonable.

Do not blindly document everything, but document only what's relevant for driver authors: Internal functions of drm.ko and definitely static functions should not have formal kerneldoc comments. Use normal C comments if you feel like a comment is warranted. You may use kerneldoc syntax in the comment, but it shall not start with a /\*\* kerneldoc marker. Similar for data structures, annotate anything entirely private with `/* private: */` comments as per the documentation guide.

<a id="rst-getting-started"></a>

## Getting Started

Developers interested in helping out with the DRM subsystem are very welcome. Often people will resort to sending in patches for various issues reported by checkpatch or sparse. We welcome such contributions.

Anyone looking to kick it up a notch can find a list of janitorial tasks on the [TODO list](</kernel/hardware/gpu/todo.md#rst-todo>).

<a id="rst-contribution-process"></a>

## Contribution Process

Mostly the DRM subsystem works like any other kernel subsystem, see [the main process guidelines and documentation](<https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/Documentation/process/index.rst?id=9021cc14f7d98b4a1d2c932f52c5343d4d0f6b92>) for how things work. Here we just document some of the specialities of the GPU subsystem.

<a id="rst-feature-merge-deadlines"></a>

### Feature Merge Deadlines

All feature work must be in the linux-next tree by the -rc6 release of the current release cycle, otherwise they must be postponed and can't reach the next merge window. All patches must have landed in the drm-next tree by latest -rc7, but if your branch is not in linux-next then this must have happened by -rc6 already.

After that point only bugfixes (like after the upstream merge window has closed with the -rc1 release) are allowed. No new platform enabling or new drivers are allowed.

This means that there's a blackout-period of about one month where feature work can't be merged. The recommended way to deal with that is having a -next tree that's always open, but making sure to not feed it into linux-next during the blackout period. As an example, drm-misc works like that.

<a id="rst-code-of-conduct"></a>

### Code of Conduct

As a freedesktop.org project, dri-devel, and the DRM community, follows the Contributor Covenant, found at: [https://www.freedesktop.org/wiki/CodeOfConduct](<https://www.freedesktop.org/wiki/CodeOfConduct>)

Please conduct yourself in a respectful and civilised manner when interacting with community members on mailing lists, IRC, or bug trackers. The community represents the project as a whole, and abusive or bullying behaviour is not tolerated by the project.

<a id="rst-simple-drm-drivers-to-use-as-examples"></a>

## Simple DRM drivers to use as examples

The DRM subsystem contains a lot of helper functions to ease writing drivers for simple graphic devices. For example, the `drivers/gpu/drm/tiny/` directory has a set of drivers that are simple enough to be implemented in a single source file.

These drivers make use of the `struct drm_simple_display_pipe_funcs`, that hides any complexity of the DRM subsystem and just requires drivers to implement a few functions needed to operate the device. This could be used for devices that just need a display pipeline with one full-screen scanout buffer feeding one output.

The tiny DRM drivers are good examples to understand how DRM drivers should look like. Since are just a few hundreds lines of code, they are quite easy to read.

<a id="rst-external-references"></a>

## External References

Delving into a Linux kernel subsystem for the first time can be an overwhelming experience, one needs to get familiar with all the concepts and learn about the subsystem's internals, among other details.

To shallow the learning curve, this section contains a list of presentations and documents that can be used to learn about DRM/KMS and graphics in general.

There are different reasons why someone might want to get into DRM: porting an existing fbdev driver, write a DRM driver for a new hardware, fixing bugs that could face when working on the graphics user-space stack, etc. For this reason, the learning material covers many aspects of the Linux graphics stack. From an overview of the kernel and user-space stacks to very specific topics.

The list is sorted in reverse chronological order, to keep the most up-to-date material at the top. But all of them contain useful information, and it can be valuable to go through older material to understand the rationale and context in which the changes to the DRM subsystem were made.

<a id="rst-conference-talks"></a>

### Conference talks

- [An Overview of the Linux and Userspace Graphics Stack](<https://www.youtube.com/watch?v=wjAJmqwg47k>)<a id="rst-an-overview-of-the-linux-and-userspace-graphics-stack"></a> - Paul Kocialkowski (2020)

- [Getting pixels on screen on Linux: introduction to Kernel Mode Setting](<https://www.youtube.com/watch?v=haes4_Xnc5Q>)<a id="rst-getting-pixels-on-screen-on-linux-introduction-to-kernel-mode-setting"></a> - Simon Ser (2020)

- [Everything Great about Upstream Graphics](<https://www.youtube.com/watch?v=kVzHOgt6WGE>)<a id="rst-everything-great-about-upstream-graphics"></a> - Simona Vetter (2019)

- [An introduction to the Linux DRM subsystem](<https://www.youtube.com/watch?v=LbDOCJcDRoo>)<a id="rst-an-introduction-to-the-linux-drm-subsystem"></a> - Maxime Ripard (2017)

- [Embrace the Atomic (Display) Age](<https://www.youtube.com/watch?v=LjiB_JeDn2M>)<a id="rst-embrace-the-atomic-display-age"></a> - Simona Vetter (2016)

- [Anatomy of an Atomic KMS Driver](<https://www.youtube.com/watch?v=lihqR9sENpc>)<a id="rst-anatomy-of-an-atomic-kms-driver"></a> - Laurent Pinchart (2015)

- [Atomic Modesetting for Drivers](<https://www.youtube.com/watch?v=kl9suFgbTc8>)<a id="rst-atomic-modesetting-for-drivers"></a> - Simona Vetter (2015)

- [Anatomy of an Embedded KMS Driver](<https://www.youtube.com/watch?v=Ja8fM7rTae4>)<a id="rst-anatomy-of-an-embedded-kms-driver"></a> - Laurent Pinchart (2013)

<a id="rst-slides-and-articles"></a>

### Slides and articles

- [The Linux graphics stack in a nutshell, part 1](<https://lwn.net/Articles/955376/>)<a id="rst-the-linux-graphics-stack-in-a-nutshell-part-1"></a> - Thomas Zimmermann (2023)

- [The Linux graphics stack in a nutshell, part 2](<https://lwn.net/Articles/955708/>)<a id="rst-the-linux-graphics-stack-in-a-nutshell-part-2"></a> - Thomas Zimmermann (2023)

- [Understanding the Linux Graphics Stack](<https://bootlin.com/doc/training/graphics/graphics-slides.pdf>)<a id="rst-understanding-the-linux-graphics-stack"></a> - Bootlin (2022)

- [DRM KMS overview](<https://wiki.st.com/stm32mpu/wiki/DRM_KMS_overview>)<a id="rst-drm-kms-overview"></a> - STMicroelectronics (2021)

- [Linux graphic stack](<https://studiopixl.com/2017-05-13/linux-graphic-stack-an-overview>)<a id="rst-linux-graphic-stack"></a> - Nathan Gauër (2017)

- [Atomic mode setting design overview, part 1](<https://lwn.net/Articles/653071/>)<a id="rst-atomic-mode-setting-design-overview-part-1"></a> - Simona Vetter (2015)

- [Atomic mode setting design overview, part 2](<https://lwn.net/Articles/653466/>)<a id="rst-atomic-mode-setting-design-overview-part-2"></a> - Simona Vetter (2015)

- [The DRM/KMS subsystem from a newbie’s point of view](<https://bootlin.com/pub/conferences/2014/elce/brezillon-drm-kms/brezillon-drm-kms.pdf>)<a id="rst-the-drm-kms-subsystem-from-a-newbies-point-of-view"></a> - Boris Brezillon (2014)

- [A brief introduction to the Linux graphics stack](<https://blogs.igalia.com/itoral/2014/07/29/a-brief-introduction-to-the-linux-graphics-stack/>)<a id="rst-a-brief-introduction-to-the-linux-graphics-stack"></a> - Iago Toral (2014)

- [The Linux Graphics Stack](<https://blog.mecheye.net/2012/06/the-linux-graphics-stack/>)<a id="rst-the-linux-graphics-stack"></a> - Jasper St. Pierre (2012)

---

# drm/komeda Arm display driver

_Peios Kernel / Hardware and drivers / Graphics_

> The drm/komeda driver supports the Arm display processor D71 and later products, this document gives a brief overview of driver design: how it works and why design it like that.

<a id="rst-drm-komeda-arm-display-driver"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

The drm/komeda driver supports the Arm display processor D71 and later products, this document gives a brief overview of driver design: how it works and why design it like that.

<a id="rst-overview-of-d71-like-display-ips"></a>

## Overview of D71 like display IPs

From D71, Arm display IP begins to adopt a flexible and modularized architecture. A display pipeline is made up of multiple individual and functional pipeline stages called components, and every component has some specific capabilities that can give the flowed pipeline pixel data a particular processing.

Typical D71 components:

<a id="rst-layer"></a>

### Layer

Layer is the first pipeline stage, which prepares the pixel data for the next stage. It fetches the pixel from memory, decodes it if it's AFBC, rotates the source image, unpacks or converts YUV pixels to the device internal RGB pixels, then adjusts the color_space of pixels if needed.

<a id="rst-scaler"></a>

### Scaler

As its name suggests, scaler takes responsibility for scaling, and D71 also supports image enhancements by scaler. The usage of scaler is very flexible and can be connected to layer output for layer scaling, or connected to compositor and scale the whole display frame and then feed the output data into wb_layer which will then write it into memory.

<a id="rst-compositor-compiz"></a>

### Compositor (compiz)

Compositor blends multiple layers or pixel data flows into one single display frame. its output frame can be fed into post image processor for showing it on the monitor or fed into wb_layer and written to memory at the same time. user can also insert a scaler between compositor and wb_layer to down scale the display frame first and then write to memory.

<a id="rst-writeback-layer-wb-layer"></a>

### Writeback Layer (wb_layer)

Writeback layer does the opposite things of Layer, which connects to compiz and writes the composition result to memory.

<a id="rst-post-image-processor-improc"></a>

### Post image processor (improc)

Post image processor adjusts frame data like gamma and color space to fit the requirements of the monitor.

<a id="rst-timing-controller-timing-ctrlr"></a>

### Timing controller (timing_ctrlr)

Final stage of display pipeline, Timing controller is not for the pixel handling, but only for controlling the display timing.

<a id="rst-merger"></a>

### Merger

D71 scaler mostly only has the half horizontal input/output capabilities compared with Layer, like if Layer supports 4K input size, the scaler only can support 2K input/output in the same time. To achieve the ful frame scaling, D71 introduces Layer Split, which splits the whole image to two half parts and feeds them to two Layers A and B, and does the scaling independently. After scaling the result need to be fed to merger to merge two part images together, and then output merged result to compiz.

<a id="rst-splitter"></a>

### Splitter

Similar to Layer Split, but Splitter is used for writeback, which splits the compiz result to two parts and then feed them to two scalers.

<a id="rst-possible-d71-pipeline-usage"></a>

## Possible D71 Pipeline usage

Benefitting from the modularized architecture, D71 pipelines can be easily adjusted to fit different usages. And D71 has two pipelines, which support two types of working mode:

- Dual display mode Two pipelines work independently and separately to drive two display outputs.

- Single display mode Two pipelines work together to drive only one display output.

  On this mode, pipeline_B doesn't work independently, but outputs its composition result into pipeline_A, and its pixel timing also derived from pipeline_A.timing_ctrlr. The pipeline_B works just like a "slave" of pipeline_A(master)

<a id="rst-single-pipeline-data-flow"></a>

### Single pipeline data flow

```mermaid
flowchart LR
  n0(["Memory"])
  n1(["Monitor"])
  subgraph g0["#160;"]
    n2["Scaler-0"]
    n3["Scaler-1"]
    n4["Scaler-0/1"]
    n5["Layer-0"]
    n6["Layer-1"]
    n7["Layer-2"]
    n8["Layer-3"]
    n9["Compiz"]
    n10["Wb_layer"]
    n11["Improc"]
    n12["Timing Controller"]
  end
  n5 --> n2
  n6 --> n2
  n7 --> n3
  n8 --> n3
  n5 --> n9
  n6 --> n9
  n7 --> n9
  n8 --> n9
  n2 --> n9
  n3 --> n9
  n9 --> n4
  n4 --> n10
  n9 --> n11
  n11 --> n12
  n10 --> n0
  n12 --> n1
  style n2 stroke-dasharray:6 4
  style n3 stroke-dasharray:6 4
  style n4 stroke-dasharray:6 4
  style g0 stroke-dasharray:6 4
```

Single pipeline data flow

<a id="rst-dual-pipeline-with-slave-enabled"></a>

### Dual pipeline with Slave enabled

```mermaid
flowchart LR
  n0(["Memory"])
  n1(["Monitor"])
  subgraph g0["Slave Pipeline_B"]
    n2["Slave.Scaler-0"]
    n3["Slave.Scaler-1"]
    n4["Slave.Layer-0"]
    n5["Slave.Layer-1"]
    n6["Slave.Layer-2"]
    n7["Slave.Layer-3"]
    n8["Slave.Compiz"]
  end
  subgraph g1["Master Pipeline_A"]
    n9["Scaler-0"]
    n10["Scaler-1"]
    n11["Scaler-0/1"]
    n12["Layer-0"]
    n13["Layer-1"]
    n14["Layer-2"]
    n15["Layer-3"]
    n16["Compiz"]
    n17["Wb_layer"]
    n18["Improc"]
    n19["Timing Controller"]
  end
  n4 --> n2
  n5 --> n2
  n6 --> n3
  n7 --> n3
  n4 --> n8
  n5 --> n8
  n6 --> n8
  n7 --> n8
  n2 --> n8
  n3 --> n8
  n12 --> n9
  n13 --> n9
  n14 --> n10
  n15 --> n10
  n8 --> n16
  n12 --> n16
  n13 --> n16
  n14 --> n16
  n15 --> n16
  n9 --> n16
  n10 --> n16
  n16 --> n11
  n11 --> n17
  n16 --> n18
  n18 --> n19
  n17 --> n0
  n19 --> n1
  style n2 stroke-dasharray:6 4
  style n3 stroke-dasharray:6 4
  style n9 stroke-dasharray:6 4
  style n10 stroke-dasharray:6 4
  style n11 stroke-dasharray:6 4
  style g0 stroke-dasharray:6 4
  style g1 stroke-dasharray:6 4
```

Slave pipeline enabled data flow

<a id="rst-sub-pipelines-for-input-and-output"></a>

### Sub-pipelines for input and output

A complete display pipeline can be easily divided into three sub-pipelines according to the in/out usage.

<a id="rst-layer-input-pipeline"></a>

#### Layer(input) pipeline

```mermaid
flowchart LR
  n0["Scaler-n"]
  n1["Layer-n"]
  n2["Compiz"]
  n1 --> n0
  n0 --> n2
  style n0 stroke-dasharray:6 4
```

Layer (input) data flow

```mermaid
flowchart LR
  n0["Layer-0/1"]
  n1["Scaler-0"]
  n2["Merger"]
  n3["Layer-2/3"]
  n4["Scaler-1"]
  n5["Compiz"]
  n0 --> n1
  n1 --> n2
  n3 --> n4
  n4 --> n2
  n2 --> n5
```

Layer Split pipeline

<a id="rst-writeback-output-pipeline"></a>

#### Writeback(output) pipeline

```mermaid
flowchart LR
  n0["Scaler-n"]
  n1["Compiz"]
  n2["Wb_layer"]
  n1 --> n0
  n0 --> n2
  style n0 stroke-dasharray:6 4
```

Writeback(output) data flow

```mermaid
flowchart LR
  n0["Compiz"]
  n1["Splitter"]
  n2["Scaler-0"]
  n3["Merger"]
  n4["Scaler-1"]
  n5["Wb_layer"]
  n0 --> n1
  n1 --> n2
  n2 --> n3
  n1 --> n4
  n4 --> n3
  n3 --> n5
```

Writeback(output) Split data flow

<a id="rst-display-output-pipeline"></a>

#### Display output pipeline

```mermaid
flowchart LR
  n0["Compiz"]
  n1["Improc"]
  n2["Timing Controller"]
  n0 --> n1
  n1 --> n2
```

display output data flow

In the following section we'll see these three sub-pipelines will be handled by KMS-plane/wb_conn/crtc respectively.

<a id="rst-komeda-resource-abstraction"></a>

## Komeda Resource abstraction

<a id="rst-struct-komeda-pipeline-component"></a>

### struct komeda_pipeline/component

To fully utilize and easily access/configure the HW, the driver side also uses a similar architecture: Pipeline/Component to describe the HW features and capabilities, and a specific component includes two parts:

- Data flow controlling.

- Specific component capabilities and features.

So the driver defines a common header struct komeda_component to describe the data flow control and all specific components are a subclass of this base structure.


#### <a id="c-struct-komeda_component"></a>`struct komeda_component`

**Definition**

```c
struct komeda_component {
    struct drm_private_obj obj;
    struct komeda_pipeline *pipeline;
    char name[32];
    u32 __iomem *reg;
    u32 id;
    u32 hw_id;
    u8 max_active_inputs;
    u8 max_active_outputs;
    u32 supported_inputs;
    u32 supported_outputs;
    const struct komeda_component_funcs *funcs;
};
```

**Members**

- `obj`: treat component as private obj
- `pipeline`: the komeda pipeline this component belongs to
- `name`: component name
- `reg`: component register base,
  which is initialized by chip and used by chip only
- `id`: component id
- `hw_id`: component hw id,
  which is initialized by chip and used by chip only
- `max_active_inputs`:

  **max_active_outputs**:

  maximum number of inputs/outputs that can be active at the same time
  Note:
  the number isn't the bit number of **supported_inputs** or
  **supported_outputs**, but may be less than it, since component may not
  support enabling all **supported_inputs**/outputs at the same time.
- `max_active_outputs`: maximum number of outputs
- `supported_inputs`:

  **supported_outputs**:

  bitmask of BIT(component->id) for the supported inputs/outputs,
  describes the possibilities of how a component is linked into a
  pipeline.
- `supported_outputs`: bitmask of supported output componenet ids
- `funcs`: chip functions to access HW

**Description**

struct komeda_component describe the data flow capabilities for how to link a
component into the display pipeline.
all specified components are subclass of this structure.

#### <a id="c-struct-komeda_component_output"></a>`struct komeda_component_output`

**Definition**

```c
struct komeda_component_output {
    struct komeda_component *component;
    u8 output_port;
};
```

**Members**

- `component`: indicate which component the data comes from
- `output_port`: the output port of the [`komeda_component_output.component`](#c-struct-komeda_component_output)

**Description**

a component has multiple outputs, if want to know where the data
comes from, only know the component is not enough, we still need to know
its output port

#### <a id="c-struct-komeda_component_state"></a>`struct komeda_component_state`

**Definition**

```c
struct komeda_component_state {
    struct drm_private_state obj;
    struct komeda_component *component;
    union {
        struct drm_crtc *crtc;
        struct drm_plane *plane;
        struct drm_connector *wb_conn;
        void *binding_user;
    };
    u16 active_inputs;
    u16 changed_active_inputs;
    u16 affected_inputs;
    struct komeda_component_output inputs[KOMEDA_COMPONENT_N_INPUTS];
};
```

**Members**

- `obj`: tracking component_state by drm_atomic_state
- `component`: backpointer to the component
- `{unnamed_union}`: anonymous
- `crtc`: backpointer for user crtc
- `plane`: backpointer for user plane
- `wb_conn`: backpointer for user wb_connector
- `binding_user`: currently bound user, the user can be **crtc**, **plane** or **wb_conn**,
  which is valid decided by **component** and **inputs**

  - Layer: its user always is plane.
  - compiz/improc/timing_ctrlr: the user is crtc.
  - wb_layer: wb_conn;
  - scaler: plane when input is layer, wb_conn if input is compiz.
- `active_inputs`: active_inputs is bitmask of **inputs** index

  - active_inputs = changed_active_inputs | unchanged_active_inputs
  - affected_inputs = old->active_inputs | new->active_inputs;
  - disabling_inputs = affected_inputs ^ active_inputs;
  - changed_inputs = disabling_inputs | changed_active_inputs;

  NOTE:
  changed_inputs doesn't include all active_input but only
  **changed_active_inputs**, and this bitmask can be used in chip
  level for dirty update.
- `changed_active_inputs`: bitmask of the changed **active_inputs**
- `affected_inputs`: bitmask for affected **inputs**
- `inputs`: the specific inputs\[i\] only valid on BIT(i) has been set in
  **active_inputs**, if not the inputs\[i\] is undefined.

**Description**

component_state is the data flow configuration of the component, and it's
the superclass of all specific component_state like **komeda_layer_state**,
**komeda_scaler_state**

#### <a id="c-struct-komeda_pipeline"></a>`struct komeda_pipeline`

**Definition**

```c
struct komeda_pipeline {
    struct drm_private_obj obj;
    struct komeda_dev *mdev;
    struct clk *pxlclk;
    int id;
    u32 avail_comps;
    u32 standalone_disabled_comps;
    int n_layers;
    struct komeda_layer *layers[KOMEDA_PIPELINE_MAX_LAYERS];
    int n_scalers;
    struct komeda_scaler *scalers[KOMEDA_PIPELINE_MAX_SCALERS];
    struct komeda_compiz *compiz;
    struct komeda_splitter *splitter;
    struct komeda_merger *merger;
    struct komeda_layer  *wb_layer;
    struct komeda_improc *improc;
    struct komeda_timing_ctrlr *ctrlr;
    const struct komeda_pipeline_funcs *funcs;
    struct device_node *of_node;
    struct device_node *of_output_port;
    struct device_node *of_output_links[2];
    bool dual_link;
};
```

**Members**

- `obj`: link pipeline as private obj of drm_atomic_state
- `mdev`: the parent komeda_dev
- `pxlclk`: pixel clock
- `id`: pipeline id
- `avail_comps`: available components mask of pipeline
- `standalone_disabled_comps`: When disable the pipeline, some components can not be disabled
  together with others, but need a sparated and standalone disable.
  The standalone_disabled_comps are the components which need to be
  disabled standalone, and this concept also introduce concept of
  two phase.
  phase 1: for disabling the common components.
  phase 2: for disabling the standalong_disabled_comps.
- `n_layers`: the number of layer on **layers**
- `layers`: the pipeline layers
- `n_scalers`: the number of scaler on **scalers**
- `scalers`: the pipeline scalers
- `compiz`: compositor
- `splitter`: for split the compiz output to two half data flows
- `merger`: merger
- `wb_layer`: writeback layer
- `improc`: post image processor
- `ctrlr`: timing controller
- `funcs`: chip private pipeline functions
- `of_node`: pipeline dt node
- `of_output_port`: pipeline output port
- `of_output_links`: output connector device nodes
- `dual_link`: true if of_output_links\[0\] and \[1\] are both valid

**Description**

Represent a complete display pipeline and hold all functional components.

#### <a id="c-struct-komeda_pipeline_state"></a>`struct komeda_pipeline_state`

**Definition**

```c
struct komeda_pipeline_state {
    struct drm_private_state obj;
    struct komeda_pipeline *pipe;
    struct drm_crtc *crtc;
    u32 active_comps;
};
```

**Members**

- `obj`: tracking pipeline_state by drm_atomic_state
- `pipe`: backpointer to the pipeline
- `crtc`: currently bound crtc
- `active_comps`: bitmask - BIT(component->id) of active components

**NOTE**

Unlike the pipeline, pipeline_state doesn’t gather any component_state
into it. It because all component will be managed by drm_atomic_state.


<a id="rst-resource-discovery-and-initialization"></a>

## Resource discovery and initialization

Pipeline and component are used to describe how to handle the pixel data. We still need a @struct komeda_dev to describe the whole view of the device, and the control-abilites of device.

We have &amp;komeda_dev, &amp;komeda_pipeline, &amp;komeda_component. Now fill devices with pipelines. Since komeda is not for D71 only but also intended for later products, of course we’d better share as much as possible between different products. To achieve this, split the komeda device into two layers: CORE and CHIP.

- CORE: for common features and capabilities handling.

- CHIP: for register programming and HW specific feature (limitation) handling.

CORE can access CHIP by three chip function structures:

- struct komeda_dev_funcs

- struct komeda_pipeline_funcs

- struct komeda_component_funcs


#### <a id="c-struct-komeda_dev_funcs"></a>`struct komeda_dev_funcs`

**Definition**

```c
struct komeda_dev_funcs {
    void (*init_format_table)(struct komeda_dev *mdev);
    int (*enum_resources)(struct komeda_dev *mdev);
    void (*cleanup)(struct komeda_dev *mdev);
    int (*connect_iommu)(struct komeda_dev *mdev);
    int (*disconnect_iommu)(struct komeda_dev *mdev);
    irqreturn_t (*irq_handler)(struct komeda_dev *mdev, struct komeda_events *events);
    int (*enable_irq)(struct komeda_dev *mdev);
    int (*disable_irq)(struct komeda_dev *mdev);
    void (*on_off_vblank)(struct komeda_dev *mdev, int master_pipe, bool on);
    void (*dump_register)(struct komeda_dev *mdev, struct seq_file *seq);
    int (*change_opmode)(struct komeda_dev *mdev, int new_mode);
    void (*flush)(struct komeda_dev *mdev, int master_pipe, u32 active_pipes);
};
```

**Members**

- `init_format_table`: initialize [`komeda_dev->format_table`](#c-struct-komeda_dev), this function should be called
  before the `enum _resource`
- `enum_resources`: for CHIP to report or add pipeline and component resources to CORE
- `cleanup`: call to chip to cleanup komeda_dev->chip data
- `connect_iommu`: Optional, connect to external iommu
- `disconnect_iommu`: Optional, disconnect to external iommu
- `irq_handler`: for CORE to get the HW event from the CHIP when interrupt happened.
- `enable_irq`: enable irq
- `disable_irq`: disable irq
- `on_off_vblank`: notify HW to on/off vblank
- `dump_register`: Optional, dump registers to seq_file
- `change_opmode`: Notify HW to switch to a new display operation mode.
- `flush`: Notify the HW to flush or kickoff the update

**Description**

Supplied by chip level and returned by the chip entry function xxx_identify,

#### <a id="c-struct-komeda_dev"></a>`struct komeda_dev`

**Definition**

```c
struct komeda_dev {
        struct device *dev;
        u32 __iomem   *reg_base;
        struct komeda_chip_info chip;
        struct komeda_format_caps_table fmt_tbl;
        struct clk *aclk;
        int irq;
        struct mutex lock;
        u32 dpmode;
        int n_pipelines;
        struct komeda_pipeline *pipelines[KOMEDA_MAX_PIPELINES];
        const struct komeda_dev_funcs *funcs;
        void *chip_data;
        struct iommu_domain *iommu;
        struct dentry *debugfs_root;
        u16 err_verbosity;
    #define KOMEDA_DEV_PRINT_ERR_EVENTS BIT(0);
    #define KOMEDA_DEV_PRINT_WARN_EVENTS BIT(1);
    #define KOMEDA_DEV_PRINT_INFO_EVENTS BIT(2);
    #define KOMEDA_DEV_PRINT_DUMP_STATE_ON_EVENT BIT(8);
    #define KOMEDA_DEV_PRINT_DISABLE_RATELIMIT BIT(12);
};
```

**Members**

- `dev`: the base device structure
- `reg_base`: the base address of komeda io space
- `chip`: the basic chip information
- `fmt_tbl`: initialized by [`komeda_dev_funcs->init_format_table`](#c-struct-komeda_dev_funcs)
- `aclk`: HW main engine clk
- `irq`: irq number
- `lock`: used to protect dpmode
- `dpmode`: current display mode
- `n_pipelines`: the number of pipe in **pipelines**
- `pipelines`: the komeda pipelines
- `funcs`: chip funcs to access to HW
- `chip_data`: chip data will be added by [`komeda_dev_funcs.enum_resources()`](#c-struct-komeda_dev_funcs) and
  destroyed by [`komeda_dev_funcs.cleanup()`](#c-struct-komeda_dev_funcs)
- `iommu`: iommu domain
- `debugfs_root`: root directory of komeda debugfs
- `err_verbosity`: bitmask for how much extra info to print on error

  See KOMEDA_DEV_* macros for details. Low byte contains the debug
  level categories, the high byte contains extra debug options.

**Description**

Pipeline and component are used to describe how to handle the pixel data.
komeda_device is for describing the whole view of the device, and the
control-abilites of device.


<a id="rst-format-handling"></a>

## Format handling


#### <a id="c-struct-komeda_format_caps"></a>`struct komeda_format_caps`

**Definition**

```c
struct komeda_format_caps {
    u32 hw_id;
    u32 fourcc;
    u32 supported_layer_types;
    u32 supported_rots;
    u32 supported_afbc_layouts;
    u64 supported_afbc_features;
};
```

**Members**

- `hw_id`: hw format id, hw specific value.
- `fourcc`: drm fourcc format.
- `supported_layer_types`: indicate which layer supports this format
- `supported_rots`: allowed rotations for this format
- `supported_afbc_layouts`: supported afbc layerout
- `supported_afbc_features`: supported afbc features

**Description**

komeda_format_caps is for describing ARM display specific features and
limitations for a specific format, and format_caps will be linked into
`komeda_framebuffer` like a extension of [`drm_format_info`](/kernel/hardware/gpu/drm-kms.md#c-drm_format_info).

**NOTE**

one fourcc may has two different format_caps items for fourcc and
fourcc+modifier

#### <a id="c-struct-komeda_format_caps_table"></a>`struct komeda_format_caps_table`

format_caps mananger

**Definition**

```c
struct komeda_format_caps_table {
    u32 n_formats;
    const struct komeda_format_caps *format_caps;
    bool (*format_mod_supported)(const struct komeda_format_caps *caps, u32 layer_type, u64 modifier, u32 rot);
};
```

**Members**

- `n_formats`: the size of format_caps list.
- `format_caps`: format_caps list.
- `format_mod_supported`: Optional. Some HW may have special requirements or
  limitations which can not be described by format_caps, this func supply HW
  the ability to do the further HW specific check.



#### <a id="c-struct-komeda_fb"></a>`struct komeda_fb`

Entending drm_framebuffer with komeda attribute

**Definition**

```c
struct komeda_fb {
    struct drm_framebuffer base;
    const struct komeda_format_caps *format_caps;
    bool is_va;
    u32 aligned_w;
    u32 aligned_h;
    u32 afbc_size;
    u32 offset_payload;
};
```

**Members**

- `base`: [`drm_framebuffer`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_framebuffer)
- `format_caps`: extends drm_format_info for komeda specific information
- `is_va`: if smmu is enabled, it will be true
- `aligned_w`: aligned frame buffer width
- `aligned_h`: aligned frame buffer height
- `afbc_size`: minimum size of afbc
- `offset_payload`: start of afbc body buffer


<a id="rst-attach-komeda-dev-to-drm-kms"></a>

## Attach komeda_dev to DRM-KMS

Komeda abstracts resources by pipeline/component, but DRM-KMS uses crtc/plane/connector. One KMS-obj cannot represent only one single component, since the requirements of a single KMS object cannot simply be achieved by a single component, usually that needs multiple components to fit the requirement. Like set mode, gamma, ctm for KMS all target on CRTC-obj, but komeda needs compiz, improc and timing_ctrlr to work together to fit these requirements. And a KMS-Plane may require multiple komeda resources: layer/scaler/compiz.

So, one KMS-Obj represents a sub-pipeline of komeda resources.

- Plane: [Layer(input) pipeline](<#rst-layer-input-pipeline>)

- Wb_connector: [Writeback(output) pipeline](<#rst-writeback-output-pipeline>)

- Crtc: [Display output pipeline](<#rst-display-output-pipeline>)

So, for komeda, we treat KMS crtc/plane/connector as users of pipeline and component, and at any one time a pipeline/component only can be used by one user. And pipeline/component will be treated as private object of DRM-KMS; the state will be managed by drm_atomic_state as well.

<a id="rst-how-to-map-plane-to-layer-input-pipeline"></a>

### How to map plane to Layer(input) pipeline

Komeda has multiple Layer input pipelines, see: -   [Single pipeline data flow](<#rst-single-pipeline-data-flow>) -   [Dual pipeline with Slave enabled](<#rst-dual-pipeline-with-slave-enabled>)

The easiest way is binding a plane to a fixed Layer pipeline, but consider the komeda capabilities:

- Layer Split, See [Layer(input) pipeline](<#rst-layer-input-pipeline>)

  Layer_Split is quite complicated feature, which splits a big image into two parts and handles it by two layers and two scalers individually. But it imports an edge problem or effect in the middle of the image after the split. To avoid such a problem, it needs a complicated Split calculation and some special configurations to the layer and scaler. We'd better hide such HW related complexity to user mode.

- Slave pipeline, See [Dual pipeline with Slave enabled](<#rst-dual-pipeline-with-slave-enabled>)

  Since the compiz component doesn't output alpha value, the slave pipeline only can be used for bottom layers composition. The komeda driver wants to hide this limitation to the user. The way to do this is to pick a suitable Layer according to plane_state-&gt;zpos.

So for komeda, the KMS-plane doesn't represent a fixed komeda layer pipeline, but multiple Layers with same capabilities. Komeda will select one or more Layers to fit the requirement of one KMS-plane.

<a id="rst-make-component-pipeline-to-be-drm-private-obj"></a>

### Make component/pipeline to be drm_private_obj

Add `drm_private_obj` to `komeda_component`, `komeda_pipeline`



```c
struct komeda_component {
    struct drm_private_obj obj;
    ...
}

struct komeda_pipeline {
    struct drm_private_obj obj;
    ...
}
```

<a id="rst-tracking-component-state-pipeline-state-by-drm-atomic-state"></a>

### Tracking component_state/pipeline_state by drm_atomic_state

Add `drm_private_state` and user to `komeda_component_state`, `komeda_pipeline_state`



```c
struct komeda_component_state {
    struct drm_private_state obj;
    void *binding_user;
    ...
}

struct komeda_pipeline_state {
    struct drm_private_state obj;
    struct drm_crtc *crtc;
    ...
}
```

<a id="rst-komeda-component-validation"></a>

### komeda component validation

Komeda has multiple types of components, but the process of validation are similar, usually including the following steps:



```c
int komeda_xxxx_validate(struct komeda_component_xxx xxx_comp,
            struct komeda_component_output *input_dflow,
            struct drm_plane/crtc/connector *user,
            struct drm_plane/crtc/connector_state, *user_state)
{
     setup 1: check if component is needed, like the scaler is optional depending
              on the user_state; if unneeded, just return, and the caller will
              put the data flow into next stage.
     Setup 2: check user_state with component features and capabilities to see
              if requirements can be met; if not, return fail.
     Setup 3: get component_state from drm_atomic_state, and try set to set
              user to component; fail if component has been assigned to another
              user already.
     Setup 3: configure the component_state, like set its input component,
              convert user_state to component specific state.
     Setup 4: adjust the input_dflow and prepare it for the next stage.
}
```

<a id="rst-komeda-kms-abstraction"></a>

### komeda_kms Abstraction


#### <a id="c-struct-komeda_plane"></a>`struct komeda_plane`

komeda instance of drm_plane

**Definition**

```c
struct komeda_plane {
    struct drm_plane base;
    struct komeda_layer *layer;
};
```

**Members**

- `base`: [`drm_plane`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_plane)
- `layer`: represents available layer input pipelines for this plane.

  NOTE:
  the layer is not for a specific Layer, but indicate a group of
  Layers with same capabilities.

#### <a id="c-struct-komeda_plane_state"></a>`struct komeda_plane_state`

**Definition**

```c
struct komeda_plane_state {
    struct drm_plane_state base;
    struct list_head zlist_node;
    u8 layer_split : 1;
};
```

**Members**

- `base`: [`drm_plane_state`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_plane_state)
- `zlist_node`: zorder list node
- `layer_split`: on/off layer_split

**Description**

The plane_state can be split into two data flow (left/right) and handled
by two layers [`komeda_plane.layer`](#c-struct-komeda_plane) and [`komeda_plane.layer`](#c-struct-komeda_plane).right

#### <a id="c-struct-komeda_wb_connector"></a>`struct komeda_wb_connector`

**Definition**

```c
struct komeda_wb_connector {
    struct drm_writeback_connector base;
    struct komeda_layer *wb_layer;
};
```

**Members**

- `base`: [`drm_writeback_connector`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_writeback_connector)
- `wb_layer`: represents associated writeback pipeline of komeda

#### <a id="c-struct-komeda_crtc"></a>`struct komeda_crtc`

**Definition**

```c
struct komeda_crtc {
    struct drm_crtc base;
    struct komeda_pipeline *master;
    struct komeda_pipeline *slave;
    u32 slave_planes;
    struct komeda_wb_connector *wb_conn;
    struct completion *disable_done;
    struct drm_encoder encoder;
};
```

**Members**

- `base`: [`drm_crtc`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_crtc)
- `master`: only master has display output
- `slave`: optional

  Doesn't have its own display output, the handled data flow will
  merge into the master.
- `slave_planes`: komeda slave planes mask
- `wb_conn`: komeda write back connector
- `disable_done`: this flip_done is for tracing the disable
- `encoder`: encoder at the end of the pipeline

#### <a id="c-struct-komeda_crtc_state"></a>`struct komeda_crtc_state`

**Definition**

```c
struct komeda_crtc_state {
    struct drm_crtc_state base;
    u32 affected_pipes;
    u32 active_pipes;
    u64 clock_ratio;
    u32 max_slave_zorder;
};
```

**Members**

- `base`: [`drm_crtc_state`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_crtc_state)
- `affected_pipes`: the affected pipelines in once display instance
- `active_pipes`: the active pipelines in once display instance
- `clock_ratio`: ratio of (aclk \<\< 32)/pxlclk
- `max_slave_zorder`: the maximum of slave zorder


<a id="rst-komde-kms-functions"></a>

### komde_kms Functions


#### <a id="c-komeda_crtc_atomic_check"></a>`komeda_crtc_atomic_check()`

```c
int komeda_crtc_atomic_check(struct drm_crtc *crtc, struct drm_atomic_state *state)
```

build display output data flow

**Parameters**

- `struct drm_crtc *crtc`: DRM crtc
- `struct drm_atomic_state *state`: the crtc state object

**Description**

crtc_atomic_check is the final check stage, so beside build a display data
pipeline according to the crtc_state, but still needs to release or disable
the unclaimed pipeline resources.

**Return**

Zero for success or -errno



#### <a id="c-komeda_plane_atomic_check"></a>`komeda_plane_atomic_check()`

```c
int komeda_plane_atomic_check(struct drm_plane *plane, struct drm_atomic_state *state)
```

build input data flow

**Parameters**

- `struct drm_plane *plane`: DRM plane
- `struct drm_atomic_state *state`: the plane state object

**Return**

Zero for success or -errno


<a id="rst-build-komeda-to-be-a-linux-module-driver"></a>

## Build komeda to be a Linux module driver

Now we have two level devices:

- komeda_dev: describes the real display hardware.

- komeda_kms_dev: attaches or connects komeda_dev to DRM-KMS.

All komeda operations are supplied or operated by komeda_dev or komeda_kms_dev, the module driver is only a simple wrapper to pass the Linux command (probe/remove/pm) into komeda_dev or komeda_kms_dev.

---

# drm/mcde ST-Ericsson MCDE Multi-channel display engine

_Peios Kernel / Hardware and drivers / Graphics_

> Reference for drm/mcde ST-Ericsson MCDE Multi-channel display engine.

<a id="rst-drm-mcde-st-ericsson-mcde-multi-channel-display-engine"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->


The MCDE (short for multi-channel display engine) is a graphics
controller found in the Ux500 chipsets, such as NovaThor U8500.
It was initially conceptualized by ST Microelectronics for the
successor of the Nomadik line, STn8500 but productified in the
ST-Ericsson U8500 where is was used for mass-market deployments
in Android phones from Samsung and Sony Ericsson.

It can do 1080p30 on SDTV CCIR656, DPI-2, DBI-2 or DSI for
panels with or without frame buffering and can convert most
input formats including most variants of RGB and YUV.

The hardware has four display pipes, and the layout is a little
bit like this:

```text
Memory     -> Overlay -> Channel -> FIFO -> 8 formatters -> DSI/DPI
External      0..5       0..3       A,B,    6 x DSI         bridge
source 0..9                         C0,C1   2 x DPI
```

FIFOs A and B are for LCD and HDMI while FIFO CO/C1 are for
panels with embedded buffer.
6 of the formatters are for DSI, 3 pairs for VID/CMD respectively.
2 of the formatters are for DPI.

Behind the formatters are the DSI or DPI ports that route to
the external pins of the chip. As there are 3 DSI ports and one
DPI port, it is possible to configure up to 4 display pipelines
(effectively using channels 0..3) for concurrent use.

In the current DRM/KMS setup, we use one external source, one overlay,
one FIFO and one formatter which we connect to the simple DMA framebuffer
helpers. We then provide a bridge to the DSI port, and on the DSI port
bridge we connect hang a panel bridge or other bridge. This may be subject
to change as we exploit more of the hardware capabilities.

TODO:

- Enabled damaged rectangles using [`drm_plane_enable_fb_damage_clips()`](/kernel/hardware/gpu/drm-kms.md#c-drm_plane_enable_fb_damage_clips)
  so we can selectively just transmit the damaged area to a
  command-only display.
- Enable mixing of more planes, possibly at the cost of moving away
  from using the simple framebuffer pipeline.
- Enable output to bridges such as the AV8100 HDMI encoder from
  the DSI bridge.

---

# drm/meson AmLogic Meson Video Processing Unit

_Peios Kernel / Hardware and drivers / Graphics_

> The Amlogic Meson Display controller is composed of several components that are going to be documented below:

<a id="rst-drm-meson-amlogic-meson-video-processing-unit"></a>


VPU Handles the Global Video Processing, it includes management of the
clocks gates, blocks reset lines and power domains.

What is missing :

- Full reset of entire video processing HW blocks
- Scaling and setup of the VPU clock
- Bus clock gates
- Powering up video processing HW blocks
- Powering Up HDMI controller and PHY


<a id="rst-video-processing-unit"></a>

## Video Processing Unit

The Amlogic Meson Display controller is composed of several components that are going to be documented below:



```text
DMC|---------------VPU (Video Processing Unit)----------------|------HHI------|
   | vd1   _______     _____________    _________________     |               |
D  |-------|      |----|            |   |                |    |   HDMI PLL    |
D  | vd2   | VIU  |    | Video Post |   | Video Encoders |<---|-----VCLK      |
R  |-------|      |----| Processing |   |                |    |               |
   | osd2  |      |    |            |---| Enci ----------|----|-----VDAC------|
R  |-------| CSC  |----| Scalers    |   | Encp ----------|----|----HDMI-TX----|
A  | osd1  |      |    | Blenders   |   | Encl ----------|----|---------------|
M  |-------|______|----|____________|   |________________|    |               |
___|__________________________________________________________|_______________|
```

<a id="rst-video-input-unit"></a>

## Video Input Unit


VIU Handles the Pixel scanout and the basic Colorspace conversions
We handle the following features :

- OSD1 RGB565/RGB888/xRGB8888 scanout
- RGB conversion to x/cb/cr
- Progressive or Interlace buffer scanout
- OSD1 Commit on Vsync
- HDR OSD matrix for GXL/GXM

What is missing :

- BGR888/xBGR8888/BGRx8888/BGRx8888 modes
- YUV4:2:2 Y0CbY1Cr scanout
- Conversion to YUV 4:4:4 from 4:2:2 input
- Colorkey Alpha matching
- Big endian scanout
- X/Y reverse scanout
- Global alpha setup
- OSD2 support, would need interlace switching on vsync
- OSD1 full scaling to support TV overscan


<a id="rst-video-post-processing"></a>

## Video Post Processing


VPP Handles all the Post Processing after the Scanout from the VIU
We handle the following post processings :

- Postblend, Blends the OSD1 only
  We exclude OSD2, VS1, VS1 and Preblend output
- Vertical OSD Scaler for OSD1 only, we disable vertical scaler and
  use it only for interlace scanout
- Intermediate FIFO with default Amlogic values

What is missing :

- Preblend for video overlay pre-scaling
- OSD2 support for cursor framebuffer
- Video pre-scaling before postblend
- Full Vertical/Horizontal OSD scaling to support TV overscan
- HDR conversion


<a id="rst-video-encoder"></a>

## Video Encoder


VENC Handle the pixels encoding to the output formats.
We handle the following encodings :

- CVBS Encoding via the ENCI encoder and VDAC digital to analog converter
- TMDS/HDMI Encoding via ENCI_DIV and ENCP
- Setup of more clock rates for HDMI modes

What is missing :

- LCD Panel encoding via ENCL
- TV Panel encoding via ENCT

VENC paths :

```text
       _____   _____   ____________________
vd1---|     |-|     | | VENC     /---------|----VDAC
vd2---| VIU |-| VPP |-|-----ENCI/-ENCI_DVI-|-|
osd1--|     |-|     | | \                  | X--HDMI-TX
osd2--|_____|-|_____| |  |\-ENCP--ENCP_DVI-|-|
                      |  |                 |
                      |  \--ENCL-----------|----LVDS
                      |____________________|
```

The ENCI is designed for PAl or NTSC encoding and can go through the VDAC
directly for CVBS encoding or through the ENCI_DVI encoder for HDMI.
The ENCP is designed for Progressive encoding but can also generate
1080i interlaced pixels, and was initially designed to encode pixels for
VDAC to output RGB ou YUV analog outputs.
It's output is only used through the ENCP_DVI encoder for HDMI.
The ENCL LVDS encoder is not implemented.

The ENCI and ENCP encoders needs specially defined parameters for each
supported mode and thus cannot be determined from standard video timings.

The ENCI end ENCP DVI encoders are more generic and can generate any timings
from the pixel data generated by ENCI or ENCP, so can use the standard video
timings are source for HW parameters.


<a id="rst-video-clocks"></a>

## Video Clocks


VCLK is the "Pixel Clock" frequency generator from a dedicated PLL.
We handle the following encodings :

- CVBS 27MHz generator via the VCLK2 to the VENCI and VDAC blocks
- HDMI Pixel Clocks generation

What is missing :

- Genenate Pixel clocks for 2K/4K 10bit formats

Clock generator scheme :

```text
 __________   _________            _____
|          | |         |          |     |--ENCI
| HDMI PLL |-| PLL_DIV |--- VCLK--|     |--ENCL
|__________| |_________| \        | MUX |--ENCP
                          --VCLK2-|     |--VDAC
                                  |_____|--HDMI-TX
```

Final clocks can take input for either VCLK or VCLK2, but
VCLK is the preferred path for HDMI clocking and VCLK2 is the
preferred path for CVBS VDAC clocking.

VCLK and VCLK2 have fixed divided clocks paths for /1, /2, /4, /6 or /12.

The PLL_DIV can achieve an additional fractional dividing like
1.5, 3.5, 3.75... to generate special 2K and 4K 10bit clocks.


<a id="rst-hdmi-video-output"></a>

## HDMI Video Output


HDMI Output is composed of :

- A Synopsys DesignWare HDMI Controller IP
- A TOP control block controlling the Clocks and PHY
- A custom HDMI PHY in order convert video to TMDS signal

```text
 ___________________________________
|            HDMI TOP               |<= HPD
|___________________________________|
|                  |                |
|  Synopsys HDMI   |   HDMI PHY     |=> TMDS
|    Controller    |________________|
|___________________________________|<=> DDC
```

The HDMI TOP block only supports HPD sensing.
The Synopsys HDMI Controller interrupt is routed
through the TOP Block interrupt.
Communication to the TOP Block and the Synopsys
HDMI Controller is done a pair of addr+read/write
registers.
The HDMI PHY is configured by registers in the
HHI register block.

Pixel data arrives in 4:4:4 format from the VENC
block and the VPU HDMI mux selects either the ENCI
encoder for the 576i or 480i formats or the ENCP
encoder for all the other formats including
interlaced HD formats.
The VENC uses a DVI encoder on top of the ENCI
or ENCP encoders to generate DVI timings for the
HDMI controller.

GXBB, GXL and GXM embeds the Synopsys DesignWare
HDMI TX IP version 2.01a with HDCP and I2C & S/PDIF
audio source interfaces.

We handle the following features :

- HPD Rise & Fall interrupt
- HDMI Controller Interrupt
- HDMI PHY Init for 480i to 1080p60
- VENC & HDMI Clock setup for 480i to 1080p60
- VENC Mode setup for 480i to 1080p60

What is missing :

- PHY, Clock and Mode setup for 2k && 4k modes
- SDDC Scrambling mode for HDMI 2.0a
- HDCP Setup
- CEC Management

---

# MSM Crash Dump Format

_Peios Kernel / Hardware and drivers / Graphics_

> Following a GPU hang the MSM driver outputs debugging information via /sys/kernel/dri/X/show or via devcoredump (/sys/class/devcoredump/dcdX/data). This document describes how the output is formatted.

**orphan:** 

<a id="rst-msm-crash-dump-format"></a>

## MSM Crash Dump Format

Following a GPU hang the MSM driver outputs debugging information via /sys/kernel/dri/X/show or via devcoredump (/sys/class/devcoredump/dcdX/data). This document describes how the output is formatted.

Each entry is in the form key: value. Sections headers will not have a value and all the contents of a section will be indented two spaces from the header. Each section might have multiple array entries the start of which is designated by a (-).

<a id="rst-mappings"></a>

### Mappings

- **kernel**

  The kernel version that generated the dump (UTS_RELEASE).

- **module**

  The module that generated the crashdump.

- **time**

  The kernel time at crash formatted as seconds.microseconds.

- **comm**

  Comm string for the binary that generated the fault.

- **cmdline**

  Command line for the binary that generated the fault.

- **revision**

  ID of the GPU that generated the crash formatted as core.major.minor.patchlevel separated by dots.

- **rbbm-status**

  The current value of RBBM_STATUS which shows what top level GPU components are in use at the time of crash.

- **ringbuffer**

  Section containing the contents of each ringbuffer. Each ringbuffer is identified with an id number.

  - **id**

    Ringbuffer ID (0 based index).  Each ringbuffer in the section will have its own unique id.

  - **iova**

    GPU address of the ringbuffer.

  - **last-fence**

    The last fence that was issued on the ringbuffer

  - **retired-fence**

    The last fence retired on the ringbuffer.

  - **rptr**

    The current read pointer (rptr) for the ringbuffer.

  - **wptr**

    The current write pointer (wptr) for the ringbuffer.

  - **size**

    Maximum size of the ringbuffer programmed in the hardware.

  - **data**

    The contents of the ring encoded as ascii85.  Only the used portions of the ring will be printed.

- **bo**

  List of buffers from the hanging submission if available. Each buffer object will have a uinque iova.

  - **iova**

    GPU address of the buffer object.

  - **size**

    Allocated size of the buffer object.

  - **data**

    The contents of the buffer object encoded with ascii85.  Only Trailing zeros at the end of the buffer will be skipped.

- **registers**

  Set of registers values. Each entry is on its own line enclosed by brackets \{ \}.

  - **offset**

    Byte offset of the register from the start of the GPU memory region.

  - **value**

    Hexadecimal value of the register.

- **registers-hlsq**

  (5xx only) Register values from the HLSQ aperture. Same format as the register section.

---

# MSM Preemption

_Peios Kernel / Hardware and drivers / Graphics_

> Preemption allows Adreno GPUs to switch to a higher priority ring when work is pushed to it, reducing latency for high priority submissions.

<!-- SPDX-License-Identifier: GPL-2.0 -->

**orphan:** 

<a id="rst-msm-preemption"></a>

## MSM Preemption

Preemption allows Adreno GPUs to switch to a higher priority ring when work is pushed to it, reducing latency for high priority submissions.

When preemption is enabled 4 rings are initialized, corresponding to different priority levels. Having multiple rings is purely a software concept as the GPU only has registers to keep track of one graphics ring. The kernel is able to switch which ring is currently being processed by requesting preemption. When certain conditions are met, depending on the priority level, the GPU will save its current state in a series of buffers, then restores state from a similar set of buffers specified by the kernel. It then resumes execution and fires an IRQ to let the kernel know the context switch has completed.

This mechanism can be used by the kernel to switch between rings. Whenever a submission occurs the kernel finds the highest priority ring which isn't empty and preempts to it if said ring is not the one being currently executed. This is also done whenever a submission completes to make sure execution resumes on a lower priority ring when a higher priority ring is done.

<a id="rst-preemption-levels"></a>

### Preemption levels

Preemption can only occur at certain boundaries. The exact conditions can be configured by changing the preemption level, this allows to compromise between latency (ie. the time that passes between when the kernel requests preemption and when the SQE begins saving state) and overhead (the amount of state that needs to be saved).

The GPU offers 3 levels:

- **Level 0**

  Preemption only occurs at the submission level. This requires the least amount of state to be saved as the execution of userspace submitted IBs is never interrupted, however it offers very little benefit compared to not enabling preemption of any kind.

- **Level 1**

  Preemption occurs at either bin level, if using GMEM rendering, or draw level in the sysmem rendering case.

- **Level 2**

  Preemption occurs at draw level.

Level 1 is the mode that is used by the msm driver.

Additionally the GPU allows to specify a `skip_save_restore` option. This disables the saving and restoring of all registers except those relating to the operation of the SQE itself, reducing overhead. Saving and restoring is only skipped when using GMEM with Level 1 preemption. When enabling this userspace is expected to set the state that isn't preserved whenever preemption occurs which is done by specifying preamble and postambles. Those are IBs that are executed before and after preemption.

<a id="rst-preemption-buffers"></a>

### Preemption buffers

A series of buffers are necessary to store the state of rings while they are not being executed. There are different kinds of preemption records and most of those require one buffer per ring. This is because preemption never occurs between submissions on the same ring, which always run in sequence when the ring is active. This means that only one context per ring is effectively active.

- **SMMU_INFO**

  This buffer contains info about the current SMMU configuration such as the ttbr0 register. The SQE firmware isn't actually able to save this record. As a result SMMU info must be saved manually from the CP to a buffer and the SMMU record updated with info from said buffer before triggering preemption.

- **NON_SECURE**

  This is the main preemption record where most state is saved. It is mostly opaque to the kernel except for the first few words that must be initialized by the kernel.

- **SECURE**

  This saves state related to the GPU's secure mode.

- **NON_PRIV**

  The intended purpose of this record is unknown. The SQE firmware actually ignores it and therefore msm doesn't handle it.

- **COUNTER**

  This record is used to save and restore performance counters.

Handling the permissions of those buffers is critical for security. All but the NON_PRIV records need to be inaccessible from userspace, so they must be mapped in the kernel address space with the MSM_BO_MAP_PRIV flag. For example, making the NON_SECURE record accessible from userspace would allow any process to manipulate a saved ring's RPTR which can be used to skip the execution of some packets in a ring and execute user commands with higher privileges.

---

# drm/nouveau NVIDIA GPU Driver

_Peios Kernel / Hardware and drivers / Graphics_

> The drm/nouveau driver provides support for a wide range of NVIDIA GPUs, covering GeForce, Quadro, and Tesla series, from the NV04 architecture up to the latest Turing, Ampere, Ada families.

<a id="rst-drm-nouveau-nvidia-gpu-driver"></a>

<!-- SPDX-License-Identifier: (GPL-2.0+ OR MIT) -->

The drm/nouveau driver provides support for a wide range of NVIDIA GPUs, covering GeForce, Quadro, and Tesla series, from the NV04 architecture up to the latest Turing, Ampere, Ada families.

<a id="rst-nvkm-nvidia-kernel-manager"></a>

## NVKM: NVIDIA Kernel Manager

The NVKM component serves as the core abstraction layer within the nouveau driver, responsible for managing NVIDIA GPU hardware at the kernel level. NVKM provides a unified interface for handling various GPU  architectures.

It enables resource management, power control, memory handling, and command submission required for the proper functioning of NVIDIA GPUs under the nouveau driver.

NVKM plays a critical role in abstracting hardware complexities and providing a consistent API to upper layers of the driver stack.

<a id="rst-gsp-support"></a>

### GSP Support


https://github.com/NVIDIA/open-gpu-kernel-modules/blob/535/src/nvidia/inc/kernel/gpu/gsp/message_queue_priv.h

The GSP command queue and status queue are message queues for the
communication between software and GSP. The software submits the GSP
RPC via the GSP command queue, GSP writes the status of the submitted
RPC in the status queue.

A GSP message queue element consists of three parts:

- message element header (struct r535_gsp_msg), which mostly maintains
  the metadata for queuing the element.

- RPC message header (struct nvfw_gsp_rpc), which maintains the info
  of the RPC. E.g., the RPC function number.

- The payload, where the RPC message stays. E.g. the params of a
  specific RPC function. Some RPC functions also have their headers
  in the payload. E.g. rm_alloc, rm_control.

The memory layout of a GSP message element can be illustrated below:

```text
+------------------------+
| Message Element Header |
|    (r535_gsp_msg)      |
|                        |
| (r535_gsp_msg.data)    |
|          |             |
|----------V-------------|
|    GSP RPC Header      |
|    (nvfw_gsp_rpc)      |
|                        |
| (nvfw_gsp_rpc.data)    |
|          |             |
|----------V-------------|
|       Payload          |
|                        |
|   header(optional)     |
|        params          |
+------------------------+
```

The max size of a message queue element is 16 pages (including the
headers). When a GSP message to be sent is larger than 16 pages, the
message should be split into multiple elements and sent accordingly.

In the bunch of the split elements, the first element has the expected
function number, while the rest of the elements are sent with the
function number NV_VGPU_MSG_FUNCTION_CONTINUATION_RECORD.

GSP consumes the elements from the cmdq and always writes the result
back to the msgq. The result is also formed as split elements.

Terminology:

- gsp_msg(msg): GSP message element (element header + GSP RPC header +
  payload)
- gsp_rpc(rpc): GSP RPC (RPC header + payload)
- gsp_rpc_buf: buffer for (GSP RPC header + payload)
- gsp_rpc_len: size of (GSP RPC header + payload)
- params_size: size of params in the payload
- payload_size: size of (header if exists + params) in the payload



When sending a GSP RPC command, there can be multiple cases of handling
the GSP RPC messages, which are the reply of GSP RPC commands, according
to the requirement of the callers and the nature of the GSP RPC commands.

NVKM_GSP_RPC_REPLY_NOWAIT - If specified, immediately return to the
caller after the GSP RPC command is issued.

NVKM_GSP_RPC_REPLY_NOSEQ - If specified, exactly like NOWAIT
but don't emit RPC sequence number.

NVKM_GSP_RPC_REPLY_RECV - If specified, wait and receive the entire GSP
RPC message after the GSP RPC command is issued.

NVKM_GSP_RPC_REPLY_POLL - If specified, wait for the specific reply and
discard the reply before returning to the caller.

---

# drm/Panfrost Mali Driver

_Peios Kernel / Hardware and drivers / Graphics_

> The drm/Panfrost driver implements the DRM client usage stats specification as documented in drm-client-usage-stats.

<a id="rst-drm-panfrost-mali-driver"></a>

<a id="rst-panfrost-drm-client-usage-stats-implementation"></a>
<a id="rst-panfrost-usage-stats"></a>

## Panfrost DRM client usage stats implementation

<!-- SPDX-License-Identifier: GPL-2.0+ -->

The drm/Panfrost driver implements the DRM client usage stats specification as documented in [DRM client usage stats](</kernel/hardware/gpu/drm-usage-stats.md#rst-drm-client-usage-stats>).

Example of the output showing the implemented key value pairs and entirety of the currently possible format options:

- **::**

  pos:    0 flags:  02400002 mnt_id: 27 ino:    531 drm-driver:     panfrost drm-client-id:  14 drm-engine-fragment:    1846584880 ns drm-cycles-fragment:    1424359409 drm-maxfreq-fragment:   799999987 Hz drm-curfreq-fragment:   799999987 Hz drm-engine-vertex-tiler:        71932239 ns drm-cycles-vertex-tiler:        52617357 drm-maxfreq-vertex-tiler:       799999987 Hz drm-curfreq-vertex-tiler:       799999987 Hz drm-total-memory:       290 MiB drm-shared-memory:      0 MiB drm-active-memory:      226 MiB drm-resident-memory:    36496 KiB drm-purgeable-memory:   128 KiB

Possible `drm-engine-` key names are: `fragment`, and  `vertex-tiler`. `drm-curfreq-` values convey the current operating frequency for that engine.

Users must bear in mind that engine and cycle sampling are disabled by default, because of power saving concerns. `fdinfo` users and benchmark applications which query the fdinfo file must make sure to toggle the job profiling status of the driver by writing into the appropriate sysfs node:



```text
echo <N> > /sys/bus/platform/drivers/panfrost/[a-f0-9]*.gpu/profiling
```

Where `N` is either `0` or `1`, depending on the desired enablement status.

---

# drm/Panthor CSF driver

_Peios Kernel / Hardware and drivers / Graphics_

> The drm/Panthor driver implements the DRM client usage stats specification as documented in drm-client-usage-stats.

<a id="rst-drm-panthor-csf-driver"></a>

<a id="rst-panthor-drm-client-usage-stats-implementation"></a>
<a id="rst-panthor-usage-stats"></a>

## Panthor DRM client usage stats implementation

<!-- SPDX-License-Identifier: GPL-2.0+ -->

The drm/Panthor driver implements the DRM client usage stats specification as documented in [DRM client usage stats](</kernel/hardware/gpu/drm-usage-stats.md#rst-drm-client-usage-stats>).

Example of the output showing the implemented key value pairs and entirety of the currently possible format options:

- **::**

  pos:    0 flags:  02400002 mnt_id: 29 ino:    491 drm-driver:     panthor drm-client-id:  10 drm-engine-panthor:     111110952750 ns drm-cycles-panthor:     94439687187 drm-maxfreq-panthor:    1000000000 Hz drm-curfreq-panthor:    1000000000 Hz panthor-resident-memory:        10396 KiB panthor-active-memory:  10396 KiB drm-total-memory:       16480 KiB drm-shared-memory:      0 drm-active-memory:      16200 KiB drm-resident-memory:    16480 KiB drm-purgeable-memory:   0

Possible `drm-engine-` key names are: `panthor`. `drm-curfreq-` values convey the current operating frequency for that engine.

Users must bear in mind that engine and cycle sampling are disabled by default, because of power saving concerns. `fdinfo` users and benchmark applications which query the fdinfo file must make sure to toggle the job profiling status of the driver by writing into the appropriate sysfs node:



```text
echo <N> > /sys/bus/platform/drivers/panthor/[a-f0-9]*.gpu/profiling
```

Where `N` is a bit mask where cycle and timestamp sampling are respectively enabled by the first and second bits.

Possible `panthor-*-memory` keys are: `active` and `resident`. These values convey the sizes of the internal driver-owned shmem BO's that aren't exposed to user-space through a DRM handle, like queue ring buffers, sync object arrays and heap chunks. Because they are all allocated and pinned at creation time, only `panthor-resident-memory` is necessary to tell us their size. `panthor-active-memory` shows the size of kernel BO's associated with VM's and groups currently being scheduled for execution by the GPU.

---

# drm/pl111 ARM PrimeCell PL110 and PL111 CLCD Driver

_Peios Kernel / Hardware and drivers / Graphics_

> Reference for drm/pl111 ARM PrimeCell PL110 and PL111 CLCD Driver.

<a id="rst-drm-pl111-arm-primecell-pl110-and-pl111-clcd-driver"></a>


The PL110/PL111 is a simple LCD controller that can support TFT
and STN displays. This driver exposes a standard KMS interface
for them.

The driver currently doesn't expose the cursor.  The DRM API for
cursors requires support for 64x64 ARGB8888 cursor images, while
the hardware can only support 64x64 monochrome with masking
cursors.  While one could imagine trying to hack something together
to look at the ARGB8888 and program reasonable in monochrome, we
just don't expose the cursor at all instead, and leave cursor
support to the application software cursor layer.

TODO:

- Fix race between setting plane base address and getting IRQ for
  vsync firing the pageflip completion.

- Read back hardware state at boot to skip reprogramming the
  hardware when doing a no-op modeset.

- Use the CLKSEL bit to support switching between the two external
  clock parents.

---

# drm/tegra NVIDIA Tegra GPU and display driver

_Peios Kernel / Hardware and drivers / Graphics_

> NVIDIA Tegra SoCs support a set of display, graphics and video functions via the host1x controller. host1x supplies command streams, gathered from a push buffer provided directly by the CPU, to its clients via channels. Software, or blocks…

<a id="rst-drm-tegra-nvidia-tegra-gpu-and-display-driver"></a>

NVIDIA Tegra SoCs support a set of display, graphics and video functions via the host1x controller. host1x supplies command streams, gathered from a push buffer provided directly by the CPU, to its clients via channels. Software, or blocks amongst themselves, can use syncpoints for synchronization.

Up until, but not including, Tegra124 (aka Tegra K1) the drm/tegra driver supports the built-in GPU, comprised of the gr2d and gr3d engines. Starting with Tegra124 the GPU is based on the NVIDIA desktop GPU architecture and supported by the drm/nouveau driver.

The drm/tegra driver supports NVIDIA Tegra SoC generations since Tegra20. It has three parts:

> - A host1x driver that provides infrastructure and access to the host1x services.
>
> - A KMS driver that supports the display controllers as well as a number of outputs, such as RGB, HDMI, DSI, and DisplayPort.
>
> - A set of custom userspace IOCTLs that can be used to submit jobs to the GPU and video engines via host1x.

<a id="rst-driver-infrastructure"></a>

## Driver Infrastructure

The various host1x clients need to be bound together into a logical device in order to expose their functionality to users. The infrastructure that supports this is implemented in the host1x driver. When a driver is registered with the infrastructure it provides a list of compatible strings specifying the devices that it needs. The infrastructure creates a logical device and scan the device tree for matching device nodes, adding the required clients to a list. Drivers for individual clients register with the infrastructure as well and are added to the logical host1x device.

Once all clients are available, the infrastructure will initialize the logical device using a driver-provided function which will set up the bits specific to the subsystem and in turn initialize each of its clients.

Similarly, when one of the clients is unregistered, the infrastructure will destroy the logical device by calling back into the driver, which ensures that the subsystem specific bits are torn down and the clients destroyed in turn.

<a id="rst-host1x-infrastructure-reference"></a>

### Host1x Infrastructure Reference


#### <a id="c-struct-host1x_bo_cache"></a>`struct host1x_bo_cache`

host1x buffer object cache

**Definition**

```c
struct host1x_bo_cache {
    struct list_head mappings;
    struct mutex lock;
};
```

**Members**

- `mappings`: list of mappings
- `lock`: synchronizes accesses to the list of mappings

**Description**

Note that entries are not periodically evicted from this cache and instead need to be
explicitly released. This is used primarily for DRM/KMS where the cache's reference is
released when the last reference to a buffer object represented by a mapping in this
cache is dropped.

#### <a id="c-struct-host1x_client_ops"></a>`struct host1x_client_ops`

host1x client operations

**Definition**

```c
struct host1x_client_ops {
    int (*early_init)(struct host1x_client *client);
    int (*init)(struct host1x_client *client);
    int (*exit)(struct host1x_client *client);
    int (*late_exit)(struct host1x_client *client);
    int (*suspend)(struct host1x_client *client);
    int (*resume)(struct host1x_client *client);
};
```

**Members**

- `early_init`: host1x client early initialization code
- `init`: host1x client initialization code
- `exit`: host1x client tear down code
- `late_exit`: host1x client late tear down code
- `suspend`: host1x client suspend code
- `resume`: host1x client resume code

#### <a id="c-struct-host1x_client"></a>`struct host1x_client`

host1x client structure

**Definition**

```c
struct host1x_client {
    struct list_head list;
    struct device *host;
    struct device *dev;
    struct iommu_group *group;
    const struct host1x_client_ops *ops;
    enum host1x_class class;
    struct host1x_channel *channel;
    struct host1x_syncpt **syncpts;
    unsigned int num_syncpts;
    struct host1x_client *parent;
    unsigned int usecount;
    struct mutex lock;
    struct host1x_bo_cache cache;
};
```

**Members**

- `list`: list node for the host1x client
- `host`: pointer to struct device representing the host1x controller
- `dev`: pointer to struct device backing this host1x client
- `group`: IOMMU group that this client is a member of
- `ops`: host1x client operations
- `class`: host1x class represented by this client
- `channel`: host1x channel associated with this client
- `syncpts`: array of syncpoints requested for this client
- `num_syncpts`: number of syncpoints requested for this client
- `parent`: pointer to parent structure
- `usecount`: reference count for this structure
- `lock`: mutex for mutually exclusive concurrency
- `cache`: host1x buffer object cache

#### <a id="c-struct-host1x_driver"></a>`struct host1x_driver`

host1x logical device driver

**Definition**

```c
struct host1x_driver {
    struct device_driver driver;
    const struct of_device_id *subdevs;
    struct list_head list;
    int (*probe)(struct host1x_device *device);
    void (*remove)(struct host1x_device *device);
    void (*shutdown)(struct host1x_device *device);
};
```

**Members**

- `driver`: core driver
- `subdevs`: table of OF device IDs matching subdevices for this driver
- `list`: list node for the driver
- `probe`: called when the host1x logical device is probed
- `remove`: called when the host1x logical device is removed
- `shutdown`: called when the host1x logical device is shut down



#### <a id="c-host1x_device_init"></a>`host1x_device_init()`

```c
int host1x_device_init(struct host1x_device *device)
```

initialize a host1x logical device

**Parameters**

- `struct host1x_device *device`: host1x logical device

**Description**

The driver for the host1x logical device can call this during execution of
its [`host1x_driver.probe`](#c-struct-host1x_driver) implementation to initialize each of its clients.
The client drivers access the subsystem specific driver data using the
[`host1x_client.parent`](#c-struct-host1x_client) field and driver data associated with it (usually by
calling `dev_get_drvdata()`).

#### <a id="c-host1x_device_exit"></a>`host1x_device_exit()`

```c
int host1x_device_exit(struct host1x_device *device)
```

uninitialize host1x logical device

**Parameters**

- `struct host1x_device *device`: host1x logical device

**Description**

When the driver for a host1x logical device is unloaded, it can call this
function to tear down each of its clients. Typically this is done after a
subsystem-specific data structure is removed and the functionality can no
longer be used.

#### <a id="c-host1x_driver_register_full"></a>`host1x_driver_register_full()`

```c
int host1x_driver_register_full(struct host1x_driver *driver, struct module *owner)
```

register a host1x driver

**Parameters**

- `struct host1x_driver *driver`: host1x driver
- `struct module *owner`: owner module

**Description**

Drivers for host1x logical devices call this function to register a driver
with the infrastructure. Note that since these drive logical devices, the
registration of the driver actually triggers tho logical device creation.
A logical device will be created for each host1x instance.

#### <a id="c-host1x_driver_unregister"></a>`host1x_driver_unregister()`

```c
void host1x_driver_unregister(struct host1x_driver *driver)
```

unregister a host1x driver

**Parameters**

- `struct host1x_driver *driver`: host1x driver

**Description**

Unbinds the driver from each of the host1x logical devices that it is
bound to, effectively removing the subsystem devices that they represent.

#### <a id="c-__host1x_client_init"></a>`__host1x_client_init()`

```c
void __host1x_client_init(struct host1x_client *client, struct lock_class_key *key)
```

initialize a host1x client

**Parameters**

- `struct host1x_client *client`: host1x client
- `struct lock_class_key *key`: lock class key for the client-specific mutex

#### <a id="c-host1x_client_exit"></a>`host1x_client_exit()`

```c
void host1x_client_exit(struct host1x_client *client)
```

uninitialize a host1x client

**Parameters**

- `struct host1x_client *client`: host1x client

#### <a id="c-__host1x_client_register"></a>`__host1x_client_register()`

```c
int __host1x_client_register(struct host1x_client *client)
```

register a host1x client

**Parameters**

- `struct host1x_client *client`: host1x client

**Description**

Registers a host1x client with each host1x controller instance. Note that
each client will only match their parent host1x controller and will only be
associated with that instance. Once all clients have been registered with
their parent host1x controller, the infrastructure will set up the logical
device and call [`host1x_device_init()`](#c-host1x_device_init), which will in turn call each client's
[`host1x_client_ops.init`](#c-struct-host1x_client_ops) implementation.

#### <a id="c-host1x_client_unregister"></a>`host1x_client_unregister()`

```c
void host1x_client_unregister(struct host1x_client *client)
```

unregister a host1x client

**Parameters**

- `struct host1x_client *client`: host1x client

**Description**

Removes a host1x client from its host1x controller instance. If a logical
device has already been initialized, it will be torn down.


<a id="rst-host1x-syncpoint-reference"></a>

### Host1x Syncpoint Reference


#### <a id="c-host1x_syncpt_alloc"></a>`host1x_syncpt_alloc()`

```c
struct host1x_syncpt * host1x_syncpt_alloc(struct host1x *host, unsigned long flags, const char *name)
```

allocate a syncpoint

**Parameters**

- `struct host1x *host`: host1x device data
- `unsigned long flags`: bitfield of HOST1X_SYNCPT_* flags
- `const char *name`: name for the syncpoint for use in debug prints

**Description**

Allocates a hardware syncpoint for the caller's use. The caller then has
the sole authority to mutate the syncpoint's value until it is freed again.

If no free syncpoints are available, or a NULL name was specified, returns
NULL.

#### <a id="c-host1x_syncpt_id"></a>`host1x_syncpt_id()`

```c
u32 host1x_syncpt_id(struct host1x_syncpt *sp)
```

retrieve syncpoint ID

**Parameters**

- `struct host1x_syncpt *sp`: host1x syncpoint

**Description**

Given a pointer to a struct host1x_syncpt, retrieves its ID. This ID is
often used as a value to program into registers that control how hardware
blocks interact with syncpoints.

#### <a id="c-host1x_syncpt_incr_max"></a>`host1x_syncpt_incr_max()`

```c
u32 host1x_syncpt_incr_max(struct host1x_syncpt *sp, u32 incrs)
```

update the value sent to hardware

**Parameters**

- `struct host1x_syncpt *sp`: host1x syncpoint
- `u32 incrs`: number of increments

#### <a id="c-host1x_syncpt_incr"></a>`host1x_syncpt_incr()`

```c
int host1x_syncpt_incr(struct host1x_syncpt *sp)
```

increment syncpoint value from CPU, updating cache

**Parameters**

- `struct host1x_syncpt *sp`: host1x syncpoint

#### <a id="c-host1x_syncpt_wait"></a>`host1x_syncpt_wait()`

```c
int host1x_syncpt_wait(struct host1x_syncpt *sp, u32 thresh, long timeout, u32 *value)
```

wait for a syncpoint to reach a given value

**Parameters**

- `struct host1x_syncpt *sp`: host1x syncpoint
- `u32 thresh`: threshold
- `long timeout`: maximum time to wait for the syncpoint to reach the given value
- `u32 *value`: return location for the syncpoint value

#### <a id="c-host1x_syncpt_request"></a>`host1x_syncpt_request()`

```c
struct host1x_syncpt * host1x_syncpt_request(struct host1x_client *client, unsigned long flags)
```

request a syncpoint

**Parameters**

- `struct host1x_client *client`: client requesting the syncpoint
- `unsigned long flags`: flags

**Description**

host1x client drivers can use this function to allocate a syncpoint for
subsequent use. A syncpoint returned by this function will be reserved for
use by the client exclusively. When no longer using a syncpoint, a host1x
client driver needs to release it using [`host1x_syncpt_put()`](#c-host1x_syncpt_put).

#### <a id="c-host1x_syncpt_put"></a>`host1x_syncpt_put()`

```c
void host1x_syncpt_put(struct host1x_syncpt *sp)
```

free a requested syncpoint

**Parameters**

- `struct host1x_syncpt *sp`: host1x syncpoint

**Description**

Release a syncpoint previously allocated using [`host1x_syncpt_request()`](#c-host1x_syncpt_request). A
host1x client driver should call this when the syncpoint is no longer in
use.

#### <a id="c-host1x_syncpt_read_max"></a>`host1x_syncpt_read_max()`

```c
u32 host1x_syncpt_read_max(struct host1x_syncpt *sp)
```

read maximum syncpoint value

**Parameters**

- `struct host1x_syncpt *sp`: host1x syncpoint

**Description**

The maximum syncpoint value indicates how many operations there are in
queue, either in channel or in a software thread.

#### <a id="c-host1x_syncpt_read_min"></a>`host1x_syncpt_read_min()`

```c
u32 host1x_syncpt_read_min(struct host1x_syncpt *sp)
```

read minimum syncpoint value

**Parameters**

- `struct host1x_syncpt *sp`: host1x syncpoint

**Description**

The minimum syncpoint value is a shadow of the current sync point value in
hardware.

#### <a id="c-host1x_syncpt_read"></a>`host1x_syncpt_read()`

```c
u32 host1x_syncpt_read(struct host1x_syncpt *sp)
```

read the current syncpoint value

**Parameters**

- `struct host1x_syncpt *sp`: host1x syncpoint

#### <a id="c-host1x_syncpt_get_by_id"></a>`host1x_syncpt_get_by_id()`

```c
struct host1x_syncpt * host1x_syncpt_get_by_id(struct host1x *host, unsigned int id)
```

obtain a syncpoint by ID

**Parameters**

- `struct host1x *host`: host1x controller
- `unsigned int id`: syncpoint ID

#### <a id="c-host1x_syncpt_get_by_id_noref"></a>`host1x_syncpt_get_by_id_noref()`

```c
struct host1x_syncpt * host1x_syncpt_get_by_id_noref(struct host1x *host, unsigned int id)
```

obtain a syncpoint by ID but don't increase the refcount.

**Parameters**

- `struct host1x *host`: host1x controller
- `unsigned int id`: syncpoint ID

#### <a id="c-host1x_syncpt_get"></a>`host1x_syncpt_get()`

```c
struct host1x_syncpt * host1x_syncpt_get(struct host1x_syncpt *sp)
```

increment syncpoint refcount

**Parameters**

- `struct host1x_syncpt *sp`: syncpoint

#### <a id="c-host1x_syncpt_get_base"></a>`host1x_syncpt_get_base()`

```c
struct host1x_syncpt_base * host1x_syncpt_get_base(struct host1x_syncpt *sp)
```

obtain the wait base associated with a syncpoint

**Parameters**

- `struct host1x_syncpt *sp`: host1x syncpoint

#### <a id="c-host1x_syncpt_base_id"></a>`host1x_syncpt_base_id()`

```c
u32 host1x_syncpt_base_id(struct host1x_syncpt_base *base)
```

retrieve the ID of a syncpoint wait base

**Parameters**

- `struct host1x_syncpt_base *base`: host1x syncpoint wait base

#### <a id="c-host1x_syncpt_release_vblank_reservation"></a>`host1x_syncpt_release_vblank_reservation()`

```c
void host1x_syncpt_release_vblank_reservation(struct host1x_client *client, u32 syncpt_id)
```

Make VBLANK syncpoint available for allocation

**Parameters**

- `struct host1x_client *client`: host1x bus client
- `u32 syncpt_id`: syncpoint ID to make available

**Description**

Makes VBLANK\<i> syncpoint available for allocatation if it was
reserved at initialization time. This should be called by the display
driver after it has ensured that any VBLANK increment programming configured
by the boot chain has been disabled.


<a id="rst-kms-driver"></a>

## KMS driver

The display hardware has remained mostly backwards compatible over the various Tegra SoC generations, up until Tegra186 which introduces several changes that make it difficult to support with a parameterized driver.

<a id="rst-display-controllers"></a>

### Display Controllers

Tegra SoCs have two display controllers, each of which can be associated with zero or more outputs. Outputs can also share a single display controller, but only if they run with compatible display timings. Two display controllers can also share a single framebuffer, allowing cloned configurations even if modes on two outputs don't match. A display controller is modelled as a CRTC in KMS terms.

On Tegra186, the number of display controllers has been increased to three. A display controller can no longer drive all of the outputs. While two of these controllers can drive both DSI outputs and both SOR outputs, the third cannot drive any DSI.

<a id="rst-windows"></a>

#### Windows

A display controller controls a set of windows that can be used to composite multiple buffers onto the screen. While it is possible to assign arbitrary Z ordering to individual windows (by programming the corresponding blending registers), this is currently not supported by the driver. Instead, it will assume a fixed Z ordering of the windows (window A is the root window, that is, the lowest, while windows B and C are overlaid on top of window A). The overlay windows support multiple pixel formats and can automatically convert from YUV to RGB at scanout time. This makes them useful for displaying video content. In KMS, each window is modelled as a plane. Each display controller has a hardware cursor that is exposed as a cursor plane.

<a id="rst-outputs"></a>

### Outputs

The type and number of supported outputs varies between Tegra SoC generations. All generations support at least HDMI. While earlier generations supported the very simple RGB interfaces (one per display controller), recent generations no longer do and instead provide standard interfaces such as DSI and eDP/DP.

Outputs are modelled as a composite encoder/connector pair.

<a id="rst-rgb-lvds"></a>

#### RGB/LVDS

This interface is no longer available since Tegra124. It has been replaced by the more standard DSI and eDP interfaces.

<a id="rst-hdmi"></a>

#### HDMI

HDMI is supported on all Tegra SoCs. Starting with Tegra210, HDMI is provided by the versatile SOR output, which supports eDP, DP and HDMI. The SOR is able to support HDMI 2.0, though support for this is currently not merged.

<a id="rst-dsi"></a>

#### DSI

Although Tegra has supported DSI since Tegra30, the controller has changed in several ways in Tegra114. Since none of the publicly available development boards prior to Dalmore (Tegra114) have made use of DSI, only Tegra114 and later are supported by the drm/tegra driver.

<a id="rst-edp-dp"></a>

#### eDP/DP

eDP was first introduced in Tegra124 where it was used to drive the display panel for notebook form factors. Tegra210 added support for full DisplayPort support, though this is currently not implemented in the drm/tegra driver.

<a id="rst-userspace-interface"></a>

## Userspace Interface

The userspace interface provided by drm/tegra allows applications to create GEM buffers, access and control syncpoints as well as submit command streams to host1x.

<a id="rst-gem-buffers"></a>

### GEM Buffers

The `DRM_IOCTL_TEGRA_GEM_CREATE` IOCTL is used to create a GEM buffer object with Tegra-specific flags. This is useful for buffers that should be tiled, or that are to be scanned out upside down (useful for 3D content).

After a GEM buffer object has been created, its memory can be mapped by an application using the mmap offset returned by the `DRM_IOCTL_TEGRA_GEM_MMAP` IOCTL.

<a id="rst-syncpoints"></a>

### Syncpoints

The current value of a syncpoint can be obtained by executing the `DRM_IOCTL_TEGRA_SYNCPT_READ` IOCTL. Incrementing the syncpoint is achieved using the `DRM_IOCTL_TEGRA_SYNCPT_INCR` IOCTL.

Userspace can also request blocking on a syncpoint. To do so, it needs to execute the `DRM_IOCTL_TEGRA_SYNCPT_WAIT` IOCTL, specifying the value of the syncpoint to wait for. The kernel will release the application when the syncpoint reaches that value or after a specified timeout.

<a id="rst-command-stream-submission"></a>

### Command Stream Submission

Before an application can submit command streams to host1x it needs to open a channel to an engine using the `DRM_IOCTL_TEGRA_OPEN_CHANNEL` IOCTL. Client IDs are used to identify the target of the channel. When a channel is no longer needed, it can be closed using the `DRM_IOCTL_TEGRA_CLOSE_CHANNEL` IOCTL. To retrieve the syncpoint associated with a channel, an application can use the `DRM_IOCTL_TEGRA_GET_SYNCPT`.

After opening a channel, submitting command streams is easy. The application writes commands into the memory backing a GEM buffer object and passes these to the `DRM_IOCTL_TEGRA_SUBMIT` IOCTL along with various other parameters, such as the syncpoints or relocations used in the job submission.

---

# TODO list

_Peios Kernel / Hardware and drivers / Graphics_

> This section contains a list of smaller janitorial tasks in the kernel DRM graphics subsystem useful as newbie projects. Or for slow rainy days.

<a id="rst-todo-list"></a>
<a id="rst-todo"></a>

This section contains a list of smaller janitorial tasks in the kernel DRM graphics subsystem useful as newbie projects. Or for slow rainy days.

<a id="rst-difficulty"></a>

## Difficulty

To make it easier task are categorized into different levels:

Starter: Good tasks to get started with the DRM subsystem.

Intermediate: Tasks which need some experience with working in the DRM subsystem, or some specific GPU/display graphics knowledge. For debugging issue it's good to have the relevant hardware (or a virtual driver set up) available for testing.

Advanced: Tricky tasks that need fairly good understanding of the DRM subsystem and graphics topics. Generally need the relevant hardware for development and testing.

Expert: Only attempt these if you've successfully completed some tricky refactorings already and are an expert in the specific area

<a id="rst-subsystem-wide-refactorings"></a>

### Subsystem-wide refactorings

<a id="rst-remove-custom-dumb-map-offset-implementations"></a>

## Remove custom dumb_map_offset implementations

All GEM based drivers should be using drm_gem_create_mmap_offset() instead. Audit each individual driver, make sure it'll work with the generic implementation (there's lots of outdated locking leftovers in various implementations), and then remove it.

Contact: Simona Vetter, respective driver maintainers

Level: Intermediate

<a id="rst-convert-existing-kms-drivers-to-atomic-modesetting"></a>

## Convert existing KMS drivers to atomic modesetting

3.19 has the atomic modeset interfaces and helpers, so drivers can now be converted over. Modern compositors like Wayland or Surfaceflinger on Android really want an atomic modeset interface, so this is all about the bright future.

There is a conversion guide for atomic <a id="rst-footnote-reference-1"></a>[1](#rst-footnote-1) and all you need is a GPU for a non-converted driver.  The "Atomic mode setting design overview" series <a id="rst-footnote-reference-2"></a>[2](#rst-footnote-2) <a id="rst-footnote-reference-3"></a>[3](#rst-footnote-3) at LWN.net can also be helpful.

As part of this drivers also need to convert to universal plane (which means exposing primary &amp; cursor as proper plane objects). But that's much easier to do by directly using the new atomic helper driver callbacks.

> <a id="rst-footnote-1"></a>
>
>
>
> **[1]** [https://blog.ffwll.ch/2014/11/atomic-modeset-support-for-kms-drivers.html](<https://blog.ffwll.ch/2014/11/atomic-modeset-support-for-kms-drivers.html>)
>
> <a id="rst-footnote-2"></a>
>
>
>
> **[2]** [https://lwn.net/Articles/653071/](<https://lwn.net/Articles/653071/>)
>
> <a id="rst-footnote-3"></a>
>
>
>
> **[3]** [https://lwn.net/Articles/653466/](<https://lwn.net/Articles/653466/>)

Contact: Simona Vetter, respective driver maintainers

Level: Advanced

<a id="rst-clean-up-the-clipped-coordination-confusion-around-planes"></a>

## Clean up the clipped coordination confusion around planes

We have a helper to get this right with drm_plane_helper_check_update(), but it's not consistently used. This should be fixed, preferably in the atomic helpers (and drivers then moved over to clipped coordinates). Probably the helper should also be moved from drm_plane_helper.c to the atomic helpers, to avoid confusion - the other helpers in that file are all deprecated legacy helpers.

Contact: Ville Syrjälä, Simona Vetter, driver maintainers

Level: Advanced

<a id="rst-improve-plane-atomic-check-helpers"></a>

## Improve plane atomic_check helpers

Aside from the clipped coordinates right above there's a few suboptimal things with the current helpers:

- drm_plane_helper_funcs-&gt;atomic_check gets called for enabled or disabled planes. At best this seems to confuse drivers, worst it means they blow up when the plane is disabled without the CRTC. The only special handling is resetting values in the plane state structures, which instead should be moved into the drm_plane_funcs-&gt;atomic_duplicate_state functions.

- Once that's done, helpers could stop calling -&gt;atomic_check for disabled planes.

- Then we could go through all the drivers and remove the more-or-less confused checks for plane_state-&gt;fb and plane_state-&gt;crtc.

Contact: Simona Vetter

Level: Advanced

<a id="rst-convert-early-atomic-drivers-to-async-commit-helpers"></a>

## Convert early atomic drivers to async commit helpers

For the first year the atomic modeset helpers didn't support asynchronous / nonblocking commits, and every driver had to hand-roll them. This is fixed now, but there's still a pile of existing drivers that easily could be converted over to the new infrastructure.

One issue with the helpers is that they require that drivers handle completion events for atomic commits correctly. But fixing these bugs is good anyway.

Somewhat related is the legacy_cursor_update hack, which should be replaced with the new atomic_async_check/commit functionality in the helpers in drivers that still look at that flag.

Contact: Simona Vetter, respective driver maintainers

Level: Advanced

<a id="rst-rename-drm-atomic-state"></a>

## Rename drm_atomic_state

The KMS framework uses two slightly different definitions for the `state` concept. For a given object (plane, CRTC, encoder, etc., so `drm_$OBJECT_state`), the state is the entire state of that object. However, at the device level, `drm_atomic_state` refers to a state update for a limited number of objects.

The state isn't the entire device state, but only the full state of some objects in that device. This is confusing to newcomers, and `drm_atomic_state` should be renamed to something clearer like `drm_atomic_commit`.

In addition to renaming the structure itself, it would also imply renaming some related functions (`drm_atomic_state_alloc`, `drm_atomic_state_get`, `drm_atomic_state_put`, `drm_atomic_state_init`, `__drm_atomic_state_free`, etc.).

Contact: Maxime Ripard &lt;[mripard@kernel.org](<mailto:mripard@kernel.org>)&gt;

Level: Advanced

<a id="rst-fallout-from-atomic-kms"></a>

## Fallout from atomic KMS

`drm_atomic_helper.c` provides a batch of functions which implement legacy IOCTLs on top of the new atomic driver interface. Which is really nice for gradual conversion of drivers, but unfortunately the semantic mismatches are a bit too severe. So there's some follow-up work to adjust the function interfaces to fix these issues:

- atomic needs the lock acquire context. At the moment that's passed around implicitly with some horrible hacks, and it's also allocate with `GFP_NOFAIL` behind the scenes. All legacy paths need to start allocating the acquire context explicitly on stack and then also pass it down into drivers explicitly so that the legacy-on-atomic functions can use them.

  Except for some driver code this is done. This task should be finished by adding WARN_ON(\!drm_drv_uses_atomic_modeset) in drm_modeset_lock_all().

- A bunch of the vtable hooks are now in the wrong place: DRM has a split between core vfunc tables (named `drm_foo_funcs`), which are used to implement the userspace ABI. And then there's the optional hooks for the helper libraries (name `drm_foo_helper_funcs`), which are purely for internal use. Some of these hooks should be move from `_funcs` to `_helper_funcs` since they are not part of the core ABI. There's a `FIXME` comment in the kerneldoc for each such case in `drm_crtc.h`.

Contact: Simona Vetter

Level: Intermediate

<a id="rst-move-buffer-object-locking-to-dma-resv-lock"></a>

## Move Buffer Object Locking to dma_resv_lock()

Many drivers have their own per-object locking scheme, usually using mutex_lock(). This causes all kinds of trouble for buffer sharing, since depending which driver is the exporter and importer, the locking hierarchy is reversed.

To solve this we need one standard per-object locking mechanism, which is dma_resv_lock(). This lock needs to be called as the outermost lock, with all other driver specific per-object locks removed. The problem is that rolling out the actual change to the locking contract is a flag day, due to struct dma_buf buffer sharing.

Level: Expert

<a id="rst-convert-logging-to-drm-functions-with-drm-device-parameter"></a>

## Convert logging to drm\_\* functions with drm_device parameter

For drivers which could have multiple instances, it is necessary to differentiate between which is which in the logs. Since DRM_INFO/WARN/ERROR don't do this, drivers used dev_info/warn/err to make this differentiation. We now have drm\_\* variants of the drm print functions, so we can start to convert those drivers back to using drm-formatted specific log messages.

Before you start this conversion please contact the relevant maintainers to make sure your work will be merged - not everyone agrees that the DRM dmesg macros are better.

Contact: Sean Paul, Maintainer of the driver you plan to convert

Level: Starter

<a id="rst-convert-drivers-to-use-simple-modeset-suspend-resume"></a>

## Convert drivers to use simple modeset suspend/resume

Most drivers (except i915 and nouveau) that use drm_atomic_helper_suspend/resume() can probably be converted to use drm_mode_config_helper_suspend/resume(). Also there's still open-coded version of the atomic suspend/resume code in older atomic modeset drivers.

Contact: Maintainer of the driver you plan to convert

Level: Intermediate

<a id="rst-reimplement-functions-in-drm-fbdev-fb-ops-without-fbdev"></a>

## Reimplement functions in drm_fbdev_fb_ops without fbdev

A number of callback functions in drm_fbdev_fb_ops could benefit from being rewritten without dependencies on the fbdev module. Some of the helpers could further benefit from using struct iosys_map instead of raw pointers.

Contact: Thomas Zimmermann &lt;[tzimmermann@suse.de](<mailto:tzimmermann@suse.de>)&gt;, Simona Vetter

Level: Advanced

<a id="rst-benchmark-and-optimize-blitting-and-format-conversion-function"></a>

## Benchmark and optimize blitting and format-conversion function

Drawing to display memory quickly is crucial for many applications' performance.

On at least x86-64, sys_imageblit() is significantly slower than cfb_imageblit(), even though both use the same blitting algorithm and the latter is written for I/O memory. It turns out that cfb_imageblit() uses movl instructions, while sys_imageblit apparently does not. This seems to be a problem with gcc's optimizer. DRM's format-conversion helpers might be subject to similar issues.

Benchmark and optimize fbdev's sys\_() helpers and DRM's format-conversion helpers. In cases that can be further optimized, maybe implement a different algorithm. For micro-optimizations, use movl/movq instructions explicitly. That might possibly require architecture-specific helpers (e.g., storel() storeq()).

Contact: Thomas Zimmermann &lt;[tzimmermann@suse.de](<mailto:tzimmermann@suse.de>)&gt;

Level: Intermediate

<a id="rst-drm-framebuffer-funcs-and-drm-mode-config-funcs-fb-create-cleanup"></a>

## drm_framebuffer_funcs and drm_mode_config_funcs.fb_create cleanup

A lot more drivers could be switched over to the drm_gem_framebuffer helpers. Various hold-ups:

- Need to switch over to the generic dirty tracking code using drm_atomic_helper_dirtyfb first (e.g. qxl).

- Need to switch to drm_fbdev_generic_setup(), otherwise a lot of the custom fb setup code can't be deleted.

- Need to switch to drm_gem_fb_create(), as now drm_gem_fb_create() checks for valid formats for atomic drivers.

- Many drivers subclass drm_framebuffer, we'd need a embedding compatible version of the varios drm_gem_fb_create functions. Maybe called drm_gem_fb_create/\_with_dirty/\_with_funcs as needed.

Contact: Simona Vetter

Level: Intermediate

<a id="rst-generic-fbdev-defio-support"></a>

## Generic fbdev defio support

The defio support code in the fbdev core has some very specific requirements, which means drivers need to have a special framebuffer for fbdev. The main issue is that it uses some fields in struct page itself, which breaks shmem gem objects (and other things). To support defio, affected drivers require the use of a shadow buffer, which may add CPU and memory overhead.

Possible solution would be to write our own defio mmap code in the drm fbdev emulation. It would need to fully wrap the existing mmap ops, forwarding everything after it has done the write-protect/mkwrite trickery:

- In the drm_fbdev_fb_mmap helper, if we need defio, change the default page prots to write-protected with something like this:



  ```text
  vma->vm_page_prot = pgprot_wrprotect(vma->vm_page_prot);
  ```

- Set the mkwrite and fsync callbacks with similar implementions to the core fbdev defio stuff. These should all work on plain ptes, they don't actually require a struct page.  uff. These should all work on plain ptes, they don't actually require a struct page.

- Track the dirty pages in a separate structure (bitfield with one bit per page should work) to avoid clobbering struct page.

Might be good to also have some igt testcases for this.

Contact: Simona Vetter, Noralf Tronnes

Level: Advanced

<a id="rst-connector-register-unregister-fixes"></a>

## connector register/unregister fixes

- For most connectors it's a no-op to call drm_connector_register/unregister directly from driver code, drm_dev_register/unregister take care of this already. We can remove all of them.

- For dp drivers it's a bit more a mess, since we need the connector to be registered when calling drm_dp_aux_register. Fix this by instead calling drm_dp_aux_init, and moving the actual registering into a late_register callback as recommended in the kerneldoc.

Level: Intermediate

<a id="rst-remove-load-unload-callbacks"></a>

## Remove load/unload callbacks

The load/unload callbacks in struct &amp;drm_driver are very much midlayers, plus for historical reasons they get the ordering wrong (and we can't fix that) between setting up the &amp;drm_driver structure and calling drm_dev_register().

- Rework drivers to no longer use the load/unload callbacks, directly coding the load/unload sequence into the driver's probe function.

- Once all drivers are converted, remove the load/unload callbacks.

Contact: Simona Vetter

Level: Intermediate

<a id="rst-replace-drm-detect-hdmi-monitor-with-drm-display-info-is-hdmi"></a>

## Replace drm_detect_hdmi_monitor() with drm_display_info.is_hdmi

Once EDID is parsed, the monitor HDMI support information is available through drm_display_info.is_hdmi. Many drivers still call drm_detect_hdmi_monitor() to retrieve the same information, which is less efficient.

Audit each individual driver calling drm_detect_hdmi_monitor() and switch to drm_display_info.is_hdmi if applicable.

Contact: Laurent Pinchart, respective driver maintainers

Level: Intermediate

<a id="rst-consolidate-custom-driver-modeset-properties"></a>

## Consolidate custom driver modeset properties

Before atomic modeset took place, many drivers where creating their own properties. Among other things, atomic brought the requirement that custom, driver specific properties should not be used.

For this task, we aim to introduce core helpers or reuse the existing ones if available:

A quick, unconfirmed, examples list.

Introduce core helpers: - audio (amdgpu, intel, gma500, radeon) - brightness, contrast, etc (armada, nouveau) - overlay only (?) - broadcast rgb (gma500, intel) - colorkey (armada, nouveau, rcar) - overlay only (?) - dither (amdgpu, nouveau, radeon) - varies across drivers - underscan family (amdgpu, radeon, nouveau)

Already in core: - colorspace (sti) - tv format names, enhancements (gma500, intel) - tv overscan, margins, etc. (gma500, intel) - zorder (omapdrm) - same as zpos (?)

Contact: Emil Velikov, respective driver maintainers

Level: Intermediate

<a id="rst-use-struct-iosys-map-throughout-codebase"></a>

## Use struct iosys_map throughout codebase

Pointers to shared device memory are stored in struct iosys_map. Each instance knows whether it refers to system or I/O memory. Most of the DRM-wide interface have been converted to use struct iosys_map, but implementations often still use raw pointers.

The task is to use struct iosys_map where it makes sense.

- Memory managers should use struct iosys_map for dma-buf-imported buffers.

- TTM might benefit from using struct iosys_map internally.

- Framebuffer copying and blitting helpers should operate on struct iosys_map.

Contact: Thomas Zimmermann &lt;[tzimmermann@suse.de](<mailto:tzimmermann@suse.de>)&gt;, Christian König, Simona Vetter

Level: Intermediate

<a id="rst-review-all-drivers-for-setting-struct-drm-mode-config-max-width-max-height-correctly"></a>

## Review all drivers for setting struct drm_mode_config.\{max_width,max_height\} correctly

The values in struct drm_mode_config.\{max_width,max_height\} describe the maximum supported framebuffer size. It's the virtual screen size, but many drivers treat it like limitations of the physical resolution.

The maximum width depends on the hardware's maximum scanline pitch. The maximum height depends on the amount of addressable video memory. Review all drivers to initialize the fields to the correct values.

Contact: Thomas Zimmermann &lt;[tzimmermann@suse.de](<mailto:tzimmermann@suse.de>)&gt;

Level: Intermediate

<a id="rst-request-memory-regions-in-all-fbdev-drivers"></a>

## Request memory regions in all fbdev drivers

Old/ancient fbdev drivers do not request their memory properly. Go through these drivers and add code to request the memory regions that the driver uses. This requires adding calls to request_mem_region(), pci_request_region() or similar functions. Use helpers for managed cleanup where possible. Problematic areas include hardware that has exclusive ranges like VGA. VGA16fb does not request the range as it is expected. Drivers are pretty bad at doing this and there used to be conflicts among DRM and fbdev drivers. Still, it's the correct thing to do.

Contact: Thomas Zimmermann &lt;[tzimmermann@suse.de](<mailto:tzimmermann@suse.de>)&gt;

Level: Starter

<a id="rst-remove-driver-dependencies-on-fb-device"></a>

## Remove driver dependencies on FB_DEVICE

A number of fbdev drivers provide attributes via sysfs and therefore depend on CONFIG_FB_DEVICE to be selected. Review each driver and attempt to make any dependencies on CONFIG_FB_DEVICE optional. At the minimum, the respective code in the driver could be conditionalized via ifdef CONFIG_FB_DEVICE. Not all drivers might be able to drop CONFIG_FB_DEVICE.

Contact: Thomas Zimmermann &lt;[tzimmermann@suse.de](<mailto:tzimmermann@suse.de>)&gt;

Level: Starter

<a id="rst-remove-disable-unprepare-in-remove-shutdown-in-panel-simple-and-panel-edp"></a>

## Remove disable/unprepare in remove/shutdown in panel-simple and panel-edp

As of commit d2aacaf07395 ("drm/panel: Check for already prepared/enabled in drm_panel"), we have a check in the drm_panel core to make sure nobody double-calls prepare/enable/disable/unprepare. Eventually that should probably be turned into a WARN_ON() or somehow made louder.

At the moment, we expect that we may still encounter the warnings in the drm_panel core when using panel-simple and panel-edp. Since those panel drivers are used with a lot of different DRM modeset drivers they still make an extra effort to disable/unprepare the panel themsevles at shutdown time. Specifically we could still encounter those warnings if the panel driver gets shutdown() \_before\_ the DRM modeset driver and the DRM modeset driver properly calls drm_atomic_helper_shutdown() in its own shutdown() callback. Warnings could be avoided in such a case by using something like device links to ensure that the panel gets shutdown() after the DRM modeset driver.

Once all DRM modeset drivers are known to shutdown properly, the extra calls to disable/unprepare in remove/shutdown in panel-simple and panel-edp should be removed and this TODO item marked complete.

Contact: Douglas Anderson &lt;[dianders@chromium.org](<mailto:dianders@chromium.org>)&gt;

Level: Intermediate

<a id="rst-transition-away-from-using-deprecated-mipi-dsi-functions"></a>

## Transition away from using deprecated MIPI DSI functions

There are many functions defined in `drm_mipi_dsi.c` which have been deprecated. Each deprecated function was deprecated in favor of its `multi` variant (e.g. `mipi_dsi_generic_write()` and `mipi_dsi_generic_write_multi()`). The `multi` variant of a function includes improved error handling and logic which makes it more convenient to make several calls in a row, as most MIPI drivers do.

Drivers should be updated to use undeprecated functions. Once all usages of the deprecated MIPI DSI functions have been removed, their definitions may be removed from `drm_mipi_dsi.c`.

Contact: Douglas Anderson &lt;[dianders@chromium.org](<mailto:dianders@chromium.org>)&gt;

Level: Starter

<a id="rst-remove-devm-drm-put-bridge"></a>

## Remove devm_drm_put_bridge()

Due to how the panel bridge handles the drm_bridge object lifetime, special care must be taken to dispose of the drm_bridge object when the panel_bridge is removed. This is currently managed using devm_drm_put_bridge(), but that is an unsafe, temporary workaround. To fix that, the DRM panel lifetime needs to be reworked. After the rework is done, remove devm_drm_put_bridge() and the TODO in drm_panel_bridge_remove().

- **Contact: Maxime Ripard &lt;[mripard@kernel.org](<mailto:mripard@kernel.org>)&gt;,**

  Luca Ceresoli &lt;[luca.ceresoli@bootlin.com](<mailto:luca.ceresoli@bootlin.com>)&gt;

Level: Intermediate

<a id="rst-convert-users-of-of-drm-find-bridge-to-of-drm-find-and-get-bridge"></a>

## Convert users of of_drm_find_bridge() to of_drm_find_and_get_bridge()

Taking a struct drm_bridge pointer requires getting a reference and putting it after disposing of the pointer. Most functions returning a struct drm_bridge pointer already call drm_bridge_get() to increment the refcount and their users have been updated to call drm_bridge_put() when appropriate. of_drm_find_bridge() does not get a reference and it has been deprecated in favor of of_drm_find_and_get_bridge() which does, but some users still need to be converted.

- **Contact: Maxime Ripard &lt;[mripard@kernel.org](<mailto:mripard@kernel.org>)&gt;,**

  Luca Ceresoli &lt;[luca.ceresoli@bootlin.com](<mailto:luca.ceresoli@bootlin.com>)&gt;

Level: Intermediate

<a id="rst-core-refactorings"></a>

### Core refactorings

<a id="rst-make-panic-handling-work"></a>

## Make panic handling work

This is a really varied tasks with lots of little bits and pieces:

- The panic path can't be tested currently, leading to constant breaking. The main issue here is that panics can be triggered from hardirq contexts and hence all panic related callback can run in hardirq context. It would be awesome if we could test at least the fbdev helper code and driver code by e.g. trigger calls through drm debugfs files. hardirq context could be achieved by using an IPI to the local processor.

- There's a massive confusion of different panic handlers. DRM fbdev emulation helpers had their own (long removed), but on top of that the fbcon code itself also has one. We need to make sure that they stop fighting over each other. This is worked around by checking `oops_in_progress` at various entry points into the DRM fbdev emulation helpers. A much cleaner approach here would be to switch fbcon to the [threaded printk support](<https://lwn.net/Articles/800946/>)<a id="rst-threaded-printk-support"></a>.

- `drm_can_sleep()` is a mess. It hides real bugs in normal operations and isn't a full solution for panic paths. We need to make sure that it only returns true if there's a panic going on for real, and fix up all the fallout.

- The panic handler must never sleep, which also means it can't ever `mutex_lock()`. Also it can't grab any other lock unconditionally, not even spinlocks (because NMI and hardirq can panic too). We need to either make sure to not call such paths, or trylock everything. Really tricky.

- A clean solution would be an entirely separate panic output support in KMS, bypassing the current fbcon support. See [\[PATCH v2 0/3\] drm: Add panic handling](<https://lore.kernel.org/dri-devel/20190311174218.51899-1-noralf@tronnes.org/>)<a id="rst-patch-v2-0-3-drm-add-panic-handling"></a>.

- Encoding the actual oops and preceding dmesg in a QR might help with the dread "important stuff scrolled away" problem. See [\[RFC\]\[PATCH\] Oops messages transfer using QR codes](<https://lore.kernel.org/lkml/1446217392-11981-1-git-send-email-alexandru.murtaza@intel.com/>)<a id="rst-rfc-patch-oops-messages-transfer-using-qr-codes"></a> for some example code that could be reused.

Contact: Simona Vetter

Level: Advanced

<a id="rst-clean-up-the-debugfs-support"></a>

## Clean up the debugfs support

There's a bunch of issues with it:

- Convert drivers to support the drm_debugfs_add_files() function instead of the drm_debugfs_create_files() function.

- Improve late-register debugfs by rolling out the same debugfs pre-register infrastructure for connector and crtc too. That way, the drivers won't need to split their setup code into init and register anymore.

- We probably want to have some support for debugfs files on crtc/connectors and maybe other kms objects directly in core. There's even drm_print support in the funcs for these objects to dump kms state, so it's all there. And then the -&gt;show() functions should obviously give you a pointer to the right object.

- The drm_driver-&gt;debugfs_init hooks we have is just an artifact of the old midlayered load sequence. DRM debugfs should work more like sysfs, where you can create properties/files for an object anytime you want, and the core takes care of publishing/unpuplishing all the files at register/unregister time. Drivers shouldn't need to worry about these technicalities, and fixing this (together with the drm_minor-&gt;drm_device move) would allow us to remove debugfs_init.

Contact: Simona Vetter

Level: Intermediate

<a id="rst-object-lifetime-fixes"></a>

## Object lifetime fixes

There's two related issues here

- Cleanup up the various -&gt;destroy callbacks, which often are all the same simple code.

- Lots of drivers erroneously allocate DRM modeset objects using devm_kzalloc, which results in use-after free issues on driver unload. This can be serious trouble even for drivers for hardware integrated on the SoC due to EPROBE_DEFERRED backoff.

Both these problems can be solved by switching over to drmm_kzalloc(), and the various convenience wrappers provided, e.g. drmm_crtc_alloc_with_planes(), drmm_universal_plane_alloc(), ... and so on.

Contact: Simona Vetter

Level: Intermediate

<a id="rst-remove-automatic-page-mapping-from-dma-buf-importing"></a>

## Remove automatic page mapping from dma-buf importing

When importing dma-bufs, the dma-buf and PRIME frameworks automatically map imported pages into the importer's DMA area. drm_gem_prime_fd_to_handle() and drm_gem_prime_handle_to_fd() require that importers call dma_buf_attach() even if they never do actual device DMA, but only CPU access through dma_buf_vmap(). This is a problem for USB devices, which do not support DMA operations.

To fix the issue, automatic page mappings should be removed from the buffer-sharing code. Fixing this is a bit more involved, since the import/export cache is also tied to &amp;drm_gem_object.import_attach. Meanwhile we paper over this problem for USB devices by fishing out the USB host controller device, as long as that supports DMA. Otherwise importing can still needlessly fail.

Contact: Thomas Zimmermann &lt;[tzimmermann@suse.de](<mailto:tzimmermann@suse.de>)&gt;, Simona Vetter

Level: Advanced

<a id="rst-implement-a-new-dumb-create2-ioctl"></a>

## Implement a new DUMB_CREATE2 ioctl

The current DUMB_CREATE ioctl is not well defined. Instead of a pixel and framebuffer format, it only accepts a color mode of vague semantics. Assuming a linear framebuffer, the color mode gives an idea of the supported pixel format. But userspace effectively has to guess the correct values. It really only works reliably with framebuffers in XRGB8888. Userspace has begun to workaround these limitations by computing arbitrary format's buffer sizes and calculating their sizes in terms of XRGB8888 pixels.

One possible solution is a new ioctl DUMB_CREATE2. It should accept a DRM format and a format modifier to resolve the color mode's ambiguity. As framebuffers can be multi-planar, the new ioctl has to return the buffer size, pitch and GEM handle for each individual color plane.

In the first step, the new ioctl can be limited to the current features of the existing DUMB_CREATE. Individual drivers can then be extended to support multi-planar formats. Rockchip might require this and would be a good candidate.

It might also be helpful to userspace to query information about the size of a potential buffer, if allocated. Userspace would supply geometry and format; the kernel would return minimal allocation sizes and scanline pitch. There is interest to allocate that memory from another device and provide it to the DRM driver (say via dma-buf).

Another requested feature is the ability to allocate a buffer by size, without format. Accelators use this for their buffer allocation and it could likely be generalized.

In addition to the kernel implementation, there must be user-space support for the new ioctl. There's code in Mesa that might be able to use the new call.

Contact: Thomas Zimmermann &lt;[tzimmermann@suse.de](<mailto:tzimmermann@suse.de>)&gt;

Level: Advanced

<a id="rst-better-testing"></a>

### Better Testing

<a id="rst-add-unit-tests-using-the-kernel-unit-testing-kunit-framework"></a>

## Add unit tests using the Kernel Unit Testing (KUnit) framework

The [KUnit](<https://www.kernel.org/doc/html/latest/dev-tools/kunit/index.html>)<a id="rst-kunit"></a> provides a common framework for unit tests within the Linux kernel. Having a test suite would allow to identify regressions earlier.

A good candidate for the first unit tests are the format-conversion helpers in `drm_format_helper.c`.

Contact: Javier Martinez Canillas &lt;[javierm@redhat.com](<mailto:javierm@redhat.com>)&gt;

Level: Intermediate

<a id="rst-clean-up-and-document-former-selftests-suites"></a>

## Clean up and document former selftests suites

Some KUnit test suites (drm_buddy, drm_cmdline_parser, drm_damage_helper, drm_format, drm_framebuffer, drm_dp_mst_helper, drm_mm, drm_plane_helper and drm_rect) are former selftests suites that have been converted over when KUnit was first introduced.

These suites were fairly undocumented, and with different goals than what unit tests can be. Trying to identify what each test in these suites actually test for, whether that makes sense for a unit test, and either remove it if it doesn't or document it if it does would be of great help.

Contact: Maxime Ripard &lt;[mripard@kernel.org](<mailto:mripard@kernel.org>)&gt;

Level: Intermediate

<a id="rst-enable-trinity-for-drm"></a>

## Enable trinity for DRM

And fix up the fallout. Should be really interesting ...

Level: Advanced

<a id="rst-make-kms-tests-in-i-g-t-generic"></a>

## Make KMS tests in i-g-t generic

The i915 driver team maintains an extensive testsuite for the i915 DRM driver, including tons of testcases for corner-cases in the modesetting API. It would be awesome if those tests (at least the ones not relying on Intel-specific GEM features) could be made to run on any KMS driver.

Basic work to run i-g-t tests on non-i915 is done, what's now missing is mass- converting things over. For modeset tests we also first need a bit of infrastructure to use dumb buffers for untiled buffers, to be able to run all the non-i915 specific modeset tests.

Level: Advanced

<a id="rst-extend-virtual-test-driver-vkms"></a>

## Extend virtual test driver (VKMS)

See the documentation of [VKMS](</kernel/hardware/gpu/vkms.md#rst-vkms>) for more details. This is an ideal internship task, since it only requires a virtual machine and can be sized to fit the available time.

Level: See details

<a id="rst-backlight-refactoring"></a>

## Backlight Refactoring

Backlight drivers have a triple enable/disable state, which is a bit overkill. Plan to fix this:

1. Roll out backlight_enable() and backlight_disable() helpers everywhere. This has started already.

2. In all, only look at one of the three status bits set by the above helpers.

3. Remove the other two status bits.

Contact: Simona Vetter

Level: Intermediate

<a id="rst-driver-specific"></a>

### Driver Specific

<a id="rst-amd-dc-display-driver"></a>

## AMD DC Display Driver

AMD DC is the display driver for AMD devices starting with Vega. There has been a bunch of progress cleaning it up but there's still plenty of work to be done.

See drivers/gpu/drm/amd/display/TODO for tasks.

Contact: Harry Wentland, Alex Deucher

<a id="rst-bootsplash"></a>

### Bootsplash

There is support in place now for writing internal DRM clients making it possible to pick up the bootsplash work that was rejected because it was written for fbdev.

- \[v6,8/8\] drm/client: Hack: Add bootsplash example [https://patchwork.freedesktop.org/patch/306579/](<https://patchwork.freedesktop.org/patch/306579/>)

- \[RFC PATCH v2 00/13\] Kernel based bootsplash [https://lore.kernel.org/r/20171213194755.3409-1-mstaudt@suse.de](<https://lore.kernel.org/r/20171213194755.3409-1-mstaudt@suse.de>)

Contact: Sam Ravnborg

Level: Advanced

<a id="rst-brightness-handling-on-devices-with-multiple-internal-panels"></a>

### Brightness handling on devices with multiple internal panels

On x86/ACPI devices there can be multiple backlight firmware interfaces: (ACPI) video, vendor specific and others. As well as direct/native (PWM) register programming by the KMS driver.

To deal with this backlight drivers used on x86/ACPI call acpi_video_get_backlight_type() which has heuristics (+quirks) to select which backlight interface to use; and backlight drivers which do not match the returned type will not register themselves, so that only one backlight device gets registered (in a single GPU setup, see below).

At the moment this more or less assumes that there will only be 1 (internal) panel on a system.

On systems with 2 panels this may be a problem, depending on what interface acpi_video_get_backlight_type() selects:

1. native: in this case the KMS driver is expected to know which backlight device belongs to which output so everything should just work.

2. video: this does support controlling multiple backlights, but some work will need to be done to get the output &lt;-&gt; backlight device mapping

The above assumes both panels will require the same backlight interface type. Things will break on systems with multiple panels where the 2 panels need a different type of control. E.g. one panel needs ACPI video backlight control, where as the other is using native backlight control. Currently in this case only one of the 2 required backlight devices will get registered, based on the acpi_video_get_backlight_type() return value.

If this (theoretical) case ever shows up, then supporting this will need some work. A possible solution here would be to pass a device and connector-name to acpi_video_get_backlight_type() so that it can deal with this.

Note in a way we already have a case where userspace sees 2 panels, in dual GPU laptop setups with a mux. On those systems we may see either 2 native backlight devices; or 2 native backlight devices.

Userspace already has code to deal with this by detecting if the related panel is active (iow which way the mux between the GPU and the panels points) and then uses that backlight device. Userspace here very much assumes a single panel though. It picks only 1 of the 2 backlight devices and then only uses that one.

Note that all userspace code (that I know off) is currently hardcoded to assume a single panel.

Before the recent changes to not register multiple (e.g. video + native) /sys/class/backlight devices for a single panel (on a single GPU laptop), userspace would see multiple backlight devices all controlling the same backlight.

To deal with this userspace had to always picks one preferred device under /sys/class/backlight and will ignore the others. So to support brightness control on multiple panels userspace will need to be updated too.

There are plans to allow brightness control through the KMS API by adding a "display brightness" property to drm_connector objects for panels. This solves a number of issues with the /sys/class/backlight API, including not being able to map a sysfs backlight device to a specific connector. Any userspace changes to add support for brightness control on devices with multiple panels really should build on top of this new KMS property.

Contact: Hans de Goede

Level: Advanced

<a id="rst-buffer-age-or-other-damage-accumulation-algorithm-for-buffer-damage"></a>

### Buffer age or other damage accumulation algorithm for buffer damage

Drivers that do per-buffer uploads, need a buffer damage handling (rather than frame damage like drivers that do per-plane or per-CRTC uploads), but there is no support to get the buffer age or any other damage accumulation algorithm.

For this reason, the damage helpers just fallback to a full plane update if the framebuffer attached to a plane has changed since the last page-flip. Drivers set &amp;drm_plane_state.ignore_damage_clips to true as indication to drm_atomic_helper_damage_iter_init() and drm_atomic_helper_damage_iter_next() helpers that the damage clips should be ignored.

This should be improved to get damage tracking properly working on drivers that do per-buffer uploads.

More information about damage tracking and references to learning materials can be found in [damage_tracking_properties](<https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/Documentation/gpu/drm-kms.rst?id=9021cc14f7d98b4a1d2c932f52c5343d4d0f6b92>).

Contact: Javier Martinez Canillas &lt;[javierm@redhat.com](<mailto:javierm@redhat.com>)&gt;

Level: Advanced

<a id="rst-querying-errors-from-drm-syncobj"></a>

### Querying errors from drm_syncobj

The drm_syncobj container can be used by driver independent code to signal complection of submission.

One minor feature still missing is a generic DRM IOCTL to query the error status of binary and timeline drm_syncobj.

This should probably be improved by implementing the necessary kernel interface and adding support for that in the userspace stack.

Contact: Christian König

Level: Starter

<a id="rst-drm-gpu-scheduler"></a>

### DRM GPU Scheduler

<a id="rst-provide-a-universal-successor-for-drm-sched-resubmit-jobs"></a>

## Provide a universal successor for drm_sched_resubmit_jobs()

drm_sched_resubmit_jobs() is deprecated. Main reason being that it leads to reinitializing dma_fences. See that function's docu for details. The better approach for valid resubmissions by amdgpu and Xe is (apparently) to figure out which job (and, through association: which entity) caused the hang. Then, the job's buffer data, together with all other jobs' buffer data currently in the same hardware ring, must be invalidated. This can for example be done by overwriting it. amdgpu currently determines which jobs are in the ring and need to be overwritten by keeping copies of the job. Xe obtains that information by directly accessing drm_sched's pending_list.

Tasks:

1. implement scheduler functionality through which the driver can obtain the information which *broken* jobs are currently in the hardware ring.

2. Such infrastructure would then typically be used in drm_sched_backend_ops.timedout_job(). Document that.

3. Port a driver as first user.

4. Document the new alternative in the docu of deprecated drm_sched_resubmit_jobs().

- **Contact: Christian König &lt;[christian.koenig@amd.com](<mailto:christian.koenig@amd.com>)&gt;**

  Philipp Stanner &lt;[phasta@kernel.org](<mailto:phasta@kernel.org>)&gt;

Level: Advanced

<a id="rst-add-locking-for-runqueues"></a>

## Add locking for runqueues

There is an old FIXME by Sima in include/drm/gpu_scheduler.h. It details that struct drm_sched_rq is read at many places without any locks, not even with a READ_ONCE. At XDC 2025 no one could really tell why that is the case, whether locks are needed and whether they could be added. (But for real, that should probably be locked\!). Check whether it's possible to add locks everywhere, and do so if yes.

Contact: Philipp Stanner &lt;[phasta@kernel.org](<mailto:phasta@kernel.org>)&gt;

Level: Intermediate

<a id="rst-outside-drm"></a>

### Outside DRM

<a id="rst-convert-fbdev-drivers-to-drm"></a>

## Convert fbdev drivers to DRM

There are plenty of fbdev drivers for older hardware. Some hardware has become obsolete, but some still provides good(-enough) framebuffers. The drivers that are still useful should be converted to DRM and afterwards removed from fbdev.

Very simple fbdev drivers can best be converted by starting with a new DRM driver. Simple KMS helpers and SHMEM should be able to handle any existing hardware. The new driver's call-back functions are filled from existing fbdev code.

More complex fbdev drivers can be refactored step-by-step into a DRM driver with the help of the DRM fbconv helpers <a id="rst-footnote-reference-4"></a>[4](#rst-footnote-4). These helpers provide the transition layer between the DRM core infrastructure and the fbdev driver interface. Create a new DRM driver on top of the fbconv helpers, copy over the fbdev driver, and hook it up to the DRM code. Examples for several fbdev drivers are available in Thomas Zimmermann's fbconv tree <a id="rst-footnote-reference-5"></a>[4](#rst-footnote-4), as well as a tutorial of this process <a id="rst-footnote-reference-6"></a>[5](#rst-footnote-5). The result is a primitive DRM driver that can run X11 and Weston.

> <a id="rst-footnote-4"></a>
>
>
>
> **[4]** [https://gitlab.freedesktop.org/tzimmermann/linux/tree/fbconv](<https://gitlab.freedesktop.org/tzimmermann/linux/tree/fbconv>)
>
> <a id="rst-footnote-5"></a>
>
>
>
> **[5]** [https://gitlab.freedesktop.org/tzimmermann/linux/blob/fbconv/drivers/gpu/drm/drm_fbconv_helper.c](<https://gitlab.freedesktop.org/tzimmermann/linux/blob/fbconv/drivers/gpu/drm/drm_fbconv_helper.c>)

Contact: Thomas Zimmermann &lt;[tzimmermann@suse.de](<mailto:tzimmermann@suse.de>)&gt;

Level: Advanced

---

# drm/tve200 Faraday TV Encoder 200

_Peios Kernel / Hardware and drivers / Graphics_

> Reference for drm/tve200 Faraday TV Encoder 200.

<a id="rst-drm-tve200-faraday-tv-encoder-200"></a>


The Faraday TV Encoder TVE200 is also known as the Gemini TV Interface
Controller (TVC) and is found in the Gemini Chipset from Storlink
Semiconductor (later Storm Semiconductor, later Cortina Systems)
but also in the Grain Media GM8180 chipset. On the Gemini the module
is connected to 8 data lines and a single clock line, comprising an
8-bit BT.656 interface.

This is a very basic YUV display driver. The datasheet specifies that
it supports the ITU BT.656 standard. It requires a 27 MHz clock which is
the hallmark of any TV encoder supporting both PAL and NTSC.

This driver exposes a standard KMS interface for this TV encoder.

---

# drm/v3d Broadcom V3D Graphics Driver

_Peios Kernel / Hardware and drivers / Graphics_

> Reference for drm/v3d Broadcom V3D Graphics Driver.

<a id="rst-drm-v3d-broadcom-v3d-graphics-driver"></a>


This driver supports the Broadcom V3D 3.3 and 4.1 OpenGL ES GPUs.
For V3D 2.x support, see the VC4 driver.

The V3D GPU includes a tiled render (composed of a bin and render
pipelines), the TFU (texture formatting unit), and the CSD (compute
shader dispatch).


<a id="rst-gpu-buffer-object-bo-management"></a>

## GPU buffer object (BO) management


Compared to VC4 (V3D 2.x), V3D 3.3 introduces an MMU between the
GPU and the bus, allowing us to use shmem objects for our storage
instead of CMA.

Physically contiguous objects may still be imported to V3D, but the
driver doesn't allocate physically contiguous objects on its own.
Display engines requiring physically contiguous allocations should
look into Mesa's "renderonly" support (as used by the Mesa pl111
driver) for an example of how to integrate with V3D.


<a id="rst-address-space-management"></a>

### Address space management


The V3D 3.x hardware (compared to VC4) now includes an MMU. It has
a single level of page tables for the V3D's 4GB address space to
map to AXI bus addresses, thus it could need up to 4MB of
physically contiguous memory to store the PTEs.

Because the 4MB of contiguous memory for page tables is precious,
and switching between them is expensive, we load all BOs into the
same 4GB address space.

To protect clients from each other, we should use the GMP to
quickly mask out (at 128kb granularity) what pages are available to
each client. This is not yet implemented.


<a id="rst-gpu-scheduling"></a>

### GPU Scheduling


The shared DRM GPU scheduler is used to coordinate submitting jobs
to the hardware. Each DRM fd (roughly a client process) gets its
own scheduler entity, which will process jobs in order. The GPU
scheduler will schedule the clients with a FIFO scheduling algorithm.

For simplicity, and in order to keep latency low for interactive
jobs when bulk background jobs are queued up, we submit a new job
to the HW only when it has completed the last one, instead of
filling up the CT\[01\]Q FIFOs with jobs. Similarly, we use
`drm_sched_job_add_dependency()` to manage the dependency between bin
and render, instead of having the clients submit jobs using the HW's
semaphores to interlock between them.


<a id="rst-interrupts"></a>

## Interrupts


When we take a bin, render, TFU done, or CSD done interrupt, we
need to signal the fence for that job so that the scheduler can
queue up the next one and unblock any waiters.

When we take the binner out of memory interrupt, we need to
allocate some new memory and pass it to the binner so that the
current job can make progress.

---

# drm/vc4 Broadcom VC4 Graphics Driver

_Peios Kernel / Hardware and drivers / Graphics_

> This section covers everything related to the display hardware including the mode setting infrastructure, plane, sprite and cursor handling and display, output probing and related topics.

<a id="rst-drm-vc4-broadcom-vc4-graphics-driver"></a>


The Broadcom VideoCore 4 (present in the Raspberry Pi) contains a
OpenGL ES 2.0-compatible 3D engine called V3D, and a highly
configurable display output pipeline that supports HDMI, DSI, DPI,
and Composite TV output.

The 3D engine also has an interface for submitting arbitrary
compute shader-style jobs using the same shader processor as is
used for vertex and fragment shaders in GLES 2.0.  However, given
that the hardware isn't able to expose any standard interfaces like
OpenGL compute shaders or OpenCL, it isn't supported by this
driver.


<a id="rst-display-hardware-handling"></a>

## Display Hardware Handling

This section covers everything related to the display hardware including the mode setting infrastructure, plane, sprite and cursor handling and display, output probing and related topics.

<a id="rst-pixel-valve-drm-crtc"></a>

### Pixel Valve (DRM CRTC)


In VC4, the Pixel Valve is what most closely corresponds to the
DRM's concept of a CRTC.  The PV generates video timings from the
encoder's clock plus its configuration.  It pulls scaled pixels from
the HVS at that timing, and feeds it to the encoder.

However, the DRM CRTC also collects the configuration of all the
DRM planes attached to it.  As a result, the CRTC is also
responsible for writing the display list for the HVS channel that
the CRTC will use.

The 2835 has 3 different pixel valves.  pv0 in the audio power
domain feeds DSI0 or DPI, while pv1 feeds DS1 or SMI.  pv2 in the
image domain can feed either HDMI or the SDTV controller.  The
pixel valve chooses from the CPRMAN clocks (HSM for HDMI, VEC for
SDTV, etc.) according to which output type is chosen in the mux.

For power management, the pixel valve's registers are all clocked
by the AXI clock, while the timings and FIFOs make use of the
output-specific clock.  Since the encoders also directly consume
the CPRMAN clocks, and know what timings they need, they are the
ones that set the clock.


<a id="rst-hvs"></a>

### HVS


The Hardware Video Scaler (HVS) is the piece of hardware that does
translation, scaling, colorspace conversion, and compositing of
pixels stored in framebuffers into a FIFO of pixels going out to
the Pixel Valve (CRTC).  It operates at the system clock rate (the
system audio clock gate, specifically), which is much higher than
the pixel clock rate.

There is a single global HVS, with multiple output FIFOs that can
be consumed by the PVs.  This file just manages the resources for
the HVS, while the vc4_crtc.c code actually drives HVS setup for
each CRTC.


<a id="rst-hvs-planes"></a>

### HVS planes


Each DRM plane is a layer of pixels being scanned out by the HVS.

At atomic modeset check time, we compute the HVS display element
state that would be necessary for displaying the plane (giving us a
chance to figure out if a plane configuration is invalid), then at
atomic flush time the CRTC will ask us to write our element state
into the region of the HVS that it has allocated for us.


<a id="rst-hdmi-encoder"></a>

### HDMI encoder


The HDMI core has a state machine and a PHY.  On BCM2835, most of
the unit operates off of the HSM clock from CPRMAN.  It also
internally uses the PLLH_PIX clock for the PHY.

HDMI infoframes are kept within a small packet ram, where each
packet can be individually enabled for including in a frame.

HDMI audio is implemented entirely within the HDMI IP block.  A
register in the HDMI encoder takes SPDIF frames from the DMA engine
and transfers them over an internal MAI (multi-channel audio
interconnect) bus to the encoder side for insertion into the video
blank regions.

The driver's HDMI encoder does not yet support power management.
The HDMI encoder's power domain and the HSM/pixel clocks are kept
continuously running, and only the HDMI logic and packet ram are
powered off/on at disable/enable time.

The driver does not yet support CEC control, though the HDMI
encoder block has CEC support.


<a id="rst-dsi-encoder"></a>

### DSI encoder


BCM2835 contains two DSI modules, DSI0 and DSI1.  DSI0 is a
single-lane DSI controller, while DSI1 is a more modern 4-lane DSI
controller.

Most Raspberry Pi boards expose DSI1 as their "DISPLAY" connector,
while the compute module brings both DSI0 and DSI1 out.

This driver has been tested for DSI1 video-mode display only
currently, with most of the information necessary for DSI0
hopefully present.


<a id="rst-dpi-encoder"></a>

### DPI encoder


The VC4 DPI hardware supports MIPI DPI type 4 and Nokia ViSSI
signals.  On BCM2835, these can be routed out to GPIO0-27 with the
ALT2 function.


<a id="rst-vec-composite-tv-out-encoder"></a>

### VEC (Composite TV out) encoder


The VEC encoder generates PAL or NTSC composite video output.

TV mode selection is done by an atomic property on the encoder,
because a drm_mode_modeinfo is insufficient to distinguish between
PAL and PAL-M or NTSC and NTSC-J.


<a id="rst-kunit-tests"></a>

## KUnit Tests

The VC4 Driver uses KUnit to perform driver-specific unit and integration tests.

These tests are using a mock driver and can be ran using the command below, on either arm or arm64 architectures,



```bash
$ ./tools/testing/kunit/kunit.py run \
        --kunitconfig=drivers/gpu/drm/vc4/tests/.kunitconfig \
        --cross_compile aarch64-linux-gnu- --arch arm64
```

- **Parts of the driver that are currently covered by tests are:**

  - The HVS to PixelValve dynamic FIFO assignment, for the BCM2835-7 and BCM2711.

<a id="rst-memory-management-and-3d-command-submission"></a>

## Memory Management and 3D Command Submission

This section covers the GEM implementation in the vc4 driver.

<a id="rst-gpu-buffer-object-bo-management"></a>

### GPU buffer object (BO) management


The VC4 GPU architecture (both scanout and rendering) has direct
access to system memory with no MMU in between.  To support it, we
use the GEM DMA helper functions to allocate contiguous ranges of
physical memory for our BOs.

Since the DMA allocator is very slow, we keep a cache of recently
freed BOs around so that the kernel's allocation of objects for 3D
rendering can return quickly.


<a id="rst-v3d-binner-command-list-bcl-validation"></a>

### V3D binner command list (BCL) validation


Since the VC4 has no IOMMU between it and system memory, a user
with access to execute command lists could escalate privilege by
overwriting system memory (drawing to it as a framebuffer) or
reading system memory it shouldn't (reading it as a vertex buffer
or index buffer)

We validate binner command lists to ensure that all accesses are
within the bounds of the GEM objects referenced by the submitted
job.  It explicitly whitelists packets, and looks at the offsets in
any address fields to make sure they're contained within the BOs
they reference.

Note that because CL validation is already reading the
user-submitted CL and writing the validated copy out to the memory
that the GPU will actually read, this is also where GEM relocation
processing (turning BO references into actual addresses for the GPU
to use) happens.


<a id="rst-v3d-render-command-list-rcl-generation"></a>

### V3D render command list (RCL) generation


In the V3D hardware, render command lists are what load and store
tiles of a framebuffer and optionally call out to binner-generated
command lists to do the 3D drawing for that tile.

In the VC4 driver, render command list generation is performed by the
kernel instead of userspace.  We do this because validating a
user-submitted command list is hard to get right and has high CPU overhead,
while the number of valid configurations for render command lists is
actually fairly low.


<a id="rst-shader-validator-for-vc4"></a>

### Shader validator for VC4


Since the VC4 has no IOMMU between it and system memory, a user
with access to execute shaders could escalate privilege by
overwriting system memory (using the VPM write address register in
the general-purpose DMA mode) or reading system memory it shouldn't
(reading it as a texture, uniform data, or direct-addressed TMU
lookup).

The shader validator walks over a shader's BO, ensuring that its
accesses are appropriately bounded, and recording where texture
accesses are made so that we can do relocations for them in the
uniform stream.

Shader BO are immutable for their lifetimes (enforced by not
allowing mmaps, GEM prime export, or rendering to from a CL), so
this validation is only performed at BO creation time.


<a id="rst-v3d-interrupts"></a>

### V3D Interrupts


We have an interrupt status register (V3D_INTCTL) which reports
interrupts, and where writing 1 bits clears those interrupts.
There are also a pair of interrupt registers
(V3D_INTENA/V3D_INTDIS) where writing a 1 to their bits enables or
disables that specific interrupt, and 0s written are ignored
(reading either one returns the set of enabled interrupts).

When we take a binning flush done interrupt, we need to submit the
next frame for binning and move the finished frame to the render
thread.

When we take a render frame interrupt, we need to wake the
processes waiting for some frame to be done, and get the next frame
submitted ASAP (so the hardware doesn't sit idle when there's work
to do).

When we take the binner out of memory interrupt, we need to
allocate some new memory and pass it to the binner so that the
current job can make progress.

---

# VGA Switcheroo

_Peios Kernel / Hardware and drivers / Graphics_

> Duplicate implicit target name: "public functions".

<a id="rst-vga-switcheroo-1"></a>
<a id="rst-vga-switcheroo"></a>


vga_switcheroo is the Linux subsystem for laptop hybrid graphics.
These come in two flavors:

* muxed: Dual GPUs with a multiplexer chip to switch outputs between GPUs.
* muxless: Dual GPUs but only one of them is connected to outputs.
  The other one is merely used to offload rendering, its results
  are copied over PCIe into the framebuffer. On Linux this is
  supported with DRI PRIME.

Hybrid graphics started to appear in the late Naughties and were initially
all muxed. Newer laptops moved to a muxless architecture for cost reasons.
A notable exception is the MacBook Pro which continues to use a mux.
Muxes come with varying capabilities: Some switch only the panel, others
can also switch external displays. Some switch all display pins at once
while others can switch just the DDC lines. (To allow EDID probing
for the inactive GPU.) Also, muxes are often used to cut power to the
discrete GPU while it is not used.

DRM drivers register GPUs with vga_switcheroo, these are henceforth called
clients. The mux is called the handler. Muxless machines also register a
handler to control the power state of the discrete GPU, its ->switchto
callback is a no-op for obvious reasons. The discrete GPU is often equipped
with an HDA controller for the HDMI/DP audio signal, this will also
register as a client so that vga_switcheroo can take care of the correct
suspend/resume order when changing the discrete GPU's power state. In total
there can thus be up to three clients: Two vga clients (GPUs) and one audio
client (on the discrete GPU). The code is mostly prepared to support
machines with more than two GPUs should they become available.

The GPU to which the outputs are currently switched is called the
active client in vga_switcheroo parlance. The GPU not in use is the
inactive client. When the inactive client's DRM driver is loaded,
it will be unable to probe the panel's EDID and hence depends on
VBIOS to provide its display modes. If the VBIOS modes are bogus or
if there is no VBIOS at all (which is common on the MacBook Pro),
a client may alternatively request that the DDC lines are temporarily
switched to it, provided that the handler supports this. Switching
only the DDC lines and not the entire output avoids unnecessary
flickering.


<a id="rst-modes-of-use"></a>

## Modes of Use

<a id="rst-manual-switching-and-manual-power-control"></a>

### Manual switching and manual power control


In this mode of use, the file /sys/kernel/debug/vgaswitcheroo/switch
can be read to retrieve the current vga_switcheroo state and commands
can be written to it to change the state. The file appears as soon as
two GPU drivers and one handler have registered with vga_switcheroo.
The following commands are understood:

* OFF: Power off the device not in use.
* ON: Power on the device not in use.
* IGD: Switch to the integrated graphics device.
  Power on the integrated GPU if necessary, power off the discrete GPU.
  Prerequisite is that no user space processes (e.g. Xorg, alsactl)
  have opened device files of the GPUs or the audio client. If the
  switch fails, the user may invoke lsof(8) or fuser(1) on /dev/dri/
  and /dev/snd/controlC1 to identify processes blocking the switch.
* DIS: Switch to the discrete graphics device.
* DIGD: Delayed switch to the integrated graphics device.
  This will perform the switch once the last user space process has
  closed the device files of the GPUs and the audio client.
* DDIS: Delayed switch to the discrete graphics device.
* MIGD: Mux-only switch to the integrated graphics device.
  Does not remap console or change the power state of either gpu.
  If the integrated GPU is currently off, the screen will turn black.
  If it is on, the screen will show whatever happens to be in VRAM.
  Either way, the user has to blindly enter the command to switch back.
* MDIS: Mux-only switch to the discrete graphics device.

For GPUs whose power state is controlled by the driver's runtime pm,
the ON and OFF commands are a no-op (see next section).

For muxless machines, the IGD/DIS, DIGD/DDIS and MIGD/MDIS commands
should not be used.


<a id="rst-driver-power-control"></a>

### Driver power control


In this mode of use, the discrete GPU automatically powers up and down at
the discretion of the driver's runtime pm. On muxed machines, the user may
still influence the muxer state by way of the debugfs interface, however
the ON and OFF commands become a no-op for the discrete GPU.

This mode is the default on Nvidia HybridPower/Optimus and ATI PowerXpress.
Specifying nouveau.runpm=0, radeon.runpm=0 or amdgpu.runpm=0 on the kernel
command line disables it.

After the GPU has been suspended, the handler needs to be called to cut
power to the GPU. Likewise it needs to reinstate power before the GPU
can resume. This is achieved by [`vga_switcheroo_init_domain_pm_ops()`](#c-vga_switcheroo_init_domain_pm_ops),
which augments the GPU's suspend/resume functions by the requisite
calls to the handler.

When the audio device resumes, the GPU needs to be woken. This is achieved
by a PCI quirk which calls [`device_link_add()`](/kernel/hardware/driver-api/fundamentals/infrastructure.md#c-device_link_add) to declare a dependency on the
GPU. That way, the GPU is kept awake whenever and as long as the audio
device is in use.

On muxed machines, if the mux is initially switched to the discrete GPU,
the user ends up with a black screen when the GPU powers down after boot.
As a workaround, the mux is forced to the integrated GPU on runtime suspend,
cf. https://bugs.freedesktop.org/show_bug.cgi?id=75917


<a id="rst-api"></a>

## API

<a id="rst-public-functions"></a>

### Public functions


#### <a id="c-vga_switcheroo_register_handler"></a>`vga_switcheroo_register_handler()`

```c
int vga_switcheroo_register_handler(const struct vga_switcheroo_handler *handler, enum vga_switcheroo_handler_flags_t handler_flags)
```

register handler

**Parameters**

- `const struct vga_switcheroo_handler *handler`: handler callbacks
- `enum vga_switcheroo_handler_flags_t handler_flags`: handler flags

**Description**

Register handler. Enable vga_switcheroo if two vga clients have already
registered.

**Return**

0 on success, -EINVAL if a handler was already registered.

#### <a id="c-vga_switcheroo_unregister_handler"></a>`vga_switcheroo_unregister_handler()`

```c
void vga_switcheroo_unregister_handler(void)
```

unregister handler

**Parameters**

- `void`: no arguments

**Description**

Unregister handler. Disable vga_switcheroo.

#### <a id="c-vga_switcheroo_handler_flags"></a>`vga_switcheroo_handler_flags()`

```c
enum vga_switcheroo_handler_flags_t vga_switcheroo_handler_flags(void)
```

obtain handler flags

**Parameters**

- `void`: no arguments

**Description**

Helper for clients to obtain the handler flags bitmask.

**Return**

Handler flags. A value of 0 means that no handler is registered
or that the handler has no special capabilities.

#### <a id="c-vga_switcheroo_register_client"></a>`vga_switcheroo_register_client()`

```c
int vga_switcheroo_register_client(struct pci_dev *pdev, const struct vga_switcheroo_client_ops *ops, bool driver_power_control)
```

register vga client

**Parameters**

- `struct pci_dev *pdev`: client pci device
- `const struct vga_switcheroo_client_ops *ops`: client callbacks
- `bool driver_power_control`: whether power state is controlled by the driver's
  runtime pm

**Description**

Register vga client (GPU). Enable vga_switcheroo if another GPU and a
handler have already registered. The power state of the client is assumed
to be ON. Beforehand, [`vga_switcheroo_client_probe_defer()`](#c-vga_switcheroo_client_probe_defer) shall be called
to ensure that all prerequisites are met.

**Return**

0 on success, -ENOMEM on memory allocation error.

#### <a id="c-vga_switcheroo_register_audio_client"></a>`vga_switcheroo_register_audio_client()`

```c
int vga_switcheroo_register_audio_client(struct pci_dev *pdev, const struct vga_switcheroo_client_ops *ops, struct pci_dev *vga_dev)
```

register audio client

**Parameters**

- `struct pci_dev *pdev`: client pci device
- `const struct vga_switcheroo_client_ops *ops`: client callbacks
- `struct pci_dev *vga_dev`: pci device which is bound to current audio client

**Description**

Register audio client (audio device on a GPU). The client is assumed
to use runtime PM. Beforehand, [`vga_switcheroo_client_probe_defer()`](#c-vga_switcheroo_client_probe_defer)
shall be called to ensure that all prerequisites are met.

**Return**

0 on success, -ENOMEM on memory allocation error, -EINVAL on getting
client id error.

#### <a id="c-vga_switcheroo_client_probe_defer"></a>`vga_switcheroo_client_probe_defer()`

```c
bool vga_switcheroo_client_probe_defer(struct pci_dev *pdev)
```

whether to defer probing a given client

**Parameters**

- `struct pci_dev *pdev`: client pci device

**Description**

Determine whether any prerequisites are not fulfilled to probe a given
client. Drivers shall invoke this early on in their ->probe callback
and return `-EPROBE_DEFER` if it evaluates to `true`. Thou shalt not
register the client ere thou hast called this.

**Return**

`true` if probing should be deferred, otherwise `false`.

#### <a id="c-vga_switcheroo_get_client_state"></a>`vga_switcheroo_get_client_state()`

```c
enum vga_switcheroo_state vga_switcheroo_get_client_state(struct pci_dev *pdev)
```

obtain power state of a given client

**Parameters**

- `struct pci_dev *pdev`: client pci device

**Description**

Obtain power state of a given client as seen from vga_switcheroo.
The function is only called from hda_intel.c.

**Return**

Power state.

#### <a id="c-vga_switcheroo_unregister_client"></a>`vga_switcheroo_unregister_client()`

```c
void vga_switcheroo_unregister_client(struct pci_dev *pdev)
```

unregister client

**Parameters**

- `struct pci_dev *pdev`: client pci device

**Description**

Unregister client. Disable vga_switcheroo if this is a vga client (GPU).

#### <a id="c-vga_switcheroo_client_fb_set"></a>`vga_switcheroo_client_fb_set()`

```c
void vga_switcheroo_client_fb_set(struct pci_dev *pdev, struct fb_info *info)
```

set framebuffer of a given client

**Parameters**

- `struct pci_dev *pdev`: client pci device
- `struct fb_info *info`: framebuffer

**Description**

Set framebuffer of a given client. The console will be remapped to this
on switching.

#### <a id="c-vga_switcheroo_lock_ddc"></a>`vga_switcheroo_lock_ddc()`

```c
int vga_switcheroo_lock_ddc(struct pci_dev *pdev)
```

temporarily switch DDC lines to a given client

**Parameters**

- `struct pci_dev *pdev`: client pci device

**Description**

Temporarily switch DDC lines to the client identified by **pdev**
(but leave the outputs otherwise switched to where they are).
This allows the inactive client to probe EDID. The DDC lines must
afterwards be switched back by calling [`vga_switcheroo_unlock_ddc()`](#c-vga_switcheroo_unlock_ddc),
even if this function returns an error.

**Return**

Previous DDC owner on success or a negative int on error.
Specifically, `-ENODEV` if no handler has registered or if the handler
does not support switching the DDC lines. Also, a negative value
returned by the handler is propagated back to the caller.
The return value has merely an informational purpose for any caller
which might be interested in it. It is acceptable to ignore the return
value and simply rely on the result of the subsequent EDID probe,
which will be `NULL` if DDC switching failed.

#### <a id="c-vga_switcheroo_unlock_ddc"></a>`vga_switcheroo_unlock_ddc()`

```c
int vga_switcheroo_unlock_ddc(struct pci_dev *pdev)
```

switch DDC lines back to previous owner

**Parameters**

- `struct pci_dev *pdev`: client pci device

**Description**

Switch DDC lines back to the previous owner after calling
[`vga_switcheroo_lock_ddc()`](#c-vga_switcheroo_lock_ddc). This must be called even if
[`vga_switcheroo_lock_ddc()`](#c-vga_switcheroo_lock_ddc) returned an error.

**Return**

Previous DDC owner on success (i.e. the client identifier of **pdev**)
or a negative int on error.
Specifically, `-ENODEV` if no handler has registered or if the handler
does not support switching the DDC lines. Also, a negative value
returned by the handler is propagated back to the caller.
Finally, invoking this function without calling [`vga_switcheroo_lock_ddc()`](#c-vga_switcheroo_lock_ddc)
first is not allowed and will result in `-EINVAL`.

#### <a id="c-vga_switcheroo_process_delayed_switch"></a>`vga_switcheroo_process_delayed_switch()`

```c
int vga_switcheroo_process_delayed_switch(void)
```

helper for delayed switching

**Parameters**

- `void`: no arguments

**Description**

Process a delayed switch if one is pending.

**Return**

0 on success. -EINVAL if no delayed switch is pending, if the client
has unregistered in the meantime or if there are other clients blocking the
switch. If the actual switch fails, an error is reported and 0 is returned.

#### <a id="c-vga_switcheroo_init_domain_pm_ops"></a>`vga_switcheroo_init_domain_pm_ops()`

```c
int vga_switcheroo_init_domain_pm_ops(struct device *dev, struct dev_pm_domain *domain)
```

helper for driver power control

**Parameters**

- `struct device *dev`: vga client device
- `struct dev_pm_domain *domain`: power domain

**Description**

Helper for GPUs whose power state is controlled by the driver's runtime pm.
After the GPU has been suspended, the handler needs to be called to cut
power to the GPU. Likewise it needs to reinstate power before the GPU
can resume. To this end, this helper augments the suspend/resume functions
by the requisite calls to the handler. It needs only be called on platforms
where the power switch is separate to the device being powered down.


<a id="rst-public-structures"></a>

### Public structures


#### <a id="c-struct-vga_switcheroo_handler"></a>`struct vga_switcheroo_handler`

handler callbacks

**Definition**

```c
struct vga_switcheroo_handler {
    int (*init)(void);
    int (*switchto)(enum vga_switcheroo_client_id id);
    int (*switch_ddc)(enum vga_switcheroo_client_id id);
    int (*power_state)(enum vga_switcheroo_client_id id, enum vga_switcheroo_state state);
    enum vga_switcheroo_client_id (*get_client_id)(struct pci_dev *pdev);
};
```

**Members**

- `init`: initialize handler.
  Optional. This gets called when vga_switcheroo is enabled, i.e. when
  two vga clients have registered. It allows the handler to perform
  some delayed initialization that depends on the existence of the
  vga clients. Currently only the radeon and amdgpu drivers use this.
  The return value is ignored
- `switchto`: switch outputs to given client.
  Mandatory. For muxless machines this should be a no-op. Returning 0
  denotes success, anything else failure (in which case the switch is
  aborted)
- `switch_ddc`: switch DDC lines to given client.
  Optional. Should return the previous DDC owner on success or a
  negative int on failure
- `power_state`: cut or reinstate power of given client.
  Optional. The return value is ignored
- `get_client_id`: determine if given pci device is integrated or discrete GPU.
  Mandatory

**Description**

Handler callbacks. The multiplexer itself. The **switchto** and **get_client_id**
methods are mandatory, all others may be set to NULL.



#### <a id="c-struct-vga_switcheroo_client_ops"></a>`struct vga_switcheroo_client_ops`

client callbacks

**Definition**

```c
struct vga_switcheroo_client_ops {
    void (*set_gpu_state)(struct pci_dev *dev, enum vga_switcheroo_state);
    void (*reprobe)(struct pci_dev *dev);
    bool (*can_switch)(struct pci_dev *dev);
    void (*gpu_bound)(struct pci_dev *dev, enum vga_switcheroo_client_id);
};
```

**Members**

- `set_gpu_state`: do the equivalent of suspend/resume for the card.
  Mandatory. This should not cut power to the discrete GPU,
  which is the job of the handler
- `reprobe`: poll outputs.
  Optional. This gets called after waking the GPU and switching
  the outputs to it
- `can_switch`: check if the device is in a position to switch now.
  Mandatory. The client should return false if a user space process
  has one of its device files open
- `gpu_bound`: notify the client id to audio client when the GPU is bound.

**Description**

Client callbacks. A client can be either a GPU or an audio device on a GPU.
The **set_gpu_state** and **can_switch** methods are mandatory, **reprobe** may be
set to NULL. For audio clients, the **reprobe** member is bogus.
OTOH, **gpu_bound** is only for audio clients, and not used for GPU clients.


<a id="rst-public-constants"></a>

### Public constants


#### <a id="c-enum-vga_switcheroo_handler_flags_t"></a>`enum vga_switcheroo_handler_flags_t`

handler flags bitmask

**Constants**

- `VGA_SWITCHEROO_CAN_SWITCH_DDC`: whether the handler is able to switch the
  DDC lines separately. This signals to clients that they should call
  [`drm_get_edid_switcheroo()`](/kernel/hardware/gpu/drm-kms-helpers.md#c-drm_get_edid_switcheroo) to probe the EDID
- `VGA_SWITCHEROO_NEEDS_EDP_CONFIG`: whether the handler is unable to switch
  the AUX channel separately. This signals to clients that the active
  GPU needs to train the link and communicate the link parameters to the
  inactive GPU (mediated by vga_switcheroo). The inactive GPU may then
  skip the AUX handshake and set up its output with these pre-calibrated
  values (DisplayPort specification v1.1a, section 2.5.3.3)

**Description**

Handler flags bitmask. Used by handlers to declare their capabilities upon
registering with vga_switcheroo.



#### <a id="c-enum-vga_switcheroo_client_id"></a>`enum vga_switcheroo_client_id`

client identifier

**Constants**

- `VGA_SWITCHEROO_UNKNOWN_ID`: initial identifier assigned to vga clients.
  Determining the id requires the handler, so GPUs are given their
  true id in a delayed fashion in `vga_switcheroo_enable()`
- `VGA_SWITCHEROO_IGD`: integrated graphics device
- `VGA_SWITCHEROO_DIS`: discrete graphics device
- `VGA_SWITCHEROO_MAX_CLIENTS`: currently no more than two GPUs are supported

**Description**

Client identifier. Audio clients use the same identifier & 0x100.



#### <a id="c-enum-vga_switcheroo_state"></a>`enum vga_switcheroo_state`

client power state

**Constants**

- `VGA_SWITCHEROO_OFF`: off
- `VGA_SWITCHEROO_ON`: on
- `VGA_SWITCHEROO_NOT_FOUND`: client has not registered with vga_switcheroo.
  Only used in [`vga_switcheroo_get_client_state()`](#c-vga_switcheroo_get_client_state) which in turn is only
  called from hda_intel.c

**Description**

Client power state.


<a id="rst-private-structures"></a>

### Private structures


#### <a id="c-struct-vgasr_priv"></a>`struct vgasr_priv`

vga_switcheroo private data

**Definition**

```c
struct vgasr_priv {
    bool active;
    bool delayed_switch_active;
    enum vga_switcheroo_client_id delayed_client_id;
    struct dentry *debugfs_root;
    int registered_clients;
    struct list_head clients;
    const struct vga_switcheroo_handler *handler;
    enum vga_switcheroo_handler_flags_t handler_flags;
    struct mutex mux_hw_lock;
    int old_ddc_owner;
};
```

**Members**

- `active`: whether vga_switcheroo is enabled.
  Prerequisite is the registration of two GPUs and a handler
- `delayed_switch_active`: whether a delayed switch is pending
- `delayed_client_id`: client to which a delayed switch is pending
- `debugfs_root`: directory for vga_switcheroo debugfs interface
- `registered_clients`: number of registered GPUs
  (counting only vga clients, not audio clients)
- `clients`: list of registered clients
- `handler`: registered handler
- `handler_flags`: flags of registered handler
- `mux_hw_lock`: protects mux state
  (in particular while DDC lines are temporarily switched)
- `old_ddc_owner`: client to which DDC lines will be switched back on unlock

**Description**

vga_switcheroo private data. Currently only one vga_switcheroo instance
per system is supported.



#### <a id="c-struct-vga_switcheroo_client"></a>`struct vga_switcheroo_client`

registered client

**Definition**

```c
struct vga_switcheroo_client {
    struct pci_dev *pdev;
    struct fb_info *fb_info;
    enum vga_switcheroo_state pwr_state;
    const struct vga_switcheroo_client_ops *ops;
    enum vga_switcheroo_client_id id;
    bool active;
    bool driver_power_control;
    struct list_head list;
    struct pci_dev *vga_dev;
};
```

**Members**

- `pdev`: client pci device
- `fb_info`: framebuffer to which console is remapped on switching
- `pwr_state`: current power state if manual power control is used.
  For driver power control, call `vga_switcheroo_pwr_state()`.
- `ops`: client callbacks
- `id`: client identifier. Determining the id requires the handler,
  so gpus are initially assigned VGA_SWITCHEROO_UNKNOWN_ID
  and later given their true id in `vga_switcheroo_enable()`
- `active`: whether the outputs are currently switched to this client
- `driver_power_control`: whether power state is controlled by the driver's
  runtime pm. If true, writing ON and OFF to the vga_switcheroo debugfs
  interface is a no-op so as not to interfere with runtime pm
- `list`: client list
- `vga_dev`: pci device, indicate which GPU is bound to current audio client

**Description**

Registered client. A client can be either a GPU or an audio device on a GPU.
For audio clients, the **fb_info** and **active** members are bogus. For GPU
clients, the **vga_dev** is bogus.


<a id="rst-handlers"></a>

## Handlers

<a id="rst-apple-gmux-handler"></a>

### apple-gmux Handler


gmux is a microcontroller built into the MacBook Pro to support dual GPUs:
A `Lattice XP2` on pre-retinas, a `Renesas R4F2113` on pre-T2 retinas.

On T2 Macbooks, the gmux is part of the T2 Coprocessor's SMC. The SMC has
an I2C connection to a `NXP PCAL6524` GPIO expander, which enables/disables
the voltage regulators of the discrete GPU, drives the display panel power,
and has a GPIO to switch the eDP mux. The Intel CPU can interact with
gmux through MMIO, similar to how the main SMC interface is controlled.

(The MacPro6,1 2013 also has a gmux, however it is unclear why since it has
dual GPUs but no built-in display.)

gmux is connected to the LPC bus of the southbridge. Its I/O ports are
accessed differently depending on the microcontroller: Driver functions
to access a pre-retina gmux are infixed `_pio_`, those for a pre-T2
retina gmux are infixed `_index_`, and those on T2 Macs are infixed
with `_mmio_`.



gmux is also connected to a GPIO pin of the southbridge and thereby is able
to trigger an ACPI GPE. ACPI name GMGP holds this GPIO pin's number. On the
MBP5 2008/09 it's GPIO pin 22 of the Nvidia MCP79, on following generations
it's GPIO pin 6 of the Intel PCH, on MMIO gmux's it's pin 21.

The GPE merely signals that an interrupt occurred, the actual type of event
is identified by reading a gmux register.

In addition to the GMGP name, gmux's ACPI device also has two methods GMSP
and GMLV. GMLV likely means "GMUX Level", and reads the value of the GPIO,
while GMSP likely means "GMUX Set Polarity", and seems to write to the GPIO's
value. On newer Macbooks (This was introduced with or sometime before the
MacBookPro14,3), the ACPI GPE method differentiates between the OS type: On
Darwin, only a notification is signaled, whereas on other OSes, the GPIO's
value is read and then inverted.

Because Linux masquerades as Darwin, it ends up in the notification-only code
path. On MMIO gmux's, this seems to lead to us being unable to clear interrupts,
unless we call GMSP(0). Without this, there is a flood of status=0 interrupts
that can't be cleared. This issue seems to be unique to MMIO gmux's.


<a id="rst-graphics-mux"></a>

#### Graphics mux


On pre-retinas, the LVDS outputs of both GPUs feed into gmux which muxes
either of them to the panel. One of the tricks gmux has up its sleeve is
to lengthen the blanking interval of its output during a switch to
synchronize it with the GPU switched to. This allows for a flicker-free
switch that is imperceptible by the user (`US 8,687,007 B2`).

On retinas, muxing is no longer done by gmux itself, but by a separate
chip which is controlled by gmux. The chip is triple sourced, it is
either an `NXP CBTL06142`, `TI HD3SS212` or `Pericom PI3VDP12412`.
The panel is driven with eDP instead of LVDS since the pixel clock
required for retina resolution exceeds LVDS' limits.

Pre-retinas are able to switch the panel's DDC pins separately.
This is handled by a `TI SN74LV4066A` which is controlled by gmux.
The inactive GPU can thus probe the panel's EDID without switching over
the entire panel. Retinas lack this functionality as the chips used for
eDP muxing are incapable of switching the AUX channel separately (see
the linked data sheets, Pericom would be capable but this is unused).
However the retina panel has the NO_AUX_HANDSHAKE_LINK_TRAINING bit set
in its DPCD, allowing the inactive GPU to skip the AUX handshake and
set up the output with link parameters pre-calibrated by the active GPU.

The external DP port is only fully switchable on the first two unibody
MacBook Pro generations, MBP5 2008/09 and MBP6 2010. This is done by an
`NXP CBTL06141` which is controlled by gmux. It's the predecessor of the
eDP mux on retinas, the difference being support for 2.7 versus 5.4 Gbit/s.

The following MacBook Pro generations replaced the external DP port with a
combined DP/Thunderbolt port and lost the ability to switch it between GPUs,
connecting it either to the discrete GPU or the Thunderbolt controller.
Oddly enough, while the full port is no longer switchable, AUX and HPD
are still switchable by way of an `NXP CBTL03062` (on pre-retinas
MBP8 2011 and MBP9 2012) or two `TI TS3DS10224` (on pre-t2 retinas) under
the control of gmux. Since the integrated GPU is missing the main link,
external displays appear to it as phantoms which fail to link-train.

gmux receives the HPD signal of all display connectors and sends an
interrupt on hotplug. On generations which cannot switch external ports,
the discrete GPU can then be woken to drive the newly connected display.
The ability to switch AUX on these generations could be used to improve
reliability of hotplug detection by having the integrated GPU poll the
ports while the discrete GPU is asleep, but currently we do not make use
of this feature.

Our switching policy for the external port is that on those generations
which are able to switch it fully, the port is switched together with the
panel when IGD / DIS commands are issued to vga_switcheroo. It is thus
possible to drive e.g. a beamer on battery power with the integrated GPU.
The user may manually switch to the discrete GPU if more performance is
needed.

On all newer generations, the external port can only be driven by the
discrete GPU. If a display is plugged in while the panel is switched to
the integrated GPU, *both* GPUs will be in use for maximum performance.
To decrease power consumption, the user may manually switch to the
discrete GPU, thereby suspending the integrated GPU.

gmux' initial switch state on bootup is user configurable via the EFI
variable `gpu-power-prefs-fa4ce28d-b62f-4c99-9cc3-6815686e30f9` (5th byte,
1 = IGD, 0 = DIS). Based on this setting, the EFI firmware tells gmux to
switch the panel and the external DP connector and allocates a framebuffer
for the selected GPU.


<a id="rst-power-control"></a>

#### Power control


gmux is able to cut power to the discrete GPU. It automatically takes care
of the correct sequence to tear down and bring up the power rails for
core voltage, VRAM and PCIe.


<a id="rst-backlight-control"></a>

#### Backlight control


On single GPU MacBooks, the PWM signal for the backlight is generated by
the GPU. On dual GPU MacBook Pros by contrast, either GPU may be suspended
to conserve energy. Hence the PWM signal needs to be generated by a separate
backlight driver which is controlled by gmux. The earliest generation
MBP5 2008/09 uses a `TI LP8543` backlight driver. Newer models
use a `TI LP8545` or a TI LP8548.


<a id="rst-public-functions-1"></a>

#### Public functions


#### <a id="c-apple_gmux_detect"></a>`apple_gmux_detect()`

```c
bool apple_gmux_detect(struct pnp_dev *pnp_dev, enum apple_gmux_type *type_ret)
```

detect if gmux is built into the machine

**Parameters**

- `struct pnp_dev *pnp_dev`: Device to probe or NULL to use the first matching device
- `enum apple_gmux_type *type_ret`: Returns (by reference) the apple_gmux_type of the device

**Description**

Detect if a supported gmux device is present by actually probing it.
This avoids the false positives returned on some models by
[`apple_gmux_present()`](#c-apple_gmux_present).

**Return**

`true` if a supported gmux ACPI device is detected and the kernel
was configured with CONFIG_APPLE_GMUX, `false` otherwise.

#### <a id="c-apple_gmux_present"></a>`apple_gmux_present()`

```c
bool apple_gmux_present(void)
```

check if gmux ACPI device is present

**Parameters**

- `void`: no arguments

**Description**

Drivers may use this to activate quirks specific to dual GPU MacBook Pros
and Mac Pros, e.g. for deferred probing, runtime pm and backlight.

**Return**

`true` if gmux ACPI device is present and the kernel was configured
with CONFIG_APPLE_GMUX, `false` otherwise.

---

# VGA Arbiter

_Peios Kernel / Hardware and drivers / Graphics_

> Graphic devices are accessed through ranges in I/O or memory space. While most modern devices allow relocation of such ranges, some "Legacy" VGA devices implemented on PCI will typically have the same "hard-decoded" addresses as they did…

<a id="rst-vga-arbiter"></a>

Graphic devices are accessed through ranges in I/O or memory space. While most modern devices allow relocation of such ranges, some "Legacy" VGA devices implemented on PCI will typically have the same "hard-decoded" addresses as they did on ISA. For more details see "PCI Bus Binding to IEEE Std 1275-1994 Standard for Boot (Initialization Configuration) Firmware Revision 2.1" Section 7, Legacy Devices.

The Resource Access Control (RAC) module inside the X server \[0\] existed for the legacy VGA arbitration task (besides other bus management tasks) when more than one legacy device co-exist on the same machine. But the problem happens when these devices are trying to be accessed by different userspace clients (e.g. two servers in parallel). Their address assignments conflict. Moreover, ideally, being a userspace application, it is not the role of the X server to control bus resources. Therefore an arbitration scheme outside of the X server is needed to control the sharing of these resources. This document introduces the operation of the VGA arbiter implemented for the Linux kernel.

<a id="rst-vgaarb-kernel-userspace-abi"></a>

## vgaarb kernel/userspace ABI

The vgaarb is a module of the Linux Kernel. When it is initially loaded, it scans all PCI devices and adds the VGA ones inside the arbitration. The arbiter then enables/disables the decoding on different devices of the VGA legacy instructions. Devices which do not want/need to use the arbiter may explicitly tell it by calling vga_set_legacy_decoding().

The kernel exports a char device interface (/dev/vga_arbiter) to the clients, which has the following semantics:

- **open**

  Opens a user instance of the arbiter. By default, it's attached to the default VGA device of the system.

- **close**

  Close a user instance. Release locks made by the user

- **read**

  Return a string indicating the status of the target like:

  "&lt;card_ID&gt;,decodes=&lt;io_state&gt;,owns=&lt;io_state&gt;,locks=&lt;io_state&gt; (ic,mc)"

  An IO state string is of the form \{io,mem,io+mem,none\}, mc and ic are respectively mem and io lock counts (for debugging/ diagnostic only). "decodes" indicate what the card currently decodes, "owns" indicates what is currently enabled on it, and "locks" indicates what is locked by this card. If the card is unplugged, we get "invalid" then for card_ID and an -ENODEV error is returned for any command until a new card is targeted.

- **write**

  Write a command to the arbiter. List of commands:

  - **target &lt;card_ID&gt;**

    switch target to card &lt;card_ID&gt; (see below)

  - **lock &lt;io_state&gt;**

    acquires locks on target ("none" is an invalid io_state)

  - **trylock &lt;io_state&gt;**

    non-blocking acquire locks on target (returns EBUSY if unsuccessful)

  - **unlock &lt;io_state&gt;**

    release locks on target

  - **unlock all**

    release all locks on target held by this user (not implemented yet)

  - **decodes &lt;io_state&gt;**

    set the legacy decoding attributes for the card

  - **poll**

    event if something changes on any card (not just the target)

  card_ID is of the form "PCI:domain:bus:dev.fn". It can be set to "default" to go back to the system default card (TODO: not implemented yet). Currently, only PCI is supported as a prefix, but the userland API may support other bus types in the future, even if the current kernel implementation doesn't.

Note about locks:

The driver keeps track of which user has which locks on which card. It supports stacking, like the kernel one. This complexifies the implementation a bit, but makes the arbiter more tolerant to user space problems and able to properly cleanup in all cases when a process dies. Currently, a max of 16 cards can have locks simultaneously issued from user space for a given user (file descriptor instance) of the arbiter.

In the case of devices hot-\{un,\}plugged, there is a hook - pci_notify() - to notify them being added/removed in the system and automatically added/removed in the arbiter.

There is also an in-kernel API of the arbiter in case DRM, vgacon, or other drivers want to use it.

<a id="rst-in-kernel-interface"></a>

## In-kernel interface


#### <a id="c-vga_get_interruptible"></a>`vga_get_interruptible()`

```c
int vga_get_interruptible(struct pci_dev *pdev, unsigned int rsrc)
```

**Parameters**

- `struct pci_dev *pdev`: pci device of the VGA card or NULL for the system default
- `unsigned int rsrc`: bit mask of resources to acquire and lock

**Description**

Shortcut to vga_get with interruptible set to true.

On success, release the VGA resource again with [`vga_put()`](#c-vga_put).

#### <a id="c-vga_get_uninterruptible"></a>`vga_get_uninterruptible()`

```c
int vga_get_uninterruptible(struct pci_dev *pdev, unsigned int rsrc)
```

shortcut to [`vga_get()`](#c-vga_get)

**Parameters**

- `struct pci_dev *pdev`: pci device of the VGA card or NULL for the system default
- `unsigned int rsrc`: bit mask of resources to acquire and lock

**Description**

Shortcut to vga_get with interruptible set to false.

On success, release the VGA resource again with [`vga_put()`](#c-vga_put).



#### <a id="c-vga_default_device"></a>`vga_default_device()`

```c
struct pci_dev * vga_default_device(void)
```

return the default VGA device, for vgacon

**Parameters**

- `void`: no arguments

**Description**

This can be defined by the platform. The default implementation is
rather dumb and will probably only work properly on single VGA card
setups and/or x86 platforms.

If your VGA default device is not PCI, you'll have to return NULL here.
In this case, I assume it will not conflict with any PCI card. If this
is not true, I'll have to define two arch hooks for enabling/disabling
the VGA default device if that is possible. This may be a problem with
real _ISA_ VGA cards, in addition to a PCI one. I don't know at this
point how to deal with that card. Can their IOs be disabled at all? If
not, then I suppose it's a matter of having the proper arch hook telling
us about it, so we basically never allow anybody to succeed a [`vga_get()`](#c-vga_get).

#### <a id="c-vga_remove_vgacon"></a>`vga_remove_vgacon()`

```c
int vga_remove_vgacon(struct pci_dev *pdev)
```

deactivate VGA console

**Parameters**

- `struct pci_dev *pdev`: PCI device.

**Description**

Unbind and unregister vgacon in case pdev is the default VGA device.
Can be called by GPU drivers on initialization to make sure VGA register
access done by vgacon will not disturb the device.

#### <a id="c-vga_get"></a>`vga_get()`

```c
int vga_get(struct pci_dev *pdev, unsigned int rsrc, int interruptible)
```

acquire & lock VGA resources

**Parameters**

- `struct pci_dev *pdev`: PCI device of the VGA card or NULL for the system default
- `unsigned int rsrc`: bit mask of resources to acquire and lock
- `int interruptible`: blocking should be interruptible by signals ?

**Description**

Acquire VGA resources for the given card and mark those resources
locked. If the resources requested are "normal" (and not legacy)
resources, the arbiter will first check whether the card is doing legacy
decoding for that type of resource. If yes, the lock is "converted" into
a legacy resource lock.

The arbiter will first look for all VGA cards that might conflict and disable
their IOs and/or Memory access, including VGA forwarding on P2P bridges if
necessary, so that the requested resources can be used. Then, the card is
marked as locking these resources and the IO and/or Memory accesses are
enabled on the card (including VGA forwarding on parent P2P bridges if any).

This function will block if some conflicting card is already locking one of
the required resources (or any resource on a different bus segment, since P2P
bridges don't differentiate VGA memory and IO afaik). You can indicate
whether this blocking should be interruptible by a signal (for userland
interface) or not.

Must not be called at interrupt time or in atomic context.  If the card
already owns the resources, the function succeeds.  Nested calls are
supported (a per-resource counter is maintained)

On success, release the VGA resource again with [`vga_put()`](#c-vga_put).

0 on success, negative error code on failure.

#### <a id="c-vga_put"></a>`vga_put()`

```c
void vga_put(struct pci_dev *pdev, unsigned int rsrc)
```

release lock on legacy VGA resources

**Parameters**

- `struct pci_dev *pdev`: PCI device of VGA card or NULL for system default
- `unsigned int rsrc`: bit mask of resource to release

**Description**

Release resources previously locked by [`vga_get()`](#c-vga_get) or `vga_tryget()`.  The
resources aren't disabled right away, so that a subsequent [`vga_get()`](#c-vga_get) on
the same card will succeed immediately.  Resources have a counter, so
locks are only released if the counter reaches 0.

#### <a id="c-vga_set_legacy_decoding"></a>`vga_set_legacy_decoding()`

```c
void vga_set_legacy_decoding(struct pci_dev *pdev, unsigned int decodes)
```

**Parameters**

- `struct pci_dev *pdev`: PCI device of the VGA card
- `unsigned int decodes`: bit mask of what legacy regions the card decodes

**Description**

Indicate to the arbiter if the card decodes legacy VGA IOs, legacy VGA
Memory, both, or none. All cards default to both, the card driver (fbdev for
example) should tell the arbiter if it has disabled legacy decoding, so the
card can be left out of the arbitration process (and can be safe to take
interrupts at any time.

#### <a id="c-vga_client_register"></a>`vga_client_register()`

```c
int vga_client_register(struct pci_dev *pdev, unsigned int (*set_decode)(struct pci_dev *pdev, bool decode))
```

register or unregister a VGA arbitration client

**Parameters**

- `struct pci_dev *pdev`: PCI device of the VGA client
- `unsigned int (*set_decode)(struct pci_dev *pdev, bool decode)`: VGA decode change callback

**Description**

Clients have two callback mechanisms they can use.

**set_decode** callback: If a client can disable its GPU VGA resource, it
will get a callback from this to set the encode/decode state.

Rationale: we cannot disable VGA decode resources unconditionally
because some single GPU laptops seem to require ACPI or BIOS access to
the VGA registers to control things like backlights etc. Hopefully newer
multi-GPU laptops do something saner, and desktops won't have any
special ACPI for this. The driver will get a callback when VGA
arbitration is first used by userspace since some older X servers have
issues.

Does not check whether a client for **pdev** has been registered already.

To unregister, call `vga_client_unregister()`.

**Return**

0 on success, -ENODEV on failure


<a id="rst-libpciaccess"></a>

## libpciaccess

To use the vga arbiter char device, an API was implemented inside the libpciaccess library. One field was added to struct pci_device (each device on the system):



```text
/* the type of resource decoded by the device */
int vgaarb_rsrc;
```

Besides it, in pci_system were added:



```text
int vgaarb_fd;
int vga_count;
struct pci_device *vga_target;
struct pci_device *vga_default_dev;
```

The vga_count is used to track how many cards are being arbitrated, so for instance, if there is only one card, then it can completely escape arbitration.

These functions below acquire VGA resources for the given card and mark those resources as locked. If the resources requested are "normal" (and not legacy) resources, the arbiter will first check whether the card is doing legacy decoding for that type of resource. If yes, the lock is "converted" into a legacy resource lock. The arbiter will first look for all VGA cards that might conflict and disable their IOs and/or Memory access, including VGA forwarding on P2P bridges if necessary, so that the requested resources can be used. Then, the card is marked as locking these resources and the IO and/or Memory access is enabled on the card (including VGA forwarding on parent P2P bridges if any). In the case of vga_arb_lock(), the function will block if some conflicting card is already locking one of the required resources (or any resource on a different bus segment, since P2P bridges don't differentiate VGA memory and IO afaik). If the card already owns the resources, the function succeeds.  vga_arb_trylock() will return (-EBUSY) instead of blocking. Nested calls are supported (a per-resource counter is maintained).

Set the target device of this client.



```text
int  pci_device_vgaarb_set_target   (struct pci_device *dev);
```

For instance, in x86 if two devices on the same bus want to lock different resources, both will succeed (lock). If devices are in different buses and trying to lock different resources, only the first who tried succeeds.



```text
int  pci_device_vgaarb_lock         (void);
int  pci_device_vgaarb_trylock      (void);
```

Unlock resources of device.



```text
int  pci_device_vgaarb_unlock       (void);
```

Indicates to the arbiter if the card decodes legacy VGA IOs, legacy VGA Memory, both, or none. All cards default to both, the card driver (fbdev for example) should tell the arbiter if it has disabled legacy decoding, so the card can be left out of the arbitration process (and can be safe to take interrupts at any time.



```text
int  pci_device_vgaarb_decodes      (int new_vgaarb_rsrc);
```

Connects to the arbiter device, allocates the struct



```text
int  pci_device_vgaarb_init         (void);
```

Close the connection



```text
void pci_device_vgaarb_fini         (void);
```

<a id="rst-xf86vgaarbiter-x-server-implementation"></a>

## xf86VGAArbiter (X server implementation)

X server basically wraps all the functions that touch VGA registers somehow.

<a id="rst-references"></a>

## References

Benjamin Herrenschmidt (IBM?) started this work when he discussed such design with the Xorg community in 2005 \[1, 2\]. In the end of 2007, Paulo Zanoni and Tiago Vignatti (both of C3SL/Federal University of Paraná) proceeded his work enhancing the kernel code to adapt as a kernel module and also did the implementation of the user space side \[3\]. Now (2009) Tiago Vignatti and Dave Airlie finally put this work in shape and queued to Jesse Barnes' PCI tree.

0. [https://cgit.freedesktop.org/xorg/xserver/commit/?id=4b42448a2388d40f257774fbffdccaea87bd0347](<https://cgit.freedesktop.org/xorg/xserver/commit/?id=4b42448a2388d40f257774fbffdccaea87bd0347>)

1. [https://lists.freedesktop.org/archives/xorg/2005-March/006663.html](<https://lists.freedesktop.org/archives/xorg/2005-March/006663.html>)

2. [https://lists.freedesktop.org/archives/xorg/2005-March/006745.html](<https://lists.freedesktop.org/archives/xorg/2005-March/006745.html>)

3. [https://lists.freedesktop.org/archives/xorg/2007-October/029507.html](<https://lists.freedesktop.org/archives/xorg/2007-October/029507.html>)

---

# drm/vkms Virtual Kernel Modesetting

_Peios Kernel / Hardware and drivers / Graphics_

> The VKMS driver can be setup with the following steps:

<a id="rst-drm-vkms-virtual-kernel-modesetting"></a>
<a id="rst-vkms"></a>


VKMS is a software-only model of a KMS driver that is useful for testing
and for running X (or similar) on headless machines. VKMS aims to enable
a virtual display with no need of a hardware display capability, releasing
the GPU in DRM API tests.


<a id="rst-setup"></a>

## Setup

The VKMS driver can be setup with the following steps:

To check if VKMS is loaded, run:



```text
lsmod | grep vkms
```

This should list the VKMS driver. If no output is obtained, then you need to enable and/or load the VKMS driver. Ensure that the VKMS driver has been set as a loadable module in your kernel config file. Do:



```text
make nconfig

Go to `Device Drivers> Graphics support`

Enable `Virtual KMS (EXPERIMENTAL)`
```

Compile and build the kernel for the changes to get reflected. Now, to load the driver, use:



```text
sudo modprobe vkms
```

On running the lsmod command now, the VKMS driver will appear listed. You can also observe the driver being loaded in the dmesg logs.

The VKMS driver has optional features to simulate different kinds of hardware, which are exposed as module options. You can use the `modinfo` command to see the module options for vkms:



```text
modinfo vkms
```

Module options are helpful when testing, and enabling modules can be done while loading vkms. For example, to load vkms with cursor enabled, use:



```text
sudo modprobe vkms enable_cursor=1
```

To disable the driver, use



```text
sudo modprobe -r vkms
```

<a id="rst-configuring-with-configfs"></a>

## Configuring With Configfs

It is possible to create and configure multiple VKMS instances via configfs.

Start by mounting configfs and loading VKMS:



```text
sudo mount -t configfs none /config
sudo modprobe vkms
```

Once VKMS is loaded, `/config/vkms` is created automatically. Each directory under `/config/vkms` represents a VKMS instance, create a new one:



```text
sudo mkdir /config/vkms/my-vkms
```

By default, the instance is disabled:



```text
cat /config/vkms/my-vkms/enabled
0
```

And directories are created for each configurable item of the display pipeline:



```text
tree /config/vkms/my-vkms
├── connectors
├── crtcs
├── enabled
├── encoders
└── planes
```

To add items to the display pipeline, create one or more directories under the available paths.

Start by creating one or more planes:



```text
sudo mkdir /config/vkms/my-vkms/planes/plane0
```

Planes have 1 configurable attribute:

- type: Plane type: 0 overlay, 1 primary, 2 cursor (same values as those exposed by the "type" property of a plane)

Continue by creating one or more CRTCs:



```text
sudo mkdir /config/vkms/my-vkms/crtcs/crtc0
```

CRTCs have 1 configurable attribute:

- writeback: Enable or disable writeback connector support by writing 1 or 0

Next, create one or more encoders:



```text
sudo mkdir /config/vkms/my-vkms/encoders/encoder0
```

Last but not least, create one or more connectors:



```text
sudo mkdir /config/vkms/my-vkms/connectors/connector0
```

Connectors have 1 configurable attribute:

- status: Connection status: 1 connected, 2 disconnected, 3 unknown (same values as those exposed by the "status" property of a connector)

To finish the configuration, link the different pipeline items:



```text
sudo ln -s /config/vkms/my-vkms/crtcs/crtc0 /config/vkms/my-vkms/planes/plane0/possible_crtcs
sudo ln -s /config/vkms/my-vkms/crtcs/crtc0 /config/vkms/my-vkms/encoders/encoder0/possible_crtcs
sudo ln -s /config/vkms/my-vkms/encoders/encoder0 /config/vkms/my-vkms/connectors/connector0/possible_encoders
```

Since at least one primary plane is required, make sure to set the right type:



```text
echo "1" | sudo tee /config/vkms/my-vkms/planes/plane0/type
```

Once you are done configuring the VKMS instance, enable it:



```text
echo "1" | sudo tee /config/vkms/my-vkms/enabled
```

Finally, you can remove the VKMS instance disabling it:



```text
echo "0" | sudo tee /config/vkms/my-vkms/enabled
```

And removing the top level directory and its subdirectories:



```text
sudo rm /config/vkms/my-vkms/planes/*/possible_crtcs/*
sudo rm /config/vkms/my-vkms/encoders/*/possible_crtcs/*
sudo rm /config/vkms/my-vkms/connectors/*/possible_encoders/*
sudo rmdir /config/vkms/my-vkms/planes/*
sudo rmdir /config/vkms/my-vkms/crtcs/*
sudo rmdir /config/vkms/my-vkms/encoders/*
sudo rmdir /config/vkms/my-vkms/connectors/*
sudo rmdir /config/vkms/my-vkms
```

<a id="rst-testing-with-igt"></a>

## Testing With IGT

The IGT GPU Tools is a test suite used specifically for debugging and development of the DRM drivers. The IGT Tools can be installed from [here](<https://gitlab.freedesktop.org/drm/igt-gpu-tools>)<a id="rst-here"></a> .

The tests need to be run without a compositor, so you need to switch to text only mode. You can do this by:



```text
sudo systemctl isolate multi-user.target
```

To return to graphical mode, do:



```text
sudo systemctl isolate graphical.target
```

Once you are in text only mode, you can run tests using the IGT_FORCE_DRIVER variable to specify the device filter for the driver we want to test. IGT_FORCE_DRIVER can also be used with the run-tests.sh script to run the tests for a specific driver:



```text
sudo IGT_FORCE_DRIVER="vkms" ./build/tests/<name of test>
sudo IGT_FORCE_DRIVER="vkms" ./scripts/run-tests.sh -t <name of test>
```

For example, to test the functionality of the writeback library, we can run the kms_writeback test:



```text
sudo IGT_FORCE_DRIVER="vkms" ./build/tests/kms_writeback
sudo IGT_FORCE_DRIVER="vkms" ./scripts/run-tests.sh -t kms_writeback
```

You can also run subtests if you do not want to run the entire test:



```text
sudo IGT_FORCE_DRIVER="vkms" ./build/tests/kms_flip --run-subtest basic-plain-flip
```

<a id="rst-testing-with-kunit"></a>

## Testing With KUnit

KUnit (Kernel unit testing framework) provides a common framework for unit tests within the Linux kernel. More information in ../dev-tools/kunit/index.rst .

To run the VKMS KUnit tests:



```text
tools/testing/kunit/kunit.py run --kunitconfig=drivers/gpu/drm/vkms/tests
```

<a id="rst-todo"></a>

## TODO

If you want to do any of the items listed below, please share your interest with VKMS maintainers.

<a id="rst-igt-better-support"></a>

### IGT better support

Debugging:

- kms_plane: some test cases are failing due to timeout on capturing CRC;

Virtual hardware (vblank-less) mode:

- VKMS already has support for vblanks simulated via hrtimers, which can be tested with kms_flip test; in some way, we can say that VKMS already mimics the real hardware vblank. However, we also have virtual hardware that does not support vblank interrupt and completes page_flip events right away; in this case, compositor developers may end up creating a busy loop on virtual hardware. It would be useful to support Virtual Hardware behavior in VKMS because this can help compositor developers to test their features in multiple scenarios.

<a id="rst-add-plane-features"></a>

### Add Plane Features

There's lots of plane features we could add support for:

- Add background color KMS property\[Good to get started\].

- Scaling.

- Additional buffer formats. Low/high bpp RGB formats would be interesting \[Good to get started\].

- Async updates (currently only possible on cursor plane using the legacy cursor api).

For all of these, we also want to review the igt test coverage and make sure all relevant igt testcases work on vkms. They are good options for internship project.

<a id="rst-runtime-configuration"></a>

### Runtime Configuration

We want to be able to reconfigure vkms instance without having to reload the module through configfs. Use/Test-cases:

- Hotplug/hotremove connectors on the fly (to be able to test DP MST handling of compositors).

- Change output configuration: Plug/unplug screens, change EDID, allow changing the refresh rate.

<a id="rst-writeback-support"></a>

### Writeback support

- The writeback and CRC capture operations share the use of composer_enabled boolean to ensure vblanks. Probably, when these operations work together, composer_enabled needs to refcounting the composer state to proper work. \[Good to get started\]

- Add support for cloned writeback outputs and related test cases using a cloned output in the IGT kms_writeback.

- As a v4l device. This is useful for debugging compositors on special vkms configurations, so that developers see what's really going on.

<a id="rst-output-features"></a>

### Output Features

- Variable refresh rate/freesync support. This probably needs prime buffer sharing support, so that we can use vgem fences to simulate rendering in testing. Also needs support to specify the EDID.

- Add support for link status, so that compositors can validate their runtime fallbacks when e.g. a Display Port link goes bad.

<a id="rst-crc-api-improvements"></a>

### CRC API Improvements

- Optimize CRC computation `compute_crc()` and plane blending `blend()`

<a id="rst-atomic-check-using-ebpf"></a>

### Atomic Check using eBPF

Atomic drivers have lots of restrictions which are not exposed to userspace in any explicit form through e.g. possible property values. Userspace can only inquiry about these limits through the atomic IOCTL, possibly using the TEST_ONLY flag. Trying to add configurable code for all these limits, to allow compositors to be tested against them, would be rather futile exercise. Instead we could add support for eBPF to validate any kind of atomic state, and implement a library of different restrictions.

This needs a bunch of features (plane compositing, multiple outputs, ...) enabled already to make sense.

---

# drm/xen-front Xen para-virtualized frontend driver

_Peios Kernel / Hardware and drivers / Graphics_

> This frontend driver implements Xen para-virtualized display according to the display protocol described at include/xen/interface/io/displif.h

<a id="rst-drm-xen-front-xen-para-virtualized-frontend-driver"></a>

This frontend driver implements Xen para-virtualized display according to the display protocol described at include/xen/interface/io/displif.h

<a id="rst-driver-modes-of-operation-in-terms-of-display-buffers-used"></a>

## Driver modes of operation in terms of display buffers used


Depending on the requirements for the para-virtualized environment, namely
requirements dictated by the accompanying DRM/(v)GPU drivers running in both
host and guest environments, display buffers can be allocated by either
frontend driver or backend.


<a id="rst-buffers-allocated-by-the-frontend-driver"></a>

### Buffers allocated by the frontend driver


In this mode of operation driver allocates buffers from system memory.

Note! If used with accompanying DRM/(v)GPU drivers this mode of operation
may require IOMMU support on the platform, so accompanying DRM/vGPU
hardware can still reach display buffer memory while importing PRIME
buffers from the frontend driver.


<a id="rst-buffers-allocated-by-the-backend"></a>

### Buffers allocated by the backend


This mode of operation is run-time configured via guest domain configuration
through XenStore entries.

For systems which do not provide IOMMU support, but having specific
requirements for display buffers it is possible to allocate such buffers
at backend side and share those with the frontend.
For example, if host domain is 1:1 mapped and has DRM/GPU hardware expecting
physically contiguous memory, this allows implementing zero-copying
use-cases.

Note, while using this scenario the following should be considered:

1. If guest domain dies then pages/grants received from the backend
   cannot be claimed back

1. Misbehaving guest may send too many requests to the
   backend exhausting its grant references and memory
   (consider this from security POV)


<a id="rst-driver-limitations"></a>

## Driver limitations


1. Only primary plane without additional properties is supported.

1. Only one video mode per connector supported which is configured
   via XenStore.

1. All CRTCs operate at fixed frequency of 60Hz.

---

# Xilinx ZynqMP Ultrascale+ DisplayPort Subsystem

_Peios Kernel / Hardware and drivers / Graphics_

> This subsystem handles DisplayPort video and audio output on the ZynqMP. It supports in-memory framebuffers with the DisplayPort DMA controller (xilinx-dpdma), as well as "live" video and audio from the programmable logic (PL). This…

<a id="rst-xilinx-zynqmp-ultrascale-displayport-subsystem"></a>

<!-- SPDX-License-Identifier: GPL-2.0+ -->

This subsystem handles DisplayPort video and audio output on the ZynqMP. It supports in-memory framebuffers with the DisplayPort DMA controller (xilinx-dpdma), as well as "live" video and audio from the programmable logic (PL). This subsystem can perform several transformations, including color space conversion, alpha blending, and audio mixing, although not all features are currently supported.

<a id="rst-debugfs"></a>

## debugfs

To support debugging and compliance testing, several test modes can be enabled though debugfs. The following files in /sys/kernel/debug/dri/X/DP-1/test/ control the DisplayPort test modes:

- **active:**

  Writing a 1 to this file will activate test mode, and writing a 0 will deactivate test mode. Writing a 1 or 0 when the test mode is already active/inactive will re-activate/re-deactivate test mode. When test mode is inactive, changes made to other files will have no (immediate) effect, although the settings will be saved for when test mode is activated. When test mode is active, changes made to other files will apply immediately.

- **custom:**

  Custom test pattern value

- **downspread:**

  Enable/disable clock downspreading (spread-spectrum clocking) by writing 1/0

- **enhanced:**

  Enable/disable enhanced framing

- **ignore_aux_errors:**

  Ignore AUX errors when set to 1. Writes to this file take effect immediately (regardless of whether test mode is active) and affect all AUX transfers.

- **ignore_hpd:**

  Ignore hotplug events (such as cable removals or monitor link retraining requests) when set to 1. Writes to this file take effect immediately (regardless of whether test mode is active).

- **laneX_preemphasis:**

  Preemphasis from 0 (lowest) to 2 (highest) for lane X

- **laneX_swing:**

  Voltage swing from 0 (lowest) to 3 (highest) for lane X

- **lanes:**

  Number of lanes to use (1, 2, or 4)

- **pattern:**

  Test pattern. May be one of:

  > - **video**
  >
  >   Use regular video input
  >
  > - **symbol-error**
  >
  >   Symbol error measurement pattern
  >
  > - **prbs7**
  >
  >   Output of the PRBS7 (x^7 + x^6 + 1) polynomial
  >
  > - **80bit-custom**
  >
  >   A custom 80-bit pattern
  >
  > - **cp2520**
  >
  >   HBR2 compliance eye pattern
  >
  > - **tps1**
  >
  >   Link training symbol pattern TPS1 (/D10.2/)
  >
  > - **tps2**
  >
  >   Link training symbol pattern TPS2
  >
  > - **tps3**
  >
  >   Link training symbol pattern TPS3 (for HBR2)

- **rate:**

  Rate in hertz. One of

  > - 5400000000 (HBR2)
  >
  > - 2700000000 (HBR)
  >
  > - 1620000000 (RBR)

You can dump the displayport test settings with the following command:



```text
for prop in /sys/kernel/debug/dri/1/DP-1/test/*; do
        printf '%-17s ' ${prop##*/}
        if [ ${prop##*/} = custom ]; then
                hexdump -C $prop | head -1
        else
                cat $prop
        fi
done
```

The output could look something like:



```text
active            1
custom            00000000  00 00 00 00 00 00 00 00  00 00                    |..........|
downspread        0
enhanced          1
ignore_aux_errors 1
ignore_hpd        1
lane0_preemphasis 0
lane0_swing       3
lane1_preemphasis 0
lane1_swing       3
lanes             2
pattern           prbs7
rate              1620000000
```

The recommended test procedure is to connect the board to a monitor, configure test mode, activate test mode, and then disconnect the cable and connect it to your test equipment of choice. For example, one sequence of commands could be:



```text
echo 1 > /sys/kernel/debug/dri/1/DP-1/test/enhanced
echo tps1 > /sys/kernel/debug/dri/1/DP-1/test/pattern
echo 1620000000 > /sys/kernel/debug/dri/1/DP-1/test/rate
echo 1 > /sys/kernel/debug/dri/1/DP-1/test/ignore_aux_errors
echo 1 > /sys/kernel/debug/dri/1/DP-1/test/ignore_hpd
echo 1 > /sys/kernel/debug/dri/1/DP-1/test/active
```

at which point the cable could be disconnected from the monitor.

<a id="rst-internals"></a>

## Internals


#### <a id="c-enum-zynqmp_dpsub_layer_id"></a>`enum zynqmp_dpsub_layer_id`

Layer identifier

**Constants**

- `ZYNQMP_DPSUB_LAYER_VID`: Video layer
- `ZYNQMP_DPSUB_LAYER_GFX`: Graphics layer



#### <a id="c-struct-zynqmp_dpsub"></a>`struct zynqmp_dpsub`

ZynqMP DisplayPort Subsystem

**Definition**

```c
struct zynqmp_dpsub {
    struct device *dev;
    struct clk *apb_clk;
    struct clk *vid_clk;
    bool vid_clk_from_ps;
    struct clk *aud_clk;
    bool aud_clk_from_ps;
    unsigned int connected_ports;
    bool dma_enabled;
    struct zynqmp_dpsub_drm *drm;
    struct drm_bridge *bridge;
    struct zynqmp_disp *disp;
    struct zynqmp_disp_layer *layers[ZYNQMP_DPSUB_NUM_LAYERS];
    struct zynqmp_dp *dp;
    unsigned int dma_align;
    struct zynqmp_dpsub_audio *audio;
};
```

**Members**

- `dev`: The physical device
- `apb_clk`: The APB clock
- `vid_clk`: Video clock
- `vid_clk_from_ps`: True of the video clock comes from PS, false from PL
- `aud_clk`: Audio clock
- `aud_clk_from_ps`: True of the audio clock comes from PS, false from PL
- `connected_ports`: Bitmask of connected ports in the device tree
- `dma_enabled`: True if the DMA interface is enabled, false if the DPSUB is
  driven by the live input
- `drm`: The DRM/KMS device data
- `bridge`: The DP encoder bridge
- `disp`: The display controller
- `layers`: Video and graphics layers
- `dp`: The DisplayPort controller
- `dma_align`: DMA alignment constraint (must be a power of 2)
- `audio`: DP audio data



#### <a id="c-struct-zynqmp_dpsub_drm"></a>`struct zynqmp_dpsub_drm`

ZynqMP DisplayPort Subsystem DRM/KMS data

**Definition**

```c
struct zynqmp_dpsub_drm {
    struct zynqmp_dpsub *dpsub;
    struct drm_device dev;
    struct drm_plane planes[ZYNQMP_DPSUB_NUM_LAYERS];
    struct drm_crtc crtc;
    struct drm_encoder encoder;
};
```

**Members**

- `dpsub`: Backpointer to the DisplayPort subsystem
- `dev`: The DRM/KMS device
- `planes`: The DRM planes
- `crtc`: The DRM CRTC
- `encoder`: The dummy DRM encoder



#### <a id="c-enum-zynqmp_dpsub_layer_mode"></a>`enum zynqmp_dpsub_layer_mode`

Layer mode

**Constants**

- `ZYNQMP_DPSUB_LAYER_NONLIVE`: non-live (memory) mode
- `ZYNQMP_DPSUB_LAYER_LIVE`: live (stream) mode

#### <a id="c-struct-zynqmp_disp_format"></a>`struct zynqmp_disp_format`

Display subsystem format information

**Definition**

```c
struct zynqmp_disp_format {
    u32 drm_fmt;
    u32 bus_fmt;
    u32 buf_fmt;
    bool swap;
    const u32 *sf;
};
```

**Members**

- `drm_fmt`: DRM format (4CC)
- `bus_fmt`: Media bus format
- `buf_fmt`: AV buffer format
- `swap`: Flag to swap R & B for RGB formats, and U & V for YUV formats
- `sf`: Scaling factors for color components

#### <a id="c-struct-zynqmp_disp_layer_dma"></a>`struct zynqmp_disp_layer_dma`

DMA channel for one data plane of a layer

**Definition**

```c
struct zynqmp_disp_layer_dma {
    struct dma_chan *chan;
    struct dma_interleaved_template xt;
    struct data_chunk sgl;
};
```

**Members**

- `chan`: DMA channel
- `xt`: Interleaved DMA descriptor template
- `sgl`: Data chunk for dma_interleaved_template

#### <a id="c-struct-zynqmp_disp_layer_info"></a>`struct zynqmp_disp_layer_info`

Static layer information

**Definition**

```c
struct zynqmp_disp_layer_info {
    const struct zynqmp_disp_format *formats;
    unsigned int num_formats;
    unsigned int num_channels;
};
```

**Members**

- `formats`: Array of supported formats
- `num_formats`: Number of formats in **formats** array
- `num_channels`: Number of DMA channels

#### <a id="c-struct-zynqmp_disp_layer"></a>`struct zynqmp_disp_layer`

Display layer

**Definition**

```c
struct zynqmp_disp_layer {
    enum zynqmp_dpsub_layer_id id;
    struct zynqmp_disp *disp;
    const struct zynqmp_disp_layer_info *info;
    struct zynqmp_disp_layer_dma dmas[ZYNQMP_DISP_MAX_NUM_SUB_PLANES];
    const struct zynqmp_disp_format *disp_fmt;
    const struct drm_format_info *drm_fmt;
    enum zynqmp_dpsub_layer_mode mode;
};
```

**Members**

- `id`: Layer ID
- `disp`: Back pointer to struct zynqmp_disp
- `info`: Static layer information
- `dmas`: DMA channels
- `disp_fmt`: Current format information
- `drm_fmt`: Current DRM format information
- `mode`: Current operation mode

#### <a id="c-struct-zynqmp_disp"></a>`struct zynqmp_disp`

Display controller

**Definition**

```c
struct zynqmp_disp {
    struct device *dev;
    struct zynqmp_dpsub *dpsub;
    void __iomem *blend;
    void __iomem *avbuf;
    struct zynqmp_disp_layer layers[ZYNQMP_DPSUB_NUM_LAYERS];
};
```

**Members**

- `dev`: Device structure
- `dpsub`: Display subsystem
- `blend`: Register I/O base address for the blender
- `avbuf`: Register I/O base address for the audio/video buffer manager
- `layers`: Layers (planes)

#### <a id="c-zynqmp_disp_avbuf_set_format"></a>`zynqmp_disp_avbuf_set_format()`

```c
void zynqmp_disp_avbuf_set_format(struct zynqmp_disp *disp, struct zynqmp_disp_layer *layer, const struct zynqmp_disp_format *fmt)
```

Set the input format for a layer

**Parameters**

- `struct zynqmp_disp *disp`: Display controller
- `struct zynqmp_disp_layer *layer`: The layer
- `const struct zynqmp_disp_format *fmt`: The format information

**Description**

Set the video buffer manager format for **layer** to **fmt**.

#### <a id="c-zynqmp_disp_avbuf_set_clocks_sources"></a>`zynqmp_disp_avbuf_set_clocks_sources()`

```c
void zynqmp_disp_avbuf_set_clocks_sources(struct zynqmp_disp *disp, bool video_from_ps, bool audio_from_ps, bool timings_internal)
```

Set the clocks sources

**Parameters**

- `struct zynqmp_disp *disp`: Display controller
- `bool video_from_ps`: True if the video clock originates from the PS
- `bool audio_from_ps`: True if the audio clock originates from the PS
- `bool timings_internal`: True if video timings are generated internally

**Description**

Set the source for the video and audio clocks, as well as for the video
timings. Clocks can originate from the PS or PL, and timings can be
generated internally or externally.

#### <a id="c-zynqmp_disp_avbuf_enable_channels"></a>`zynqmp_disp_avbuf_enable_channels()`

```c
void zynqmp_disp_avbuf_enable_channels(struct zynqmp_disp *disp)
```

Enable buffer channels

**Parameters**

- `struct zynqmp_disp *disp`: Display controller

**Description**

Enable all (video and audio) buffer channels.

#### <a id="c-zynqmp_disp_avbuf_disable_channels"></a>`zynqmp_disp_avbuf_disable_channels()`

```c
void zynqmp_disp_avbuf_disable_channels(struct zynqmp_disp *disp)
```

Disable buffer channels

**Parameters**

- `struct zynqmp_disp *disp`: Display controller

**Description**

Disable all (video and audio) buffer channels.

#### <a id="c-zynqmp_disp_avbuf_enable_audio"></a>`zynqmp_disp_avbuf_enable_audio()`

```c
void zynqmp_disp_avbuf_enable_audio(struct zynqmp_disp *disp)
```

Enable audio

**Parameters**

- `struct zynqmp_disp *disp`: Display controller

**Description**

Enable all audio buffers with a non-live (memory) source.

#### <a id="c-zynqmp_disp_avbuf_disable_audio"></a>`zynqmp_disp_avbuf_disable_audio()`

```c
void zynqmp_disp_avbuf_disable_audio(struct zynqmp_disp *disp)
```

Disable audio

**Parameters**

- `struct zynqmp_disp *disp`: Display controller

**Description**

Disable all audio buffers.

#### <a id="c-zynqmp_disp_avbuf_enable_video"></a>`zynqmp_disp_avbuf_enable_video()`

```c
void zynqmp_disp_avbuf_enable_video(struct zynqmp_disp *disp, struct zynqmp_disp_layer *layer)
```

Enable a video layer

**Parameters**

- `struct zynqmp_disp *disp`: Display controller
- `struct zynqmp_disp_layer *layer`: The layer

**Description**

Enable the video/graphics buffer for **layer**.

#### <a id="c-zynqmp_disp_avbuf_disable_video"></a>`zynqmp_disp_avbuf_disable_video()`

```c
void zynqmp_disp_avbuf_disable_video(struct zynqmp_disp *disp, struct zynqmp_disp_layer *layer)
```

Disable a video layer

**Parameters**

- `struct zynqmp_disp *disp`: Display controller
- `struct zynqmp_disp_layer *layer`: The layer

**Description**

Disable the video/graphics buffer for **layer**.

#### <a id="c-zynqmp_disp_avbuf_enable"></a>`zynqmp_disp_avbuf_enable()`

```c
void zynqmp_disp_avbuf_enable(struct zynqmp_disp *disp)
```

Enable the video pipe

**Parameters**

- `struct zynqmp_disp *disp`: Display controller

**Description**

De-assert the video pipe reset.

#### <a id="c-zynqmp_disp_avbuf_disable"></a>`zynqmp_disp_avbuf_disable()`

```c
void zynqmp_disp_avbuf_disable(struct zynqmp_disp *disp)
```

Disable the video pipe

**Parameters**

- `struct zynqmp_disp *disp`: Display controller

**Description**

Assert the video pipe reset.

#### <a id="c-zynqmp_disp_blend_set_output_format"></a>`zynqmp_disp_blend_set_output_format()`

```c
void zynqmp_disp_blend_set_output_format(struct zynqmp_disp *disp, enum zynqmp_dpsub_format format)
```

Set the output format of the blender

**Parameters**

- `struct zynqmp_disp *disp`: Display controller
- `enum zynqmp_dpsub_format format`: Output format

**Description**

Set the output format of the blender to **format**.

#### <a id="c-zynqmp_disp_blend_set_bg_color"></a>`zynqmp_disp_blend_set_bg_color()`

```c
void zynqmp_disp_blend_set_bg_color(struct zynqmp_disp *disp, u32 rcr, u32 gy, u32 bcb)
```

Set the background color

**Parameters**

- `struct zynqmp_disp *disp`: Display controller
- `u32 rcr`: Red/Cr color component
- `u32 gy`: Green/Y color component
- `u32 bcb`: Blue/Cb color component

**Description**

Set the background color to (**rcr**, **gy**, **bcb**), corresponding to the R, G and
B or Cr, Y and Cb components respectively depending on the selected output
format.

#### <a id="c-zynqmp_disp_blend_set_global_alpha"></a>`zynqmp_disp_blend_set_global_alpha()`

```c
void zynqmp_disp_blend_set_global_alpha(struct zynqmp_disp *disp, bool enable, u32 alpha)
```

Configure global alpha blending

**Parameters**

- `struct zynqmp_disp *disp`: Display controller
- `bool enable`: True to enable global alpha blending
- `u32 alpha`: Global alpha value (ignored if **enabled** is false)

#### <a id="c-zynqmp_disp_blend_layer_set_csc"></a>`zynqmp_disp_blend_layer_set_csc()`

```c
void zynqmp_disp_blend_layer_set_csc(struct zynqmp_disp *disp, struct zynqmp_disp_layer *layer, const u16 *coeffs, const u32 *offsets)
```

Configure colorspace conversion for layer

**Parameters**

- `struct zynqmp_disp *disp`: Display controller
- `struct zynqmp_disp_layer *layer`: The layer
- `const u16 *coeffs`: Colorspace conversion matrix
- `const u32 *offsets`: Colorspace conversion offsets

**Description**

Configure the input colorspace conversion matrix and offsets for the **layer**.
Columns of the matrix are automatically swapped based on the input format to
handle RGB and YCrCb components permutations.

#### <a id="c-zynqmp_disp_blend_layer_enable"></a>`zynqmp_disp_blend_layer_enable()`

```c
void zynqmp_disp_blend_layer_enable(struct zynqmp_disp *disp, struct zynqmp_disp_layer *layer)
```

Enable a layer

**Parameters**

- `struct zynqmp_disp *disp`: Display controller
- `struct zynqmp_disp_layer *layer`: The layer

#### <a id="c-zynqmp_disp_blend_layer_disable"></a>`zynqmp_disp_blend_layer_disable()`

```c
void zynqmp_disp_blend_layer_disable(struct zynqmp_disp *disp, struct zynqmp_disp_layer *layer)
```

Disable a layer

**Parameters**

- `struct zynqmp_disp *disp`: Display controller
- `struct zynqmp_disp_layer *layer`: The layer

#### <a id="c-zynqmp_disp_layer_find_format"></a>`zynqmp_disp_layer_find_format()`

```c
const struct zynqmp_disp_format * zynqmp_disp_layer_find_format(struct zynqmp_disp_layer *layer, u32 drm_fmt)
```

Find format information for a DRM format

**Parameters**

- `struct zynqmp_disp_layer *layer`: The layer
- `u32 drm_fmt`: DRM format to search

**Description**

Search display subsystem format information corresponding to the given DRM
format **drm_fmt** for the **layer**, and return a pointer to the format
descriptor.

**Return**

A pointer to the format descriptor if found, NULL otherwise

#### <a id="c-zynqmp_disp_layer_find_live_format"></a>`zynqmp_disp_layer_find_live_format()`

```c
const struct zynqmp_disp_format * zynqmp_disp_layer_find_live_format(struct zynqmp_disp_layer *layer, u32 media_bus_format)
```

Find format information for given media bus format

**Parameters**

- `struct zynqmp_disp_layer *layer`: The layer
- `u32 media_bus_format`: Media bus format to search

**Description**

Search display subsystem format information corresponding to the given media
bus format **media_bus_format** for the **layer**, and return a pointer to the
format descriptor.

**Return**

A pointer to the format descriptor if found, NULL otherwise

#### <a id="c-zynqmp_disp_layer_drm_formats"></a>`zynqmp_disp_layer_drm_formats()`

```c
u32 * zynqmp_disp_layer_drm_formats(struct zynqmp_disp_layer *layer, unsigned int *num_formats)
```

Return the DRM formats supported by the layer

**Parameters**

- `struct zynqmp_disp_layer *layer`: The layer
- `unsigned int *num_formats`: Pointer to the returned number of formats

**NOTE**

This function doesn't make sense for live video layers and will
always return an empty list in such cases. [`zynqmp_disp_live_layer_formats()`](#c-zynqmp_disp_live_layer_formats)
should be used to query a list of media bus formats supported by the live
video input layer.

**Return**

A newly allocated u32 array that stores all the DRM formats
supported by the layer. The number of formats in the array is returned
through the num_formats argument.

#### <a id="c-zynqmp_disp_live_layer_formats"></a>`zynqmp_disp_live_layer_formats()`

```c
u32 * zynqmp_disp_live_layer_formats(struct zynqmp_disp_layer *layer, unsigned int *num_formats)
```

Return the media bus formats supported by the live video layer

**Parameters**

- `struct zynqmp_disp_layer *layer`: The layer
- `unsigned int *num_formats`: Pointer to the returned number of formats

**NOTE**

This function should be used only for live video input layers.

**Return**

A newly allocated u32 array of media bus formats supported by the
layer. The number of formats in the array is returned through the
**num_formats** argument.

#### <a id="c-zynqmp_disp_layer_enable"></a>`zynqmp_disp_layer_enable()`

```c
void zynqmp_disp_layer_enable(struct zynqmp_disp_layer *layer)
```

Enable a layer

**Parameters**

- `struct zynqmp_disp_layer *layer`: The layer

**Description**

Enable the **layer** in the audio/video buffer manager and the blender. DMA
channels are started separately by [`zynqmp_disp_layer_update()`](#c-zynqmp_disp_layer_update).

#### <a id="c-zynqmp_disp_layer_disable"></a>`zynqmp_disp_layer_disable()`

```c
void zynqmp_disp_layer_disable(struct zynqmp_disp_layer *layer)
```

Disable the layer

**Parameters**

- `struct zynqmp_disp_layer *layer`: The layer

**Description**

Disable the layer by stopping its DMA channels and disabling it in the
audio/video buffer manager and the blender.

#### <a id="c-zynqmp_disp_layer_set_format"></a>`zynqmp_disp_layer_set_format()`

```c
void zynqmp_disp_layer_set_format(struct zynqmp_disp_layer *layer, const struct drm_format_info *info)
```

Set the layer format

**Parameters**

- `struct zynqmp_disp_layer *layer`: The layer
- `const struct drm_format_info *info`: The format info

**NOTE**

Use [`zynqmp_disp_layer_set_live_format()`](#c-zynqmp_disp_layer_set_live_format) to set media bus format for
live video layers.

Set the format for **layer** to **info**. The layer must be disabled.

#### <a id="c-zynqmp_disp_layer_set_live_format"></a>`zynqmp_disp_layer_set_live_format()`

```c
void zynqmp_disp_layer_set_live_format(struct zynqmp_disp_layer *layer, u32 media_bus_format)
```

Set the live video layer format

**Parameters**

- `struct zynqmp_disp_layer *layer`: The layer
- `u32 media_bus_format`: Media bus format to set

**NOTE**

This function should not be used to set format for non-live video
layer. Use [`zynqmp_disp_layer_set_format()`](#c-zynqmp_disp_layer_set_format) instead.

Set the display format for the live **layer**. The layer must be disabled.

#### <a id="c-zynqmp_disp_layer_update"></a>`zynqmp_disp_layer_update()`

```c
int zynqmp_disp_layer_update(struct zynqmp_disp_layer *layer, struct drm_plane_state *state)
```

Update the layer framebuffer

**Parameters**

- `struct zynqmp_disp_layer *layer`: The layer
- `struct drm_plane_state *state`: The plane state

**Description**

Update the framebuffer for the layer by issuing a new DMA engine transaction
for the new framebuffer.

**Return**

0 on success, or the DMA descriptor failure error otherwise

#### <a id="c-zynqmp_disp_layer_release_dma"></a>`zynqmp_disp_layer_release_dma()`

```c
void zynqmp_disp_layer_release_dma(struct zynqmp_disp *disp, struct zynqmp_disp_layer *layer)
```

Release DMA channels for a layer

**Parameters**

- `struct zynqmp_disp *disp`: Display controller
- `struct zynqmp_disp_layer *layer`: The layer

**Description**

Release the DMA channels associated with **layer**.

#### <a id="c-zynqmp_disp_destroy_layers"></a>`zynqmp_disp_destroy_layers()`

```c
void zynqmp_disp_destroy_layers(struct zynqmp_disp *disp)
```

Destroy all layers

**Parameters**

- `struct zynqmp_disp *disp`: Display controller

#### <a id="c-zynqmp_disp_layer_request_dma"></a>`zynqmp_disp_layer_request_dma()`

```c
int zynqmp_disp_layer_request_dma(struct zynqmp_disp *disp, struct zynqmp_disp_layer *layer)
```

Request DMA channels for a layer

**Parameters**

- `struct zynqmp_disp *disp`: Display controller
- `struct zynqmp_disp_layer *layer`: The layer

**Description**

Request all DMA engine channels needed by **layer**.

**Return**

0 on success, or the DMA channel request error otherwise

#### <a id="c-zynqmp_disp_create_layers"></a>`zynqmp_disp_create_layers()`

```c
int zynqmp_disp_create_layers(struct zynqmp_disp *disp)
```

Create and initialize all layers

**Parameters**

- `struct zynqmp_disp *disp`: Display controller

**Return**

0 on success, or the DMA channel request error otherwise

#### <a id="c-zynqmp_disp_enable"></a>`zynqmp_disp_enable()`

```c
void zynqmp_disp_enable(struct zynqmp_disp *disp)
```

Enable the display controller

**Parameters**

- `struct zynqmp_disp *disp`: Display controller

#### <a id="c-zynqmp_disp_disable"></a>`zynqmp_disp_disable()`

```c
void zynqmp_disp_disable(struct zynqmp_disp *disp)
```

Disable the display controller

**Parameters**

- `struct zynqmp_disp *disp`: Display controller

#### <a id="c-zynqmp_disp_setup_clock"></a>`zynqmp_disp_setup_clock()`

```c
int zynqmp_disp_setup_clock(struct zynqmp_disp *disp, unsigned long mode_clock)
```

Configure the display controller pixel clock rate

**Parameters**

- `struct zynqmp_disp *disp`: Display controller
- `unsigned long mode_clock`: The pixel clock rate, in Hz

**Return**

0 on success, or a negative error clock otherwise



#### <a id="c-struct-zynqmp_dp_link_config"></a>`struct zynqmp_dp_link_config`

Common link config between source and sink

**Definition**

```c
struct zynqmp_dp_link_config {
    int max_rate;
    u8 max_lanes;
};
```

**Members**

- `max_rate`: maximum link rate
- `max_lanes`: maximum number of lanes

#### <a id="c-struct-zynqmp_dp_mode"></a>`struct zynqmp_dp_mode`

Configured mode of DisplayPort

**Definition**

```c
struct zynqmp_dp_mode {
    const char *fmt;
    int pclock;
    u8 bw_code;
    u8 lane_cnt;
};
```

**Members**

- `fmt`: format identifier string
- `pclock`: pixel clock frequency of current mode
- `bw_code`: code for bandwidth(link rate)
- `lane_cnt`: number of lanes

#### <a id="c-struct-zynqmp_dp_config"></a>`struct zynqmp_dp_config`

Configuration of DisplayPort from DTS

**Definition**

```c
struct zynqmp_dp_config {
    u8 misc0;
    u8 misc1;
    u8 bpp;
};
```

**Members**

- `misc0`: misc0 configuration (per DP v1.2 spec)
- `misc1`: misc1 configuration (per DP v1.2 spec)
- `bpp`: bits per pixel

#### <a id="c-enum-test_pattern"></a>`enum test_pattern`

Test patterns for test testing

**Constants**

- `TEST_VIDEO`: Use regular video input
- `TEST_TPS1`: Link training symbol pattern TPS1 (/D10.2/)
- `TEST_TPS2`: Link training symbol pattern TPS2
- `TEST_TPS3`: Link training symbol pattern TPS3 (for HBR2)
- `TEST_SYMBOL_ERROR`: Symbol error measurement pattern
- `TEST_PRBS7`: Output of the PRBS7 (x^7 + x^6 + 1) polynomial
- `TEST_80BIT_CUSTOM`: A custom 80-bit pattern
- `TEST_CP2520`: HBR2 compliance eye pattern

#### <a id="c-struct-zynqmp_dp_test"></a>`struct zynqmp_dp_test`

Configuration for test mode

**Definition**

```c
struct zynqmp_dp_test {
    enum test_pattern pattern;
    bool enhanced, downspread, active;
    u8 custom[10];
    u8 train_set[ZYNQMP_DP_MAX_LANES];
    u8 bw_code;
    u8 link_cnt;
};
```

**Members**

- `pattern`: The test pattern
- `enhanced`: Use enhanced framing
- `downspread`: Use SSC
- `active`: Whether test mode is active
- `custom`: Custom pattern for `TEST_80BIT_CUSTOM`
- `train_set`: Voltage/preemphasis settings
- `bw_code`: Bandwidth code for the link
- `link_cnt`: Number of lanes

#### <a id="c-struct-zynqmp_dp_train_set_priv"></a>`struct zynqmp_dp_train_set_priv`

Private data for train_set debugfs files

**Definition**

```c
struct zynqmp_dp_train_set_priv {
    struct zynqmp_dp *dp;
    int lane;
};
```

**Members**

- `dp`: DisplayPort IP core structure
- `lane`: The lane for this file

#### <a id="c-struct-zynqmp_dp"></a>`struct zynqmp_dp`

Xilinx DisplayPort core

**Definition**

```c
struct zynqmp_dp {
    struct drm_dp_aux aux;
    struct drm_bridge bridge;
    struct work_struct hpd_work;
    struct work_struct hpd_irq_work;
    struct completion aux_done;
    struct mutex lock;
    struct drm_bridge *next_bridge;
    struct device *dev;
    struct zynqmp_dpsub *dpsub;
    void __iomem *iomem;
    struct reset_control *reset;
    struct phy *phy[ZYNQMP_DP_MAX_LANES];
    enum drm_connector_status status;
    int irq;
    bool enabled;
    bool ignore_aux_errors;
    bool ignore_hpd;
    struct zynqmp_dp_train_set_priv debugfs_train_set[ZYNQMP_DP_MAX_LANES];
    struct zynqmp_dp_mode mode;
    struct zynqmp_dp_link_config link_config;
    struct zynqmp_dp_test test;
    struct zynqmp_dp_config config;
    u8 dpcd[DP_RECEIVER_CAP_SIZE];
    u8 train_set[ZYNQMP_DP_MAX_LANES];
    u8 num_lanes;
};
```

**Members**

- `aux`: aux channel
- `bridge`: DRM bridge for the DP encoder
- `hpd_work`: hot plug detection worker
- `hpd_irq_work`: hot plug detection IRQ worker
- `aux_done`: Completed when we get an AUX reply or timeout
- `lock`: Mutex protecting this struct and register access (but not AUX)
- `next_bridge`: The downstream bridge
- `dev`: device structure
- `dpsub`: Display subsystem
- `iomem`: device I/O memory for register access
- `reset`: reset controller
- `phy`: PHY handles for DP lanes
- `status`: connection status
- `irq`: irq
- `enabled`: flag to indicate if the device is enabled
- `ignore_aux_errors`: If set, AUX errors are suppressed
- `ignore_hpd`: If set, HPD events and IRQs are ignored
- `debugfs_train_set`: Debugfs private data for **train_set**
- `mode`: current mode between IP core and sink device
- `link_config`: common link configuration between IP core and sink device
- `test`: Configuration for test mode
- `config`: IP core configuration from DTS
- `dpcd`: DP configuration data from currently connected sink device
- `train_set`: set of training data
- `num_lanes`: number of enabled phy lanes

**Description**

**lock** covers the link configuration in this struct and the device's
registers. It does not cover **aux** or **ignore_aux_errors**. It is not strictly
required for any of the members which are only modified at probe/remove time
(e.g. **dev**).

#### <a id="c-zynqmp_dp_phy_init"></a>`zynqmp_dp_phy_init()`

```c
int zynqmp_dp_phy_init(struct zynqmp_dp *dp)
```

Initialize the phy

**Parameters**

- `struct zynqmp_dp *dp`: DisplayPort IP core structure

**Description**

Initialize the phy.

**Return**

0 if the phy instances are initialized correctly, or the error code
returned from the callee functions.

#### <a id="c-zynqmp_dp_phy_exit"></a>`zynqmp_dp_phy_exit()`

```c
void zynqmp_dp_phy_exit(struct zynqmp_dp *dp)
```

Exit the phy

**Parameters**

- `struct zynqmp_dp *dp`: DisplayPort IP core structure

**Description**

Exit the phy.

#### <a id="c-zynqmp_dp_phy_probe"></a>`zynqmp_dp_phy_probe()`

```c
int zynqmp_dp_phy_probe(struct zynqmp_dp *dp)
```

Probe the PHYs

**Parameters**

- `struct zynqmp_dp *dp`: DisplayPort IP core structure

**Description**

Probe PHYs for all lanes. Less PHYs may be available than the number of
lanes, which is not considered an error as long as at least one PHY is
found. The caller can check dp->num_lanes to check how many PHYs were found.

**Return**

* 0                          - Success
* -ENXIO                     - No PHY found
* -EPROBE_DEFER              - Probe deferral requested
* Other negative value       - PHY retrieval failure

#### <a id="c-zynqmp_dp_phy_ready"></a>`zynqmp_dp_phy_ready()`

```c
int zynqmp_dp_phy_ready(struct zynqmp_dp *dp)
```

Check if PHY is ready

**Parameters**

- `struct zynqmp_dp *dp`: DisplayPort IP core structure

**Description**

Check if PHY is ready. If PHY is not ready, wait 1ms to check for 100 times.
This amount of delay was suggested by IP designer.

**Return**

0 if PHY is ready, or -ENODEV if PHY is not ready.

#### <a id="c-zynqmp_dp_max_rate"></a>`zynqmp_dp_max_rate()`

```c
int zynqmp_dp_max_rate(int link_rate, u8 lane_num, u8 bpp)
```

Calculate and return available max pixel clock

**Parameters**

- `int link_rate`: link rate (Kilo-bytes / sec)
- `u8 lane_num`: number of lanes
- `u8 bpp`: bits per pixel

**Return**

max pixel clock (KHz) supported by current link config.

#### <a id="c-zynqmp_dp_mode_configure"></a>`zynqmp_dp_mode_configure()`

```c
int zynqmp_dp_mode_configure(struct zynqmp_dp *dp, int pclock, u8 current_bw)
```

Configure the link values

**Parameters**

- `struct zynqmp_dp *dp`: DisplayPort IP core structure
- `int pclock`: pixel clock for requested display mode
- `u8 current_bw`: current link rate

**Description**

Find the link configuration values, rate and lane count for requested pixel
clock **pclock**. The **pclock** is stored in the mode to be used in other
functions later. The returned rate is downshifted from the current rate
**current_bw**.

**Return**

Current link rate code, or -EINVAL.

#### <a id="c-zynqmp_dp_adjust_train"></a>`zynqmp_dp_adjust_train()`

```c
void zynqmp_dp_adjust_train(struct zynqmp_dp *dp, u8 link_status[DP_LINK_STATUS_SIZE])
```

Adjust train values

**Parameters**

- `struct zynqmp_dp *dp`: DisplayPort IP core structure
- `u8 link_status[DP_LINK_STATUS_SIZE]`: link status from sink which contains requested training values

#### <a id="c-zynqmp_dp_update_vs_emph"></a>`zynqmp_dp_update_vs_emph()`

```c
int zynqmp_dp_update_vs_emph(struct zynqmp_dp *dp, u8 *train_set)
```

Update the training values

**Parameters**

- `struct zynqmp_dp *dp`: DisplayPort IP core structure
- `u8 *train_set`: A set of training values

**Description**

Update the training values based on the request from sink. The mapped values
are predefined, and values(vs, pe, pc) are from the device manual.

**Return**

0 if vs and emph are updated successfully, or the error code returned
by [`drm_dp_dpcd_write()`](/kernel/hardware/gpu/drm-kms-helpers.md#c-drm_dp_dpcd_write).

#### <a id="c-zynqmp_dp_link_train_cr"></a>`zynqmp_dp_link_train_cr()`

```c
int zynqmp_dp_link_train_cr(struct zynqmp_dp *dp)
```

Train clock recovery

**Parameters**

- `struct zynqmp_dp *dp`: DisplayPort IP core structure

**Return**

0 if clock recovery train is done successfully, or corresponding
error code.

#### <a id="c-zynqmp_dp_link_train_ce"></a>`zynqmp_dp_link_train_ce()`

```c
int zynqmp_dp_link_train_ce(struct zynqmp_dp *dp)
```

Train channel equalization

**Parameters**

- `struct zynqmp_dp *dp`: DisplayPort IP core structure

**Return**

0 if channel equalization train is done successfully, or
corresponding error code.

#### <a id="c-zynqmp_dp_setup"></a>`zynqmp_dp_setup()`

```c
int zynqmp_dp_setup(struct zynqmp_dp *dp, u8 bw_code, u8 lane_cnt, bool enhanced, bool downspread)
```

Set up major link parameters

**Parameters**

- `struct zynqmp_dp *dp`: DisplayPort IP core structure
- `u8 bw_code`: The link bandwidth as a multiple of 270 MHz
- `u8 lane_cnt`: The number of lanes to use
- `bool enhanced`: Use enhanced framing
- `bool downspread`: Enable spread-spectrum clocking

**Return**

0 on success, or -errno on failure

#### <a id="c-zynqmp_dp_train"></a>`zynqmp_dp_train()`

```c
int zynqmp_dp_train(struct zynqmp_dp *dp)
```

Train the link

**Parameters**

- `struct zynqmp_dp *dp`: DisplayPort IP core structure

**Return**

0 if all trains are done successfully, or corresponding error code.

#### <a id="c-zynqmp_dp_train_loop"></a>`zynqmp_dp_train_loop()`

```c
void zynqmp_dp_train_loop(struct zynqmp_dp *dp)
```

Downshift the link rate during training

**Parameters**

- `struct zynqmp_dp *dp`: DisplayPort IP core structure

**Description**

Train the link by downshifting the link rate if training is not successful.

#### <a id="c-zynqmp_dp_aux_cmd_submit"></a>`zynqmp_dp_aux_cmd_submit()`

```c
int zynqmp_dp_aux_cmd_submit(struct zynqmp_dp *dp, u32 cmd, u16 addr, u8 *buf, u8 bytes, u8 *reply)
```

Submit aux command

**Parameters**

- `struct zynqmp_dp *dp`: DisplayPort IP core structure
- `u32 cmd`: aux command
- `u16 addr`: aux address
- `u8 *buf`: buffer for command data
- `u8 bytes`: number of bytes for **buf**
- `u8 *reply`: reply code to be returned

**Description**

Submit an aux command. All aux related commands, native or i2c aux
read/write, are submitted through this function. The function is mapped to
the transfer function of struct drm_dp_aux. This function involves in
multiple register reads/writes, thus synchronization is needed, and it is
done by drm_dp_helper using **hw_mutex**. The calling thread goes into sleep
if there's no immediate reply to the command submission. The reply code is
returned at **reply** if **reply** != NULL.

**Return**

0 if the command is submitted properly, or corresponding error code:
-EBUSY when there is any request already being processed
-ETIMEDOUT when receiving reply is timed out
-EIO when received bytes are less than requested

#### <a id="c-zynqmp_dp_aux_init"></a>`zynqmp_dp_aux_init()`

```c
int zynqmp_dp_aux_init(struct zynqmp_dp *dp)
```

Initialize and register the DP AUX

**Parameters**

- `struct zynqmp_dp *dp`: DisplayPort IP core structure

**Description**

Program the AUX clock divider and filter and register the DP AUX adapter.

**Return**

0 on success, error value otherwise

#### <a id="c-zynqmp_dp_aux_cleanup"></a>`zynqmp_dp_aux_cleanup()`

```c
void zynqmp_dp_aux_cleanup(struct zynqmp_dp *dp)
```

Cleanup the DP AUX

**Parameters**

- `struct zynqmp_dp *dp`: DisplayPort IP core structure

**Description**

Unregister the DP AUX adapter.

#### <a id="c-zynqmp_dp_update_misc"></a>`zynqmp_dp_update_misc()`

```c
void zynqmp_dp_update_misc(struct zynqmp_dp *dp)
```

Write the misc registers

**Parameters**

- `struct zynqmp_dp *dp`: DisplayPort IP core structure

**Description**

The misc register values are stored in the structure, and this
function applies the values into the registers.

#### <a id="c-zynqmp_dp_set_format"></a>`zynqmp_dp_set_format()`

```c
int zynqmp_dp_set_format(struct zynqmp_dp *dp, const struct drm_display_info *info, enum zynqmp_dpsub_format format, unsigned int bpc)
```

Set the input format

**Parameters**

- `struct zynqmp_dp *dp`: DisplayPort IP core structure
- `const struct drm_display_info *info`: Display info
- `enum zynqmp_dpsub_format format`: input format
- `unsigned int bpc`: bits per component

**Description**

Update misc register values based on input **format** and **bpc**.

**Return**

0 on success, or -EINVAL.

#### <a id="c-zynqmp_dp_encoder_mode_set_transfer_unit"></a>`zynqmp_dp_encoder_mode_set_transfer_unit()`

```c
void zynqmp_dp_encoder_mode_set_transfer_unit(struct zynqmp_dp *dp, const struct drm_display_mode *mode)
```

Set the transfer unit values

**Parameters**

- `struct zynqmp_dp *dp`: DisplayPort IP core structure
- `const struct drm_display_mode *mode`: requested display mode

**Description**

Set the transfer unit, and calculate all transfer unit size related values.
Calculation is based on DP and IP core specification.

#### <a id="c-zynqmp_dp_encoder_mode_set_stream"></a>`zynqmp_dp_encoder_mode_set_stream()`

```c
void zynqmp_dp_encoder_mode_set_stream(struct zynqmp_dp *dp, const struct drm_display_mode *mode)
```

Configure the main stream

**Parameters**

- `struct zynqmp_dp *dp`: DisplayPort IP core structure
- `const struct drm_display_mode *mode`: requested display mode

**Description**

Configure the main stream based on the requested mode **mode**. Calculation is
based on IP core specification.

#### <a id="c-zynqmp_dp_disp_connected_live_layer"></a>`zynqmp_dp_disp_connected_live_layer()`

```c
struct zynqmp_disp_layer * zynqmp_dp_disp_connected_live_layer(struct zynqmp_dp *dp)
```

Return the first connected live layer

**Parameters**

- `struct zynqmp_dp *dp`: DisplayPort IP core structure

**Return**

The first connected live display layer or NULL if none of the live
layers are connected.

#### <a id="c-zynqmp_dp_set_test_pattern"></a>`zynqmp_dp_set_test_pattern()`

```c
int zynqmp_dp_set_test_pattern(struct zynqmp_dp *dp, enum test_pattern pattern, u8 *const custom)
```

Configure the link for a test pattern

**Parameters**

- `struct zynqmp_dp *dp`: DisplayPort IP core structure
- `enum test_pattern pattern`: The test pattern to configure
- `u8 *const custom`: The custom pattern to use if **pattern** is `TEST_80BIT_CUSTOM`

**Return**

0 on success, or negative errno on (DPCD) failure

#### <a id="c-zynqmp_dp_enable_vblank"></a>`zynqmp_dp_enable_vblank()`

```c
void zynqmp_dp_enable_vblank(struct zynqmp_dp *dp)
```

Enable vblank

**Parameters**

- `struct zynqmp_dp *dp`: DisplayPort IP core structure

**Description**

Enable vblank interrupt

#### <a id="c-zynqmp_dp_disable_vblank"></a>`zynqmp_dp_disable_vblank()`

```c
void zynqmp_dp_disable_vblank(struct zynqmp_dp *dp)
```

Disable vblank

**Parameters**

- `struct zynqmp_dp *dp`: DisplayPort IP core structure

**Description**

Disable vblank interrupt



#### <a id="c-zynqmp_dpsub_drm_handle_vblank"></a>`zynqmp_dpsub_drm_handle_vblank()`

```c
void zynqmp_dpsub_drm_handle_vblank(struct zynqmp_dpsub *dpsub)
```

Handle the vblank event

**Parameters**

- `struct zynqmp_dpsub *dpsub`: DisplayPort subsystem

**Description**

This function handles the vblank interrupt, and sends an event to
CRTC object. This will be called by the DP vblank interrupt handler.

---

# drm/amdgpu AMDgpu driver

_Peios Kernel / Hardware and drivers / Graphics / amdgpu_

> The drm/amdgpu driver supports all AMD Radeon GPUs based on the Graphics Core Next (GCN), Radeon DNA (RDNA), and Compute DNA (CDNA) architectures.

<a id="rst-drm-amdgpu-amdgpu-driver"></a>

The drm/amdgpu driver supports all AMD Radeon GPUs based on the Graphics Core Next (GCN), Radeon DNA (RDNA), and Compute DNA (CDNA) architectures.

- [Core Driver Infrastructure](</kernel/hardware/gpu/amdgpu/driver-core.md>)
- [Ring Buffer](</kernel/hardware/gpu/amdgpu/ring-buffer.md>)
- [amd-hardware-list-info](<https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/Documentation/gpu/amdgpu/amd-hardware-list-info.rst?id=9021cc14f7d98b4a1d2c932f52c5343d4d0f6b92>)
- [Module Parameters](</kernel/hardware/gpu/amdgpu/module-parameters.md>)
- [drm/amdgpu - Graphics and Compute (GC)](</kernel/hardware/gpu/amdgpu-gc/index.md>)
- [drm/amd/display - Display Core (DC)](</kernel/hardware/gpu/amdgpu-display/index.md>)
- [User Mode Queues](</kernel/hardware/gpu/amdgpu/userq.md>)
- [dGPU firmware flashing](</kernel/hardware/gpu/amdgpu/flashing.md>)
- [AMDGPU XGMI Support](</kernel/hardware/gpu/amdgpu/xgmi.md>)
- [AMDGPU RAS Support](</kernel/hardware/gpu/amdgpu/ras.md>)
- [GPU Power/Thermal Controls and Monitoring](</kernel/hardware/gpu/amdgpu/thermal.md>)
- [Misc AMDGPU driver information](</kernel/hardware/gpu/amdgpu/driver-misc.md>)
- [GPU Debugging](</kernel/hardware/gpu/amdgpu/debugging.md>)
- [AMDGPU DebugFS](</kernel/hardware/gpu/amdgpu/debugfs.md>)
- [AMDGPU Process Isolation](</kernel/hardware/gpu/amdgpu/process-isolation.md>)
- [amdgpu-glossary](<https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/Documentation/gpu/amdgpu/amdgpu-glossary.rst?id=9021cc14f7d98b4a1d2c932f52c5343d4d0f6b92>)

---

# AMD Hardware Components Information per Product

_Peios Kernel / Hardware and drivers / Graphics / amdgpu_

> On this page, you can find the AMD product name and which component version is part of it.

<a id="rst-amd-hardware-components-information-per-product"></a>

On this page, you can find the AMD product name and which component version is part of it.

<a id="rst-accelerated-processing-units-apu-info"></a>

## Accelerated Processing Units (APU) Info



| Product Name | Code Reference | DCN/DCE version | GC version | VCE/UVD/VCN version | SDMA version | MP0 version | MP1 version |
|---|---|---|---|---|---|---|---|
| Radeon R\* Graphics | CARRIZO/STONEY | DCE 11 | 8 | VCE 3 / UVD 6 | 3 | n/a | 8 |
| Ryzen 3000 series / AMD Ryzen Embedded V1\*/R1\* with Radeon Vega Gfx | RAVEN/PICASSO | DCN 1.0 | 9.1.0 | VCN 1.0 | 4.1.0 | 10.0.0 | 10.0.0 |
| Ryzen 4000 series | RENOIR | DCN 2.1 | 9.3 | VCN 2.2 | 4.1.2 | 11.0.3 | 12.0.1 |
| Ryzen 3000 series / AMD Ryzen Embedded V1\*/R1\* with Radeon Vega Gfx | RAVEN2 | DCN 1.0 | 9.2.2 | VCN 1.0.1 | 4.1.1 | 10.0.1 | 10.0.1 |
| SteamDeck | VANGOGH | DCN 3.0.1 | 10.3.1 | VCN 3.1.0 | 5.2.1 | 11.5.0 | 11.5.0 |
| Ryzen 5000 series / Ryzen 7x30 series | GREEN SARDINE / Cezanne / Barcelo / Barcelo-R | DCN 2.1 | 9.3 | VCN 2.2 | 4.1.1 | 12.0.1 | 12.0.1 |
| Ryzen 6000 series / Ryzen 7x35 series / Ryzen 7x36 series | YELLOW CARP / Rembrandt / Rembrandt-R | 3.1.2 | 10.3.3 | VCN 3.1.1 | 5.2.3 | 13.0.3 | 13.0.3 |
| Ryzen 7000 series (AM5) | Raphael | 3.1.5 | 10.3.6 | 3.1.2 | 5.2.6 | 13.0.5 | 13.0.5 |
| Ryzen 9000 series (AM5) | Granite Ridge | 3.1.5 | 10.3.6 | 3.1.2 | 5.2.6 | 13.0.5 | 13.0.5 |
| Ryzen 7x45 series (FL1) | Dragon Range | 3.1.5 | 10.3.6 | 3.1.2 | 5.2.6 | 13.0.5 | 13.0.5 |
| Ryzen 7x20 series | Mendocino | 3.1.6 | 10.3.7 | 3.1.1 | 5.2.7 | 13.0.8 | 13.0.8 |
| Ryzen 7x40 series | Phoenix | 3.1.4 | 11.0.1 / 11.0.4 | 4.0.2 | 6.0.1 | 13.0.4 / 13.0.11 | 13.0.4 / 13.0.11 |
| Ryzen 8x40 series | Hawk Point | 3.1.4 | 11.0.1 / 11.0.4 | 4.0.2 | 6.0.1 | 13.0.4 / 13.0.11 | 13.0.4 / 13.0.11 |
| Ryzen AI 300 series | Strix Point | 3.5.0 | 11.5.0 | 4.0.5 | 6.1.0 | 14.0.0 | 14.0.0 |
| Ryzen AI 330 series | Krackan Point | 3.6.0 | 11.5.3 | 4.0.5 | 6.1.3 | 14.0.5 | 14.0.5 |
| Ryzen AI 350 series | Krackan Point | 3.5.0 | 11.5.2 | 4.0.5 | 6.1.2 | 14.0.4 | 14.0.4 |
| Ryzen AI Max 300 series | Strix Halo | 3.5.1 | 11.5.1 | 4.0.6 | 6.1.1 | 14.0.1 | 14.0.1 |
| Ryzen AI 9 475 / 470 / 465 | Gorgon Point | 3.5.0 | 11.5.0 | 4.0.5 | 6.1.0 | 14.0.0 | 14.0.0 |
| Ryzen AI 7 450 | Gorgon Point | 3.5.0 | 11.5.2 | 4.0.5 | 6.1.2 | 14.0.4 | 14.0.4 |
| Ryzen AI 5 440 / 435 | Gorgon Point | 3.6.0 | 11.5.3 | 4.0.5 | 6.1.3 | 14.0.5 | 14.0.5 |


<a id="rst-discrete-gpu-info"></a>

## Discrete GPU Info



| Product Name | Code Reference | DCN/DCE version | GC version | VCN version | SDMA version | MP0 version | MP1 version |
|---|---|---|---|---|---|---|---|
| AMD Radeon (TM) HD 8500M/ 8600M /M200 /M320 /M330 /M335 Series | HAINAN | -- | 6 | -- | -- | -- | 6 |
| AMD Radeon HD 7800 /7900 /FireGL Series | TAHITI | DCE 6 | 6 | VCE 1 / UVD 3 | -- | -- | 6 |
| AMD Radeon R7 (TM\|HD) M265 /M370 /8500M /8600 /8700 /8700M | OLAND | DCE 6 | 6 | -- / UVD 3 | -- | -- | 6 |
| AMD Radeon (TM) (HD\|R7) 7800 /7970 /8800 /8970 /370/ Series | PITCAIRN | DCE 6 | 6 | VCE 1 / UVD 3 | -- | -- | 6 |
| AMD Radeon (TM\|R7\|R9\|HD) E8860 /M360 /7700 /7800 /8800 /9000(M) /W4100 Series | VERDE | DCE 6 | 6 | VCE 1 / UVD 3 | -- | -- | 6 |
| AMD Radeon HD M280X /M380 /7700 /8950 /W5100 | BONAIRE | DCE 8 | 7 | VCE 2 / UVD 4.2 | 1 | -- | 7 |
| AMD Radeon (R9\|TM) 200 /390 /W8100 /W9100 Series | HAWAII | DCE 8 | 7 | VCE 2 / UVD 4.2 | 1 | -- | 7 |
| AMD Radeon (TM) R(5\|7) M315 /M340 /M360 | TOPAZ | \* | 8 | -- | 2 | n/a | 7 |
| AMD Radeon (TM) R9 200 /380 /W7100 /S7150 /M390 /M395 Series | TONGA | DCE 10 | 8 | VCE 3 / UVD 5 | 3 | n/a | 7 |
| AMD Radeon (FirePro) (TM) R9 Fury Series | FIJI | DCE 10 | 8 | VCE 3 / UVD 6 | 3 | n/a | 7 |
| Radeon RX 470 /480 /570 /580 /590 Series - AMD Radeon (TM) (Pro WX) 5100 /E9390 /E9560 /E9565 /V7350 /7100 /P30PH | POLARIS10 | DCE 11.2 | 8 | VCE 3.4 / UVD 6.3 | 3 | n/a | 7 |
| Radeon (TM) (RX\|Pro WX) E9260 /460 /V5300X /550 /560(X) Series | POLARIS11 | DCE 11.2 | 8 | VCE 3.4 / UVD 6.3 | 3 | n/a | 7 |
| Radeon (RX/Pro) 500 /540(X) /550 /640 /WX2100 /WX3100 /WX200 Series | POLARIS12 | DCE 11.2 | 8 | VCE 3.4 / UVD 6.3 | 3 | n/a | 7 |
| Radeon (RX\|TM) (PRO\|WX) Vega /MI25 /V320 /V340L /8200 /9100 /SSG MxGPU | VEGA10 | DCE 12 | 9.0.1 | VCE 4.0.0 / UVD 7.0.0 | 4.0.0 | 9.0.0 | 9.0.0 |
| AMD Radeon (Pro) VII /MI50 /MI60 | VEGA20 | DCE 12 | 9.4.0 | VCE 4.1.0 / UVD 7.2.0 | 4.2.0 | 11.0.2 | 11.0.2 |
| MI100 | ARCTURUS | \* | 9.4.1 | VCN 2.5.0 | 4.2.2 | 11.0.4 | 11.0.2 |
| MI200 Series | ALDEBARAN | \* | 9.4.2 | VCN 2.6.0 | 4.4.0 | 13.0.2 | 13.0.2 |
| MI300 Series | AQUA\_VANJARAM | \* | 9.4.3 | VCN 4.0.3 | 4.4.2 | 13.0.6 | 13.0.6 |
| AMD Radeon (RX\|Pro) 5600(M\|XT) /5700 (M\|XT\|XTB) /W5700 | NAVI10 | DCN 2.0.0 | 10.1.10 | VCN 2.0.0 | 5.0.0 | 11.0.0 | 11.0.0 |
| AMD Radeon (Pro) 5300 /5500XTB/5500(XT\|M) /W5500M /W5500 | NAVI14 | DCN 2.0.0 | 10.1.1 | VCN 2.0.2 | 5.0.2 | 11.0.5 | 11.0.5 |
| AMD Radeon RX 6800(XT) /6900(XT) /W6800 | SIENNA\_CICHLID | DCN 3.0.0 | 10.3.0 | VCN 3.0.0 | 5.2.0 | 11.0.7 | 11.0.7 |
| AMD Radeon RX 6700 XT / 6800M / 6700M | NAVY\_FLOUNDER | DCN 3.0.0 | 10.3.2 | VCN 3.0.0 | 5.2.2 | 11.0.11 | 11.0.11 |
| AMD Radeon RX 6600(XT) /6600M /W6600 /W6600M | DIMGREY\_CAVEFISH | DCN 3.0.2 | 10.3.4 | VCN 3.0.16 | 5.2.4 | 11.0.12 | 11.0.12 |
| AMD Radeon RX 6500M /6300M /W6500M /W6300M | BEIGE\_GOBY | DCN 3.0.3 | 10.3.5 | VCN 3.0.33 | 5.2.5 | 11.0.13 | 11.0.13 |
| AMD Radeon RX 7900 XT /XTX |  | DCN 3.2.0 | 11.0.0 | VCN 4.0.0 | 6.0.0 | 13.0.0 | 13.0.0 |
| AMD Radeon RX 7800 XT |  | DCN 3.2.0 | 11.0.3 | VCN 4.0.0 | 6.0.3 | 13.0.10 | 13.0.10 |
| AMD Radeon RX 7600M (XT) /7700S /7600S |  | DCN 3.2.1 | 11.0.2 | VCN 4.0.4 | 6.0.2 | 13.0.7 | 13.0.7 |
| AMD Radeon RX 9070 (XT) |  | DCN 4.0.1 | 12.0.1 | VCN 5.0.0 | 7.0.1 | 14.0.3 | 14.0.3 |
| AMD Radeon RX 9060 XT |  | DCN 4.0.1 | 12.0.0 | VCN 5.0.0 | 7.0.0 | 14.0.2 | 14.0.2 |

---

# AMDGPU Glossary

_Peios Kernel / Hardware and drivers / Graphics / amdgpu_

> Here you can find some generic acronyms used in the amdgpu driver. Notice that we have a dedicated glossary for Display Core at 'Documentation/gpu/amdgpu/display/dc-glossary.rst'.

<a id="rst-amdgpu-glossary"></a>

Here you can find some generic acronyms used in the amdgpu driver. Notice that we have a dedicated glossary for Display Core at '[Documentation/gpu/amdgpu/display/dc-glossary.rst](/kernel/hardware/gpu/amdgpu-display/dc-glossary.md)'.



- **<a id="rst-term-active-cu-number"></a>active\_cu\_number**

  The number of CUs that are active on the system.  The number of active CUs may be less than SE \* SH \* CU depending on the board configuration.

- **<a id="rst-term-baco"></a>BACO**

  Bus Alive, Chip Off

- **<a id="rst-term-boco"></a>BOCO**

  Bus Off, Chip Off

- **<a id="rst-term-ce"></a>CE**

  Constant Engine

- **<a id="rst-term-cik"></a>CIK**

  Sea Islands

- **<a id="rst-term-cb"></a>CB**

  Color Buffer

- **<a id="rst-term-cp"></a>CP**

  Command Processor

- **<a id="rst-term-cpc"></a>CPC**

  Command Processor Compute

- **<a id="rst-term-cpf"></a>CPF**

  Command Processor Fetch

- **<a id="rst-term-cpg"></a>CPG**

  Command Processor Graphics

- **<a id="rst-term-cplib"></a>CPLIB**

  Content Protection Library

- **<a id="rst-term-cs"></a>CS**

  Command Submission

- **<a id="rst-term-csb"></a>CSB**

  Clear State Indirect Buffer

- **<a id="rst-term-cu"></a>CU**

  Compute Unit

- **<a id="rst-term-db"></a>DB**

  Depth Buffer

- **<a id="rst-term-dfs"></a>DFS**

  Digital Frequency Synthesizer

- **<a id="rst-term-ecp"></a>ECP**

  Enhanced Content Protection

- **<a id="rst-term-eop"></a>EOP**

  End Of Pipe/Pipeline

- **<a id="rst-term-flr"></a>FLR**

  Function Level Reset

- **<a id="rst-term-gart"></a>GART**

  Graphics Address Remapping Table.  This is the name we use for the GPUVM page table used by the GPU kernel driver.  It remaps system resources (memory or MMIO space) into the GPU's address space so the GPU can access them.  The name GART harkens back to the days of AGP when the platform provided an MMU that the GPU could use to get a contiguous view of scattered pages for DMA.  The MMU has since moved on to the GPU, but the name stuck.

- **<a id="rst-term-gc"></a>GC**

  Graphics and Compute

- **<a id="rst-term-gds"></a>GDS**

  Global Data Share

- **<a id="rst-term-ge"></a>GE**

  Geometry Engine

- **<a id="rst-term-gmc"></a>GMC**

  Graphic Memory Controller

- **<a id="rst-term-gpr"></a>GPR**

  General Purpose Register

- **<a id="rst-term-gpuvm"></a>GPUVM**

  GPU Virtual Memory.  This is the GPU's MMU.  The GPU supports multiple virtual address spaces that can be in flight at any given time.  These allow the GPU to remap VRAM and system resources into GPU virtual address spaces for use by the GPU kernel driver and applications using the GPU. These provide memory protection for different applications using the GPU.

- **<a id="rst-term-gtt"></a>GTT**

  Graphics Translation Tables.  This is a memory pool managed through TTM which provides access to system resources (memory or MMIO space) for use by the GPU. These addresses can be mapped into the "GART" GPUVM page table for use by the kernel driver or into per process GPUVM page tables for application usage.

- **<a id="rst-term-gws"></a>GWS**

  Global Wave Sync

- **<a id="rst-term-ih"></a>IH**

  Interrupt Handler

- **<a id="rst-term-iv"></a>IV**

  Interrupt Vector

- **<a id="rst-term-hqd"></a>HQD**

  Hardware Queue Descriptor

- **<a id="rst-term-ib"></a>IB**

  Indirect Buffer

- **<a id="rst-term-imu"></a>IMU**

  Integrated Management Unit (Power Management support)

- **<a id="rst-term-ip"></a>IP**

  Intellectual Property blocks

- **<a id="rst-term-kcq"></a>KCQ**

  Kernel Compute Queue

- **<a id="rst-term-kfd"></a>KFD**

  Kernel Fusion Driver

- **<a id="rst-term-kgq"></a>KGQ**

  Kernel Graphics Queue

- **<a id="rst-term-kiq"></a>KIQ**

  Kernel Interface Queue

- **<a id="rst-term-mc"></a>MC**

  Memory Controller

- **<a id="rst-term-mcbp"></a>MCBP**

  Mid Command Buffer Preemption

- **<a id="rst-term-me"></a>ME**

  MicroEngine (Graphics)

- **<a id="rst-term-mec"></a>MEC**

  MicroEngine Compute

- **<a id="rst-term-mes"></a>MES**

  MicroEngine Scheduler

- **<a id="rst-term-mmhub"></a>MMHUB**

  Multi-Media HUB

- **<a id="rst-term-mqd"></a>MQD**

  Memory Queue Descriptor

- **<a id="rst-term-pa"></a>PA**

  Primitive Assembler / Physical Address

- **<a id="rst-term-pde"></a>PDE**

  Page Directory Entry

- **<a id="rst-term-pfp"></a>PFP**

  Pre-Fetch Parser (Graphics)

- **<a id="rst-term-pplib"></a>PPLib**

  PowerPlay Library - PowerPlay is the power management component.

- **<a id="rst-term-prt"></a>PRT**

  Partially Resident Texture (also known as sparse residency)

- **<a id="rst-term-psp"></a>PSP**

  Platform Security Processor

- **<a id="rst-term-pte"></a>PTE**

  Page Table Entry

- **<a id="rst-term-rb"></a>RB**

  Render Backends. Some people called it ROPs.

- **<a id="rst-term-rlc"></a>RLC**

  RunList Controller. This name is a remnant of past ages and doesn't have much meaning today. It's a group of general-purpose helper engines for the GFX block. It's involved in GFX power management and SR-IOV, among other things.

- **<a id="rst-term-sc"></a>SC**

  Scan Converter

- **<a id="rst-term-sdma"></a>SDMA**

  System DMA

- **<a id="rst-term-se"></a>SE**

  Shader Engine

- **<a id="rst-term-sgpr"></a>SGPR**

  Scalar General-Purpose Registers

- **<a id="rst-term-sh"></a>SH**

  SHader array

- **<a id="rst-term-si"></a>SI**

  Southern Islands

- **<a id="rst-term-smu-smc"></a>SMU/SMC**

  System Management Unit / System Management Controller

- **<a id="rst-term-spi-amdgpu"></a>SPI (AMDGPU)**

  Shader Processor Input

- **<a id="rst-term-srlc"></a>SRLC**

  Save/Restore List Control

- **<a id="rst-term-srlg"></a>SRLG**

  Save/Restore List GPM\_MEM

- **<a id="rst-term-srls"></a>SRLS**

  Save/Restore List SRM\_MEM

- **<a id="rst-term-ss"></a>SS**

  Spread Spectrum

- **<a id="rst-term-sx"></a>SX**

  Shader Export

- **<a id="rst-term-ta"></a>TA**

  Trusted Application

- **<a id="rst-term-tc"></a>TC**

  Texture Cache

- **<a id="rst-term-tcp-amdgpu"></a>TCP (AMDGPU)**

  Texture Cache per Pipe. Even though the name "Texture" is part of this acronym, the TCP represents the path to memory shaders; i.e., it is not related to texture. The name is a leftover from older designs where shader stages had different cache designs; it refers to the L1 cache in older architectures.

- **<a id="rst-term-tmr"></a>TMR**

  Trusted Memory Region

- **<a id="rst-term-tmz"></a>TMZ**

  Trusted Memory Zone

- **<a id="rst-term-toc"></a>TOC**

  Table of Contents

- **<a id="rst-term-umc"></a>UMC**

  Unified Memory Controller

- **<a id="rst-term-umsch"></a>UMSCH**

  User Mode Scheduler

- **<a id="rst-term-utc-amdgpu"></a>UTC (AMDGPU)**

  Unified Translation Cache. UTC is equivalent to TLB. You might see a variation of this acronym with L at the end, i.e., UTCL followed by a number; L means the cache level (e.g., UTCL1 and UTCL2).

- **<a id="rst-term-uvd"></a>UVD**

  Unified Video Decoder

- **<a id="rst-term-vce"></a>VCE**

  Video Compression Engine

- **<a id="rst-term-vcn"></a>VCN**

  Video Codec Next

- **<a id="rst-term-vgpr"></a>VGPR**

  Vector General-Purpose Registers

- **<a id="rst-term-vmid"></a>VMID**

  Virtual Memory ID

- **<a id="rst-term-vpe"></a>VPE**

  Video Processing Engine

- **<a id="rst-term-xcc"></a>XCC**

  Accelerator Core Complex

- **<a id="rst-term-xcp"></a>XCP**

  Accelerator Core Partition

---

# AMDGPU DebugFS

_Peios Kernel / Hardware and drivers / Graphics / amdgpu_

> The amdgpu driver provides a number of debugfs files to aid in debugging issues in the driver. These are usually found in /sys/kernel/debug/dri/<num>.

<a id="rst-amdgpu-debugfs"></a>

The amdgpu driver provides a number of debugfs files to aid in debugging issues in the driver.  These are usually found in /sys/kernel/debug/dri/&lt;num&gt;.

<a id="rst-debugfs-files"></a>

## DebugFS Files

<a id="rst-amdgpu-benchmark"></a>

### amdgpu_benchmark

Run benchmarks using the DMA engine the driver uses for GPU memory paging. Write a number to the file to run the test.  The results are written to the kernel log.  VRAM is on device memory (dGPUs) or carve out (APUs) and GTT (Graphics Translation Tables) is system memory that is accessible by the GPU. The following tests are available:

- 1: simple test, VRAM to GTT and GTT to VRAM

- 2: simple test, VRAM to VRAM

- 3: GTT to VRAM, buffer size sweep, powers of 2

- 4: VRAM to GTT, buffer size sweep, powers of 2

- 5: VRAM to VRAM, buffer size sweep, powers of 2

- 6: GTT to VRAM, buffer size sweep, common display sizes

- 7: VRAM to GTT, buffer size sweep, common display sizes

- 8: VRAM to VRAM, buffer size sweep, common display sizes

<a id="rst-amdgpu-test-ib"></a>

### amdgpu_test_ib

Read this file to run simple IB (Indirect Buffer) tests on all kernel managed rings.  IBs are command buffers usually generated by userspace applications which are submitted to the kernel for execution on an particular GPU engine. This just runs the simple IB tests included in the kernel.  These tests are engine specific and verify that IB submission works.

<a id="rst-amdgpu-discovery"></a>

### amdgpu_discovery

Provides raw access to the IP discovery binary provided by the GPU.  Read this file to access the raw binary.  This is useful for verifying the contents of the IP discovery table.  It is chip specific.

<a id="rst-amdgpu-vbios"></a>

### amdgpu_vbios

Provides raw access to the ROM binary image from the GPU.  Read this file to access the raw binary.  This is useful for verifying the contents of the video BIOS ROM.  It is board specific.

<a id="rst-amdgpu-evict-gtt"></a>

### amdgpu_evict_gtt

Evict all buffers from the GTT memory pool.  Read this file to evict all buffers from this pool.

<a id="rst-amdgpu-evict-vram"></a>

### amdgpu_evict_vram

Evict all buffers from the VRAM memory pool.  Read this file to evict all buffers from this pool.

<a id="rst-amdgpu-gpu-recover"></a>

### amdgpu_gpu_recover

Trigger a GPU reset.  Read this file to trigger reset the entire GPU. All work currently running  on the GPU will be lost.

<a id="rst-amdgpu-ring-name"></a>

### amdgpu_ring\_&lt;name&gt;

Provides read access to the kernel managed ring buffers for each ring &lt;name&gt;. These are useful for debugging problems on a particular ring.  The ring buffer is how the CPU sends commands to the GPU.  The CPU writes commands into the buffer and then asks the GPU engine to process it.  This is the raw binary contents of the ring buffer.  Use a tool like UMR to decode the rings into human readable form.

<a id="rst-amdgpu-mqd-name"></a>

### amdgpu_mqd\_&lt;name&gt;

Provides read access to the kernel managed MQD (Memory Queue Descriptor) for ring &lt;name&gt; managed by the kernel driver.  MQDs define the features of the ring and are used to store the ring's state when it is not connected to hardware. The driver writes the requested ring features and metadata (GPU addresses of the ring itself and associated buffers) to the MQD and the firmware uses the MQD to populate the hardware when the ring is mapped to a hardware slot.  Only available on engines which use MQDs.  This provides access to the raw MQD binary.

<a id="rst-amdgpu-error-name"></a>

### amdgpu_error\_&lt;name&gt;

Provides an interface to set an error code on the dma fences associated with ring &lt;name&gt;.  The error code specified is propagated to all fences associated with the ring.  Use this to inject a fence error into a ring.

<a id="rst-amdgpu-pm-info"></a>

### amdgpu_pm_info

Provides human readable information about the power management features and state of the GPU.  This includes current GFX clock, Memory clock, voltages, average SoC power, temperature, GFX load, Memory load, SMU feature mask, VCN power state, clock and power gating features.

<a id="rst-amdgpu-firmware-info"></a>

### amdgpu_firmware_info

Lists the firmware versions for all firmwares used by the GPU.  Only entries with a non-0 version are valid.  If the version is 0, the firmware is not valid for the GPU.

<a id="rst-amdgpu-fence-info"></a>

### amdgpu_fence_info

Shows the last signalled and emitted fence sequence numbers for each kernel driver managed ring.  Fences are associated with submissions to the engine.  Emitted fences have been submitted to the ring and signalled fences have been signalled by the GPU.  Rings with a larger emitted fence value have outstanding work that is still being processed by the engine that owns that ring.  When the emitted and signalled fence values are equal, the ring is idle.

<a id="rst-amdgpu-gem-info"></a>

### amdgpu_gem_info

Lists all of the PIDs using the GPU and the GPU buffers that they have allocated.  This lists the buffer size, pool (VRAM, GTT, etc.), and buffer attributes (CPU access required, CPU cache attributes, etc.).

<a id="rst-amdgpu-vm-info"></a>

### amdgpu_vm_info

Lists all of the PIDs using the GPU and the GPU buffers that they have allocated as well as the status of those buffers relative to that process' GPU virtual address space (e.g., evicted, idle, invalidated, etc.).

<a id="rst-amdgpu-sa-info"></a>

### amdgpu_sa_info

Prints out all of the suballocations (sa) by the suballocation manager in the kernel driver.  Prints the GPU address, size, and fence info associated with each suballocation.  The suballocations are used internally within the kernel driver for various things.

<a id="rst-amdgpu-pool-mm"></a>

### amdgpu\_&lt;pool&gt;\_mm

Prints TTM information about the memory pool &lt;pool&gt;.

<a id="rst-amdgpu-vram"></a>

### amdgpu_vram

Provides direct access to VRAM.  Used by tools like UMR to inspect objects in VRAM.

<a id="rst-amdgpu-iomem"></a>

### amdgpu_iomem

Provides direct access to GTT memory.  Used by tools like UMR to inspect GTT memory.

<a id="rst-amdgpu-regs"></a>

### amdgpu_regs\_\*

Provides direct access to various register apertures on the GPU.  Used by tools like UMR to access GPU registers.

<a id="rst-amdgpu-regs2"></a>

### amdgpu_regs2

Provides an IOCTL interface used by UMR for interacting with GPU registers.

<a id="rst-amdgpu-sensors"></a>

### amdgpu_sensors

Provides an interface to query GPU power metrics (temperature, average power, etc.).  Used by tools like UMR to query GPU power metrics.

<a id="rst-amdgpu-gca-config"></a>

### amdgpu_gca_config

Provides an interface to query GPU details (Graphics/Compute Array config, PCI config, GPU family, etc.).  Used by tools like UMR to query GPU details.

<a id="rst-amdgpu-wave"></a>

### amdgpu_wave

Used to query GFX/compute wave information from the hardware.  Used by tools like UMR to query GFX/compute wave information.

<a id="rst-amdgpu-gpr"></a>

### amdgpu_gpr

Used to query GFX/compute GPR (General Purpose Register) information from the hardware.  Used by tools like UMR to query GPRs when debugging shaders.

<a id="rst-amdgpu-gprwave"></a>

### amdgpu_gprwave

Provides an IOCTL interface used by UMR for interacting with shader waves.

<a id="rst-amdgpu-fw-attestation"></a>

### amdgpu_fw_attestation

Provides an interface for reading back firmware attestation records.

---

# GPU Debugging

_Peios Kernel / Hardware and drivers / Graphics / amdgpu_

> The DebugFS section provides documentation on a number files to aid in debugging issues on the GPU.

<a id="rst-gpu-debugging"></a>

<a id="rst-general-debugging-options"></a>

## General Debugging Options

The DebugFS section provides documentation on a number files to aid in debugging issues on the GPU.

<a id="rst-gpuvm-debugging"></a>

## GPUVM Debugging

To aid in debugging GPU virtual memory related problems, the driver supports a number of options module parameters:

`vm_fault_stop` - If non-0, halt the GPU memory controller on a GPU page fault.

`vm_update_mode` - If non-0, use the CPU to update GPU page tables rather than the GPU.

<a id="rst-decoding-a-gpuvm-page-fault"></a>

## Decoding a GPUVM Page Fault

If you see a GPU page fault in the kernel log, you can decode it to figure out what is going wrong in your application.  A page fault in your kernel log may look something like this:



```text
[gfxhub0] no-retry page fault (src_id:0 ring:24 vmid:3 pasid:32777, for process glxinfo pid 2424 thread glxinfo:cs0 pid 2425)
  in page starting at address 0x0000800102800000 from IH client 0x1b (UTCL2)
VM_L2_PROTECTION_FAULT_STATUS:0x00301030
       Faulty UTCL2 client ID: TCP (0x8)
       MORE_FAULTS: 0x0
       WALKER_ERROR: 0x0
       PERMISSION_FAULTS: 0x3
       MAPPING_ERROR: 0x0
       RW: 0x0
```

First you have the memory hub, gfxhub and mmhub.  gfxhub is the memory hub used for graphics, compute, and sdma on some chips.  mmhub is the memory hub used for multi-media and sdma on some chips.

Next you have the vmid and pasid.  If the vmid is 0, this fault was likely caused by the kernel driver or firmware.  If the vmid is non-0, it is generally a fault in a user application.  The pasid is used to link a vmid to a system process id.  If the process is active when the fault happens, the process information will be printed.

The GPU virtual address that caused the fault comes next.

The client ID indicates the GPU block that caused the fault. Some common client IDs:

- CB/DB: The color/depth backend of the graphics pipe

- CPF: Command Processor Frontend

- CPC: Command Processor Compute

- CPG: Command Processor Graphics

- TCP/SQC/SQG: Shaders

- SDMA: SDMA engines

- VCN: Video encode/decode engines

- JPEG: JPEG engines

PERMISSION_FAULTS describe what faults were encountered:

- bit 0: the PTE was not valid

- bit 1: the PTE read bit was not set

- bit 2: the PTE write bit was not set

- bit 3: the PTE execute bit was not set

Finally, RW, indicates whether the access was a read (0) or a write (1).

In the example above, a shader (cliend id = TCP) generated a read (RW = 0x0) to an invalid page (PERMISSION_FAULTS = 0x3) at GPU virtual address 0x0000800102800000.  The user can then inspect their shader code and resource descriptor state to determine what caused the GPU page fault.

<a id="rst-umr"></a>

## UMR

[umr](<https://gitlab.freedesktop.org/tomstdenis/umr>)<a id="rst-umr-1"></a> is a general purpose GPU debugging and diagnostics tool.  Please see the umr [documentation](<https://umr.readthedocs.io/en/main/>)<a id="rst-documentation"></a> for more information about its capabilities.

<a id="rst-debugging-backlight-brightness"></a>

## Debugging backlight brightness

Default backlight brightness is intended to be set via the policy advertised by the firmware.  Firmware will often provide different defaults for AC or DC. Furthermore, some userspace software will save backlight brightness during the previous boot and attempt to restore it.

Some firmware also has support for a feature called "Custom Backlight Curves" where an input value for brightness is mapped along a linearly interpolated curve of brightness values that better match display characteristics.

In the event of problems happening with backlight, there is a trace event that can be enabled at bootup to log every brightness change request. This can help isolate where the problem is. To enable the trace event add the following to the kernel command line:

> tp_printk trace_event=amdgpu_dm:amdgpu_dm_brightness:mod:amdgpu trace_buf_size=1M

---

# Core Driver Infrastructure

_Peios Kernel / Hardware and drivers / Graphics / amdgpu_

> Each ASIC is a collection of hardware blocks. We refer to them as "IPs" (Intellectual Property blocks). Each IP encapsulates certain functionality. IPs are versioned and can also be mixed and matched. E.g., you might have two different…

<a id="rst-core-driver-infrastructure"></a>

<a id="rst-gpu-hardware-structure"></a>

## GPU Hardware Structure

Each ASIC is a collection of hardware blocks.  We refer to them as "IPs" (Intellectual Property blocks).  Each IP encapsulates certain functionality. IPs are versioned and can also be mixed and matched. E.g., you might have two different ASICs that both have System DMA (SDMA) 5.x IPs. The driver is arranged by IPs.  There are driver components to handle the initialization and operation of each IP.  There are also a bunch of smaller IPs that don't really need much if any driver interaction. Those end up getting lumped into the common stuff in the soc files. The soc files (e.g., vi.c, soc15.c nv.c) contain code for aspects of the SoC itself rather than specific IPs.  E.g., things like GPU resets and register access functions are SoC dependent.

An APU contains more than just CPU and GPU, it also contains all of the platform stuff (audio, usb, gpio, etc.).  Also, a lot of components are shared between the CPU, platform, and the GPU (e.g., SMU, PSP, etc.).  Specific components (CPU, GPU, etc.) usually have their interface to interact with those common components.  For things like S0i3 there is a ton of coordination required across all the components, but that is probably a bit beyond the scope of this section.

With respect to the GPU, we have the following major IPs:

- **GMC (Graphics Memory Controller)**

  This was a dedicated IP on older pre-vega chips, but has since become somewhat decentralized on vega and newer chips.  They now have dedicated memory hubs for specific IPs or groups of IPs.  We still treat it as a single component in the driver however since the programming model is still pretty similar.  This is how the different IPs on the GPU get the memory (VRAM or system memory). It also provides the support for per process GPU virtual address spaces.

- **IH (Interrupt Handler)**

  This is the interrupt controller on the GPU.  All of the IPs feed their interrupts into this IP and it aggregates them into a set of ring buffers that the driver can parse to handle interrupts from different IPs.

- **PSP (Platform Security Processor)**

  This handles security policy for the SoC and executes trusted applications, and validates and loads firmwares for other blocks.

- **SMU (System Management Unit)**

  This is the power management microcontroller.  It manages the entire SoC.  The driver interacts with it to control power management features like clocks, voltages, power rails, etc.

- **DCN (Display Controller Next)**

  This is the display controller.  It handles the display hardware. It is described in more details in [Display Core](</kernel/hardware/gpu/amdgpu-display/index.md#rst-amdgpu-display-core>).

- **SDMA (System DMA)**

  This is a multi-purpose DMA engine.  The kernel driver uses it for various things including paging and GPU page table updates.  It's also exposed to userspace for use by user mode drivers (OpenGL, Vulkan, etc.)

- **GC (Graphics and Compute)**

  This is the graphics and compute engine, i.e., the block that encompasses the 3D pipeline and shader blocks.  This is by far the largest block on the GPU.  The 3D pipeline has tons of sub-blocks.  In addition to that, it also contains the CP microcontrollers (ME, PFP, CE, MEC) and the RLC microcontroller.  It's exposed to userspace for user mode drivers (OpenGL, Vulkan, OpenCL, etc.). More details in [Graphics (GFX) and Compute](</kernel/hardware/gpu/amdgpu-gc/index.md#rst-amdgpu-gc>).

- **VCN (Video Core Next)**

  This is the multi-media engine.  It handles video and image encode and decode.  It's exposed to userspace for user mode drivers (VA-API, OpenMAX, etc.)

It is important to note that these blocks can interact with each other. The picture below illustrates some of the components and their interconnection:

![](/kernel/hardware/gpu/amdgpu/asset-8c7bcc208725-amd-overview-block.svg)

In the diagram, memory-related blocks are shown in green. Notice that specific IPs have a green square that represents a small hardware block named 'hub', which is responsible for interfacing with memory. All memory hubs are connected in the UMCs, which in turn are connected to memory blocks. As a note, pre-vega devices have a dedicated block for the Graphic Memory Controller (GMC), which was replaced by UMC and hubs in new architectures. In the driver code, you can identify this component by looking for the suffix hub, for example: gfxhub, dchub, mmhub, vmhub, etc. Keep in mind that the component's interaction with the memory block may vary across architectures. For example, on Navi and newer, GC and SDMA are both attached to GCHUB; on pre-Navi, SDMA goes through MMHUB; VCN, JPEG, and VPE go through MMHUB; DCN goes through DCHUB.

There is some protection for certain memory elements, and the PSP plays an essential role in this area. When a specific firmware is loaded into memory, the PSP takes steps to ensure it has a valid signature. It also stores firmware images in a protected memory area named Trusted Memory Area (TMR), so the OS or driver can't corrupt them at runtime. Another use of PSP is to support Trusted Applications (TA), which are basically small applications that run on the trusted processor and handles a trusted operation (e.g., HDCP). PSP is also used for encrypted memory for content protection via Trusted Memory Zone (TMZ).

Another critical IP is the SMU. It handles reset distribution, as well as clock, thermal, and power management for all IPs on the SoC. SMU also helps to balance performance and power consumption.

<a id="rst-gfx-compute-and-sdma-overall-behavior"></a>
<a id="rst-pipes-and-queues-description"></a>

## GFX, Compute, and SDMA Overall Behavior

> [!NOTE]
>
> For simplicity, whenever the term block is used in this section, it means GFX, Compute, and SDMA.

GFX, Compute and SDMA share a similar form of operation that can be abstracted to facilitate understanding of the behavior of these blocks. See the figure below illustrating the common components of these blocks:

![](/kernel/hardware/gpu/amdgpu/asset-362672c161d0-pipe-and-queue-abstraction.svg)

In the central part of this figure, you can see two hardware elements, one called **Pipes** and another called **Queues**; it is important to highlight that Queues must be associated with a Pipe and vice-versa. Every specific hardware IP may have a different number of Pipes and, in turn, a different number of Queues; for example, GFX 11 has two Pipes and two Queues per Pipe for the GFX front end.

Pipe is the hardware that processes the instructions available in the Queues; in other words, it is a thread executing the operations inserted in the Queue. One crucial characteristic of Pipes is that they can only execute one Queue at a time; no matter if the hardware has multiple Queues in the Pipe, it only runs one Queue per Pipe.

Pipes have the mechanics of swapping between queues at the hardware level. Nonetheless, they only make use of Queues that are considered mapped. Pipes can switch between queues based on any of the following inputs:

1. Command Stream;

2. Packet by Packet;

3. Other hardware requests the change (e.g., MES).

Queues within Pipes are defined by the Hardware Queue Descriptors (HQD). Associated with the HQD concept, we have the Memory Queue Descriptor (MQD), which is responsible for storing information about the state of each of the available Queues in the memory. The state of a Queue contains information such as the GPU virtual address of the queue itself, save areas, doorbell, etc. The MQD also stores the HQD registers, which are vital for activating or deactivating a given Queue.  The scheduling firmware (e.g., MES) is responsible for loading HQDs from MQDs and vice versa.

The Queue-switching process can also happen with the firmware requesting the preemption or unmapping of a Queue. The firmware waits for the HQD_ACTIVE bit to change to low before saving the state into the MQD. To make a different Queue become active, the firmware copies the MQD state into the HQD registers and loads any additional state. Finally, it sets the HQD_ACTIVE bit to high to indicate that the queue is active.  The Pipe will then execute work from active Queues.

<a id="rst-driver-structure"></a>

## Driver Structure

In general, the driver has a list of all of the IPs on a particular SoC and for things like init/fini/suspend/resume, more or less just walks the list and handles each IP.

Some useful constructs:

- **KIQ (Kernel Interface Queue)**

  This is a control queue used by the kernel driver to manage other gfx and compute queues on the GFX/compute engine.  You can use it to map/unmap additional queues, etc.  This is replaced by MES on GFX 11 and newer hardware.

- **IB (Indirect Buffer)**

  A command buffer for a particular engine.  Rather than writing commands directly to the queue, you can write the commands into a piece of memory and then put a pointer to the memory into the queue. The hardware will then follow the pointer and execute the commands in the memory, then returning to the rest of the commands in the ring.

<a id="rst-memory-domains"></a>
<a id="rst-amdgpu-memory-domains"></a>

## Memory Domains


`AMDGPU_GEM_DOMAIN_CPU`       System memory that is not GPU accessible.
Memory in this pool could be swapped out to disk if there is pressure.

`AMDGPU_GEM_DOMAIN_GTT`       GPU accessible system memory, mapped into the
GPU's virtual address space via gart. Gart memory linearizes non-contiguous
pages of system memory, allows GPU access system memory in a linearized
fashion.

`AMDGPU_GEM_DOMAIN_VRAM`      Local video memory. For APUs, it is memory
carved out by the BIOS.

`AMDGPU_GEM_DOMAIN_GDS`       Global on-chip data storage used to share data
across shader threads.

`AMDGPU_GEM_DOMAIN_GWS`       Global wave sync, used to synchronize the
execution of all the waves on a device.

`AMDGPU_GEM_DOMAIN_OA`        Ordered append, used by 3D or Compute engines
for appending data.

`AMDGPU_GEM_DOMAIN_DOORBELL`  Doorbell. It is an MMIO region for
signalling user mode queues.


<a id="rst-buffer-objects"></a>

## Buffer Objects


This defines the interfaces to operate on an `amdgpu_bo` buffer object which
represents memory used by driver (VRAM, system memory, etc.). The driver
provides DRM/GEM APIs to userspace. DRM/GEM APIs then use these interfaces
to create/destroy/set buffer object which are then managed by the kernel TTM
memory manager.
The interfaces are also used internally by kernel clients, including gfx,
uvd, etc. for kernel managed allocations used by the GPU.



#### <a id="c-amdgpu_bo_is_amdgpu_bo"></a>`amdgpu_bo_is_amdgpu_bo()`

```c
bool amdgpu_bo_is_amdgpu_bo(struct ttm_buffer_object *bo)
```

check if the buffer object is an `amdgpu_bo`

**Parameters**

- `struct ttm_buffer_object *bo`: buffer object to be checked

**Description**

Uses destroy function associated with the object to determine if this is
an `amdgpu_bo`.

**Return**

true if the object belongs to `amdgpu_bo`, false if not.

#### <a id="c-amdgpu_bo_placement_from_domain"></a>`amdgpu_bo_placement_from_domain()`

```c
void amdgpu_bo_placement_from_domain(struct amdgpu_bo *abo, u32 domain)
```

set buffer's placement

**Parameters**

- `struct amdgpu_bo *abo`: `amdgpu_bo` buffer object whose placement is to be set
- `u32 domain`: requested domain

**Description**

Sets buffer's placement according to requested domain and the buffer's
flags.

#### <a id="c-amdgpu_bo_create_reserved"></a>`amdgpu_bo_create_reserved()`

```c
int amdgpu_bo_create_reserved(struct amdgpu_device *adev, unsigned long size, int align, u32 domain, struct amdgpu_bo **bo_ptr, u64 *gpu_addr, void **cpu_addr)
```

create reserved BO for kernel use

**Parameters**

- `struct amdgpu_device *adev`: amdgpu device object
- `unsigned long size`: size for the new BO
- `int align`: alignment for the new BO
- `u32 domain`: where to place it
- `struct amdgpu_bo **bo_ptr`: used to initialize BOs in structures
- `u64 *gpu_addr`: GPU addr of the pinned BO
- `void **cpu_addr`: optional CPU address mapping

**Description**

Allocates and pins a BO for kernel internal use, and returns it still
reserved.

**Note**

For bo_ptr new BO is only created if bo_ptr points to NULL.

**Return**

0 on success, negative error code otherwise.

#### <a id="c-amdgpu_bo_create_kernel"></a>`amdgpu_bo_create_kernel()`

```c
int amdgpu_bo_create_kernel(struct amdgpu_device *adev, unsigned long size, int align, u32 domain, struct amdgpu_bo **bo_ptr, u64 *gpu_addr, void **cpu_addr)
```

create BO for kernel use

**Parameters**

- `struct amdgpu_device *adev`: amdgpu device object
- `unsigned long size`: size for the new BO
- `int align`: alignment for the new BO
- `u32 domain`: where to place it
- `struct amdgpu_bo **bo_ptr`: used to initialize BOs in structures
- `u64 *gpu_addr`: GPU addr of the pinned BO
- `void **cpu_addr`: optional CPU address mapping

**Description**

Allocates and pins a BO for kernel internal use.

This function is exported to allow the V4L2 isp device
external to drm device to create and access the kernel BO.

**Note**

For bo_ptr new BO is only created if bo_ptr points to NULL.

**Return**

0 on success, negative error code otherwise.

#### <a id="c-amdgpu_bo_create_isp_user"></a>`amdgpu_bo_create_isp_user()`

```c
int amdgpu_bo_create_isp_user(struct amdgpu_device *adev, struct dma_buf *dma_buf, u32 domain, struct amdgpu_bo **bo, u64 *gpu_addr)
```

create user BO for isp

**Parameters**

- `struct amdgpu_device *adev`: amdgpu device object
- `struct dma_buf *dma_buf`: DMABUF handle for isp buffer
- `u32 domain`: where to place it
- `struct amdgpu_bo **bo`: used to initialize BOs in structures
- `u64 *gpu_addr`: GPU addr of the pinned BO

**Description**

Imports isp DMABUF to allocate and pin a user BO for isp internal use. It does
GART alloc to generate gpu_addr for BO to make it accessible through the
GART aperture for ISP HW.

This function is exported to allow the V4L2 isp device external to drm device
to create and access the isp user BO.

**Return**

0 on success, negative error code otherwise.

#### <a id="c-amdgpu_bo_create_kernel_at"></a>`amdgpu_bo_create_kernel_at()`

```c
int amdgpu_bo_create_kernel_at(struct amdgpu_device *adev, uint64_t offset, uint64_t size, struct amdgpu_bo **bo_ptr, void **cpu_addr)
```

create BO for kernel use at specific location

**Parameters**

- `struct amdgpu_device *adev`: amdgpu device object
- `uint64_t offset`: offset of the BO
- `uint64_t size`: size of the BO
- `struct amdgpu_bo **bo_ptr`: used to initialize BOs in structures
- `void **cpu_addr`: optional CPU address mapping

**Description**

Creates a kernel BO at a specific offset in VRAM.

**Return**

0 on success, negative error code otherwise.

#### <a id="c-amdgpu_bo_free_kernel"></a>`amdgpu_bo_free_kernel()`

```c
void amdgpu_bo_free_kernel(struct amdgpu_bo **bo, u64 *gpu_addr, void **cpu_addr)
```

free BO for kernel use

**Parameters**

- `struct amdgpu_bo **bo`: amdgpu BO to free
- `u64 *gpu_addr`: pointer to where the BO's GPU memory space address was stored
- `void **cpu_addr`: pointer to where the BO's CPU memory space address was stored

**Description**

unmaps and unpin a BO for kernel internal use.

This function is exported to allow the V4L2 isp device
external to drm device to free the kernel BO.

#### <a id="c-amdgpu_bo_free_isp_user"></a>`amdgpu_bo_free_isp_user()`

```c
void amdgpu_bo_free_isp_user(struct amdgpu_bo *bo)
```

free BO for isp use

**Parameters**

- `struct amdgpu_bo *bo`: amdgpu isp user BO to free

**Description**

unpin and unref BO for isp internal use.

This function is exported to allow the V4L2 isp device
external to drm device to free the isp user BO.

#### <a id="c-amdgpu_bo_create"></a>`amdgpu_bo_create()`

```c
int amdgpu_bo_create(struct amdgpu_device *adev, struct amdgpu_bo_param *bp, struct amdgpu_bo **bo_ptr)
```

create an `amdgpu_bo` buffer object

**Parameters**

- `struct amdgpu_device *adev`: amdgpu device object
- `struct amdgpu_bo_param *bp`: parameters to be used for the buffer object
- `struct amdgpu_bo **bo_ptr`: pointer to the buffer object pointer

**Description**

Creates an `amdgpu_bo` buffer object.

**Return**

0 for success or a negative error code on failure.

#### <a id="c-amdgpu_bo_create_user"></a>`amdgpu_bo_create_user()`

```c
int amdgpu_bo_create_user(struct amdgpu_device *adev, struct amdgpu_bo_param *bp, struct amdgpu_bo_user **ubo_ptr)
```

create an `amdgpu_bo_user` buffer object

**Parameters**

- `struct amdgpu_device *adev`: amdgpu device object
- `struct amdgpu_bo_param *bp`: parameters to be used for the buffer object
- `struct amdgpu_bo_user **ubo_ptr`: pointer to the buffer object pointer

**Description**

Create a BO to be used by user application;

**Return**

0 for success or a negative error code on failure.

#### <a id="c-amdgpu_bo_create_vm"></a>`amdgpu_bo_create_vm()`

```c
int amdgpu_bo_create_vm(struct amdgpu_device *adev, struct amdgpu_bo_param *bp, struct amdgpu_bo_vm **vmbo_ptr)
```

create an `amdgpu_bo_vm` buffer object

**Parameters**

- `struct amdgpu_device *adev`: amdgpu device object
- `struct amdgpu_bo_param *bp`: parameters to be used for the buffer object
- `struct amdgpu_bo_vm **vmbo_ptr`: pointer to the buffer object pointer

**Description**

Create a BO to be for GPUVM.

**Return**

0 for success or a negative error code on failure.

#### <a id="c-amdgpu_bo_kmap"></a>`amdgpu_bo_kmap()`

```c
int amdgpu_bo_kmap(struct amdgpu_bo *bo, void **ptr)
```

map an `amdgpu_bo` buffer object

**Parameters**

- `struct amdgpu_bo *bo`: `amdgpu_bo` buffer object to be mapped
- `void **ptr`: kernel virtual address to be returned

**Description**

Calls `ttm_bo_kmap()` to set up the kernel virtual mapping; calls
[`amdgpu_bo_kptr()`](#c-amdgpu_bo_kptr) to get the kernel virtual address.

**Return**

0 for success or a negative error code on failure.

#### <a id="c-amdgpu_bo_kptr"></a>`amdgpu_bo_kptr()`

```c
void * amdgpu_bo_kptr(struct amdgpu_bo *bo)
```

returns a kernel virtual address of the buffer object

**Parameters**

- `struct amdgpu_bo *bo`: `amdgpu_bo` buffer object

**Description**

Calls `ttm_kmap_obj_virtual()` to get the kernel virtual address

**Return**

the virtual address of a buffer object area.

#### <a id="c-amdgpu_bo_kunmap"></a>`amdgpu_bo_kunmap()`

```c
void amdgpu_bo_kunmap(struct amdgpu_bo *bo)
```

unmap an `amdgpu_bo` buffer object

**Parameters**

- `struct amdgpu_bo *bo`: `amdgpu_bo` buffer object to be unmapped

**Description**

Unmaps a kernel map set up by [`amdgpu_bo_kmap()`](#c-amdgpu_bo_kmap).

#### <a id="c-amdgpu_bo_ref"></a>`amdgpu_bo_ref()`

```c
struct amdgpu_bo * amdgpu_bo_ref(struct amdgpu_bo *bo)
```

reference an `amdgpu_bo` buffer object

**Parameters**

- `struct amdgpu_bo *bo`: `amdgpu_bo` buffer object

**Description**

References the contained `ttm_buffer_object`.

**Return**

a refcounted pointer to the `amdgpu_bo` buffer object.

#### <a id="c-amdgpu_bo_unref"></a>`amdgpu_bo_unref()`

```c
void amdgpu_bo_unref(struct amdgpu_bo **bo)
```

unreference an `amdgpu_bo` buffer object

**Parameters**

- `struct amdgpu_bo **bo`: `amdgpu_bo` buffer object

**Description**

Unreferences the contained `ttm_buffer_object` and clear the pointer

#### <a id="c-amdgpu_bo_pin"></a>`amdgpu_bo_pin()`

```c
int amdgpu_bo_pin(struct amdgpu_bo *bo, u32 domain)
```

pin an `amdgpu_bo` buffer object

**Parameters**

- `struct amdgpu_bo *bo`: `amdgpu_bo` buffer object to be pinned
- `u32 domain`: domain to be pinned to

**Description**

Pins the buffer object according to requested domain. If the memory is
unbound gart memory, binds the pages into gart table. Adjusts pin_count and
pin_size accordingly.

Pinning means to lock pages in memory along with keeping them at a fixed
offset. It is required when a buffer can not be moved, for example, when
a display buffer is being scanned out.

**Return**

0 for success or a negative error code on failure.

#### <a id="c-amdgpu_bo_unpin"></a>`amdgpu_bo_unpin()`

```c
void amdgpu_bo_unpin(struct amdgpu_bo *bo)
```

unpin an `amdgpu_bo` buffer object

**Parameters**

- `struct amdgpu_bo *bo`: `amdgpu_bo` buffer object to be unpinned

**Description**

Decreases the pin_count, and clears the flags if pin_count reaches 0.
Changes placement and pin size accordingly.

**Return**

0 for success or a negative error code on failure.

#### <a id="c-amdgpu_bo_init"></a>`amdgpu_bo_init()`

```c
int amdgpu_bo_init(struct amdgpu_device *adev)
```

initialize memory manager

**Parameters**

- `struct amdgpu_device *adev`: amdgpu device object

**Description**

Calls `amdgpu_ttm_init()` to initialize amdgpu memory manager.

**Return**

0 for success or a negative error code on failure.

#### <a id="c-amdgpu_bo_fini"></a>`amdgpu_bo_fini()`

```c
void amdgpu_bo_fini(struct amdgpu_device *adev)
```

tear down memory manager

**Parameters**

- `struct amdgpu_device *adev`: amdgpu device object

**Description**

Reverses [`amdgpu_bo_init()`](#c-amdgpu_bo_init) to tear down memory manager.

#### <a id="c-amdgpu_bo_set_tiling_flags"></a>`amdgpu_bo_set_tiling_flags()`

```c
int amdgpu_bo_set_tiling_flags(struct amdgpu_bo *bo, u64 tiling_flags)
```

set tiling flags

**Parameters**

- `struct amdgpu_bo *bo`: `amdgpu_bo` buffer object
- `u64 tiling_flags`: new flags

**Description**

Sets buffer object's tiling flags with the new one. Used by GEM ioctl or
kernel driver to set the tiling flags on a buffer.

**Return**

0 for success or a negative error code on failure.

#### <a id="c-amdgpu_bo_get_tiling_flags"></a>`amdgpu_bo_get_tiling_flags()`

```c
void amdgpu_bo_get_tiling_flags(struct amdgpu_bo *bo, u64 *tiling_flags)
```

get tiling flags

**Parameters**

- `struct amdgpu_bo *bo`: `amdgpu_bo` buffer object
- `u64 *tiling_flags`: returned flags

**Description**

Gets buffer object's tiling flags. Used by GEM ioctl or kernel driver to
set the tiling flags on a buffer.

#### <a id="c-amdgpu_bo_set_metadata"></a>`amdgpu_bo_set_metadata()`

```c
int amdgpu_bo_set_metadata(struct amdgpu_bo *bo, void *metadata, u32 metadata_size, uint64_t flags)
```

set metadata

**Parameters**

- `struct amdgpu_bo *bo`: `amdgpu_bo` buffer object
- `void *metadata`: new metadata
- `u32 metadata_size`: size of the new metadata
- `uint64_t flags`: flags of the new metadata

**Description**

Sets buffer object's metadata, its size and flags.
Used via GEM ioctl.

**Return**

0 for success or a negative error code on failure.

#### <a id="c-amdgpu_bo_get_metadata"></a>`amdgpu_bo_get_metadata()`

```c
int amdgpu_bo_get_metadata(struct amdgpu_bo *bo, void *buffer, size_t buffer_size, uint32_t *metadata_size, uint64_t *flags)
```

get metadata

**Parameters**

- `struct amdgpu_bo *bo`: `amdgpu_bo` buffer object
- `void *buffer`: returned metadata
- `size_t buffer_size`: size of the buffer
- `uint32_t *metadata_size`: size of the returned metadata
- `uint64_t *flags`: flags of the returned metadata

**Description**

Gets buffer object's metadata, its size and flags. buffer_size shall not be
less than metadata_size.
Used via GEM ioctl.

**Return**

0 for success or a negative error code on failure.

#### <a id="c-amdgpu_bo_move_notify"></a>`amdgpu_bo_move_notify()`

```c
void amdgpu_bo_move_notify(struct ttm_buffer_object *bo, bool evict, struct ttm_resource *new_mem)
```

notification about a memory move

**Parameters**

- `struct ttm_buffer_object *bo`: pointer to a buffer object
- `bool evict`: if this move is evicting the buffer from the graphics address space
- `struct ttm_resource *new_mem`: new resource for backing the BO

**Description**

Marks the corresponding `amdgpu_bo` buffer object as invalid, also performs
bookkeeping.
TTM driver callback which is called when ttm moves a buffer.

#### <a id="c-amdgpu_bo_release_notify"></a>`amdgpu_bo_release_notify()`

```c
void amdgpu_bo_release_notify(struct ttm_buffer_object *bo)
```

notification about a BO being released

**Parameters**

- `struct ttm_buffer_object *bo`: pointer to a buffer object

**Description**

Wipes VRAM buffers whose contents should not be leaked before the
memory is released.

#### <a id="c-amdgpu_bo_fault_reserve_notify"></a>`amdgpu_bo_fault_reserve_notify()`

```c
vm_fault_t amdgpu_bo_fault_reserve_notify(struct ttm_buffer_object *bo)
```

notification about a memory fault

**Parameters**

- `struct ttm_buffer_object *bo`: pointer to a buffer object

**Description**

Notifies the driver we are taking a fault on this BO and have reserved it,
also performs bookkeeping.
TTM driver callback for dealing with vm faults.

**Return**

0 for success or a negative error code on failure.

#### <a id="c-amdgpu_bo_fence"></a>`amdgpu_bo_fence()`

```c
void amdgpu_bo_fence(struct amdgpu_bo *bo, struct dma_fence *fence, bool shared)
```

add fence to buffer object

**Parameters**

- `struct amdgpu_bo *bo`: buffer object in question
- `struct dma_fence *fence`: fence to add
- `bool shared`: true if fence should be added shared

#### <a id="c-amdgpu_bo_sync_wait_resv"></a>`amdgpu_bo_sync_wait_resv()`

```c
int amdgpu_bo_sync_wait_resv(struct amdgpu_device *adev, struct dma_resv *resv, enum amdgpu_sync_mode sync_mode, void *owner, bool intr)
```

Wait for BO reservation fences

**Parameters**

- `struct amdgpu_device *adev`: amdgpu device pointer
- `struct dma_resv *resv`: reservation object to sync to
- `enum amdgpu_sync_mode sync_mode`: synchronization mode
- `void *owner`: fence owner
- `bool intr`: Whether the wait is interruptible

**Description**

Extract the fences from the reservation object and waits for them to finish.

**Return**

0 on success, errno otherwise.

#### <a id="c-amdgpu_bo_sync_wait"></a>`amdgpu_bo_sync_wait()`

```c
int amdgpu_bo_sync_wait(struct amdgpu_bo *bo, void *owner, bool intr)
```

Wrapper for amdgpu_bo_sync_wait_resv

**Parameters**

- `struct amdgpu_bo *bo`: buffer object to wait for
- `void *owner`: fence owner
- `bool intr`: Whether the wait is interruptible

**Description**

Wrapper to wait for fences in a BO.

**Return**

0 on success, errno otherwise.

#### <a id="c-amdgpu_bo_gpu_offset"></a>`amdgpu_bo_gpu_offset()`

```c
u64 amdgpu_bo_gpu_offset(struct amdgpu_bo *bo)
```

return GPU offset of bo

**Parameters**

- `struct amdgpu_bo *bo`: amdgpu object for which we query the offset

**Note**

object should either be pinned or reserved when calling this
function, it might be useful to add check for this for debugging.

**Return**

current GPU offset of the object.

#### <a id="c-amdgpu_bo_fb_aper_addr"></a>`amdgpu_bo_fb_aper_addr()`

```c
u64 amdgpu_bo_fb_aper_addr(struct amdgpu_bo *bo)
```

return FB aperture GPU offset of the VRAM bo

**Parameters**

- `struct amdgpu_bo *bo`: amdgpu VRAM buffer object for which we query the offset

**Return**

current FB aperture GPU offset of the object.

#### <a id="c-amdgpu_bo_gpu_offset_no_check"></a>`amdgpu_bo_gpu_offset_no_check()`

```c
u64 amdgpu_bo_gpu_offset_no_check(struct amdgpu_bo *bo)
```

return GPU offset of bo

**Parameters**

- `struct amdgpu_bo *bo`: amdgpu object for which we query the offset

**Return**

current GPU offset of the object without raising warnings.

#### <a id="c-amdgpu_bo_mem_stats_placement"></a>`amdgpu_bo_mem_stats_placement()`

```c
uint32_t amdgpu_bo_mem_stats_placement(struct amdgpu_bo *bo)
```

bo placement for memory accounting

**Parameters**

- `struct amdgpu_bo *bo`: the buffer object we should look at

**Description**

BO can have multiple preferred placements, to avoid double counting we want
to file it under a single placement for memory stats.
Luckily, if we take the highest set bit in preferred_domains the result is
quite sensible.

**Return**

Which of the placements should the BO be accounted under.

#### <a id="c-amdgpu_bo_get_preferred_domain"></a>`amdgpu_bo_get_preferred_domain()`

```c
uint32_t amdgpu_bo_get_preferred_domain(struct amdgpu_device *adev, uint32_t domain)
```

get preferred domain

**Parameters**

- `struct amdgpu_device *adev`: amdgpu device object
- `uint32_t domain`: allowed memory domains

**Return**

Which of the allowed domains is preferred for allocating the BO.

#### <a id="c-amdgpu_bo_print_info"></a>`amdgpu_bo_print_info()`

```c
u64 amdgpu_bo_print_info(int id, struct amdgpu_bo *bo, struct seq_file *m)
```

print BO info in debugfs file

**Parameters**

- `int id`: Index or Id of the BO
- `struct amdgpu_bo *bo`: Requested BO for printing info
- `struct seq_file *m`: debugfs file

**Description**

Print BO information in debugfs file

**Return**

Size of the BO in bytes.


<a id="rst-prime-buffer-sharing"></a>

## PRIME Buffer Sharing


The following callback implementations are used for sharing GEM buffer
objects between different devices via PRIME.



#### <a id="c-dma_buf_attach_adev"></a>`dma_buf_attach_adev()`

```c
struct amdgpu_device * dma_buf_attach_adev(struct dma_buf_attachment *attach)
```

Helper to get adev of an attachment

**Parameters**

- `struct dma_buf_attachment *attach`: attachment

**Return**

A struct amdgpu_device * if the attaching device is an amdgpu device or
partition, NULL otherwise.

#### <a id="c-amdgpu_dma_buf_attach"></a>`amdgpu_dma_buf_attach()`

```c
int amdgpu_dma_buf_attach(struct dma_buf *dmabuf, struct dma_buf_attachment *attach)
```

[`dma_buf_ops.attach`](/kernel/hardware/driver-api/io-and-dma/dma-buf.md#c-struct-dma_buf_ops) implementation

**Parameters**

- `struct dma_buf *dmabuf`: DMA-buf where we attach to
- `struct dma_buf_attachment *attach`: attachment to add

**Description**

Add the attachment as user to the exported DMA-buf.

#### <a id="c-amdgpu_dma_buf_pin"></a>`amdgpu_dma_buf_pin()`

```c
int amdgpu_dma_buf_pin(struct dma_buf_attachment *attach)
```

[`dma_buf_ops.pin`](/kernel/hardware/driver-api/io-and-dma/dma-buf.md#c-struct-dma_buf_ops) implementation

**Parameters**

- `struct dma_buf_attachment *attach`: attachment to pin down

**Description**

Pin the BO which is backing the DMA-buf so that it can't move any more.

#### <a id="c-amdgpu_dma_buf_unpin"></a>`amdgpu_dma_buf_unpin()`

```c
void amdgpu_dma_buf_unpin(struct dma_buf_attachment *attach)
```

[`dma_buf_ops.unpin`](/kernel/hardware/driver-api/io-and-dma/dma-buf.md#c-struct-dma_buf_ops) implementation

**Parameters**

- `struct dma_buf_attachment *attach`: attachment to unpin

**Description**

Unpin a previously pinned BO to make it movable again.

#### <a id="c-amdgpu_dma_buf_map"></a>`amdgpu_dma_buf_map()`

```c
struct sg_table * amdgpu_dma_buf_map(struct dma_buf_attachment *attach, enum dma_data_direction dir)
```

[`dma_buf_ops.map_dma_buf`](/kernel/hardware/driver-api/io-and-dma/dma-buf.md#c-struct-dma_buf_ops) implementation

**Parameters**

- `struct dma_buf_attachment *attach`: DMA-buf attachment
- `enum dma_data_direction dir`: DMA direction

**Description**

Makes sure that the shared DMA buffer can be accessed by the target device.
For now, simply pins it to the GTT domain, where it should be accessible by
all DMA devices.

**Return**

sg_table filled with the DMA addresses to use or ERR_PRT with negative error
code.

#### <a id="c-amdgpu_dma_buf_unmap"></a>`amdgpu_dma_buf_unmap()`

```c
void amdgpu_dma_buf_unmap(struct dma_buf_attachment *attach, struct sg_table *sgt, enum dma_data_direction dir)
```

[`dma_buf_ops.unmap_dma_buf`](/kernel/hardware/driver-api/io-and-dma/dma-buf.md#c-struct-dma_buf_ops) implementation

**Parameters**

- `struct dma_buf_attachment *attach`: DMA-buf attachment
- `struct sg_table *sgt`: sg_table to unmap
- `enum dma_data_direction dir`: DMA direction

**Description**

This is called when a shared DMA buffer no longer needs to be accessible by
another device. For now, simply unpins the buffer from GTT.

#### <a id="c-amdgpu_dma_buf_begin_cpu_access"></a>`amdgpu_dma_buf_begin_cpu_access()`

```c
int amdgpu_dma_buf_begin_cpu_access(struct dma_buf *dma_buf, enum dma_data_direction direction)
```

[`dma_buf_ops.begin_cpu_access`](/kernel/hardware/driver-api/io-and-dma/dma-buf.md#c-struct-dma_buf_ops) implementation

**Parameters**

- `struct dma_buf *dma_buf`: Shared DMA buffer
- `enum dma_data_direction direction`: Direction of DMA transfer

**Description**

This is called before CPU access to the shared DMA buffer's memory. If it's
a read access, the buffer is moved to the GTT domain if possible, for optimal
CPU read performance.

**Return**

0 on success or a negative error code on failure.

#### <a id="c-amdgpu_gem_prime_export"></a>`amdgpu_gem_prime_export()`

```c
struct dma_buf * amdgpu_gem_prime_export(struct drm_gem_object *gobj, int flags)
```

[`drm_driver.gem_prime_export`](/kernel/hardware/gpu/drm-internals.md#c-struct-drm_driver) implementation

**Parameters**

- `struct drm_gem_object *gobj`: GEM BO
- `int flags`: Flags such as DRM_CLOEXEC and DRM_RDWR.

**Description**

The main work is done by the [`drm_gem_prime_export`](/kernel/hardware/gpu/drm-mm.md#c-drm_gem_prime_export) helper.

**Return**

Shared DMA buffer representing the GEM BO from the given device.

#### <a id="c-amdgpu_dma_buf_create_obj"></a>`amdgpu_dma_buf_create_obj()`

```c
struct drm_gem_object * amdgpu_dma_buf_create_obj(struct drm_device *dev, struct dma_buf *dma_buf)
```

create BO for DMA-buf import

**Parameters**

- `struct drm_device *dev`: DRM device
- `struct dma_buf *dma_buf`: DMA-buf

**Description**

Creates an empty SG BO for DMA-buf import.

**Return**

A new GEM BO of the given DRM device, representing the memory
described by the given DMA-buf attachment and scatter/gather table.

#### <a id="c-amdgpu_dma_buf_move_notify"></a>`amdgpu_dma_buf_move_notify()`

```c
void amdgpu_dma_buf_move_notify(struct dma_buf_attachment *attach)
```

`attach.move_notify` implementation

**Parameters**

- `struct dma_buf_attachment *attach`: the DMA-buf attachment

**Description**

Invalidate the DMA-buf attachment, making sure that the we re-create the
mapping before the next use.

#### <a id="c-amdgpu_gem_prime_import"></a>`amdgpu_gem_prime_import()`

```c
struct drm_gem_object * amdgpu_gem_prime_import(struct drm_device *dev, struct dma_buf *dma_buf)
```

[`drm_driver.gem_prime_import`](/kernel/hardware/gpu/drm-internals.md#c-struct-drm_driver) implementation

**Parameters**

- `struct drm_device *dev`: DRM device
- `struct dma_buf *dma_buf`: Shared DMA buffer

**Description**

Import a dma_buf into a the driver and potentially create a new GEM object.

**Return**

GEM BO representing the shared DMA buffer for the given device.

#### <a id="c-amdgpu_dmabuf_is_xgmi_accessible"></a>`amdgpu_dmabuf_is_xgmi_accessible()`

```c
bool amdgpu_dmabuf_is_xgmi_accessible(struct amdgpu_device *adev, struct amdgpu_bo *bo)
```

Check if xgmi available for P2P transfer

**Parameters**

- `struct amdgpu_device *adev`: amdgpu_device pointer of the importer
- `struct amdgpu_bo *bo`: amdgpu buffer object

**Return**

True if dmabuf accessible over xgmi, false otherwise.


<a id="rst-mmu-notifier"></a>

## MMU Notifier


For coherent userptr handling registers an MMU notifier to inform the driver
about updates on the page tables of a process.

When somebody tries to invalidate the page tables we block the update until
all operations on the pages in question are completed, then those pages are
marked as accessed and also dirty if it wasn't a read only access.

New command submissions using the userptrs in question are delayed until all
page table invalidation are completed and we once more see a coherent process
address space.



#### <a id="c-amdgpu_hmm_invalidate_gfx"></a>`amdgpu_hmm_invalidate_gfx()`

```c
bool amdgpu_hmm_invalidate_gfx(struct mmu_interval_notifier *mni, const struct mmu_notifier_range *range, unsigned long cur_seq)
```

callback to notify about mm change

**Parameters**

- `struct mmu_interval_notifier *mni`: the range (mm) is about to update
- `const struct mmu_notifier_range *range`: details on the invalidation
- `unsigned long cur_seq`: Value to pass to `mmu_interval_set_seq()`

**Description**

Block for operations on BOs to finish and mark pages as accessed and
potentially dirty.

#### <a id="c-amdgpu_hmm_invalidate_hsa"></a>`amdgpu_hmm_invalidate_hsa()`

```c
bool amdgpu_hmm_invalidate_hsa(struct mmu_interval_notifier *mni, const struct mmu_notifier_range *range, unsigned long cur_seq)
```

callback to notify about mm change

**Parameters**

- `struct mmu_interval_notifier *mni`: the range (mm) is about to update
- `const struct mmu_notifier_range *range`: details on the invalidation
- `unsigned long cur_seq`: Value to pass to `mmu_interval_set_seq()`

**Description**

We temporarily evict the BO attached to this range. This necessitates
evicting all user-mode queues of the process.

#### <a id="c-amdgpu_hmm_register"></a>`amdgpu_hmm_register()`

```c
int amdgpu_hmm_register(struct amdgpu_bo *bo, unsigned long addr)
```

register a BO for notifier updates

**Parameters**

- `struct amdgpu_bo *bo`: amdgpu buffer object
- `unsigned long addr`: userptr addr we should monitor

**Description**

Registers a mmu_notifier for the given BO at the specified address.
Returns 0 on success, -ERRNO if anything goes wrong.

#### <a id="c-amdgpu_hmm_unregister"></a>`amdgpu_hmm_unregister()`

```c
void amdgpu_hmm_unregister(struct amdgpu_bo *bo)
```

unregister a BO for notifier updates

**Parameters**

- `struct amdgpu_bo *bo`: amdgpu buffer object

**Description**

Remove any registration of mmu notifier updates from the buffer object.

#### <a id="c-amdgpu_hmm_range_valid"></a>`amdgpu_hmm_range_valid()`

```c
bool amdgpu_hmm_range_valid(struct amdgpu_hmm_range *range)
```

check if an HMM range is still valid

**Parameters**

- `struct amdgpu_hmm_range *range`: pointer to the `struct amdgpu_hmm_range` to validate

**Description**

Determines whether the given HMM range **range** is still valid by
checking for invalidations via the MMU notifier sequence. This is
typically used to verify that the range has not been invalidated
by concurrent address space updates before it is accessed.

**Return**

* true if **range** is valid and can be used safely
* false if **range** is NULL or has been invalidated

#### <a id="c-amdgpu_hmm_range_alloc"></a>`amdgpu_hmm_range_alloc()`

```c
struct amdgpu_hmm_range * amdgpu_hmm_range_alloc(struct amdgpu_bo *bo)
```

allocate and initialize an AMDGPU HMM range

**Parameters**

- `struct amdgpu_bo *bo`: optional buffer object to associate with this HMM range

**Description**

Allocates memory for amdgpu_hmm_range and associates it with the **bo** passed.
The reference count of the **bo** is incremented.

**Return**

Pointer to a newly allocated struct amdgpu_hmm_range on success,
or NULL if memory allocation fails.

#### <a id="c-amdgpu_hmm_range_free"></a>`amdgpu_hmm_range_free()`

```c
void amdgpu_hmm_range_free(struct amdgpu_hmm_range *range)
```

release an AMDGPU HMM range

**Parameters**

- `struct amdgpu_hmm_range *range`: pointer to the range object to free

**Description**

Releases all resources held by **range**, including the associated
hmm_pfns and the dropping reference of associated bo if any.

**Return**

void


<a id="rst-amdgpu-virtual-memory"></a>

## AMDGPU Virtual Memory


GPUVM is the MMU functionality provided on the GPU.
GPUVM is similar to the legacy GART on older asics, however
rather than there being a single global GART table
for the entire GPU, there can be multiple GPUVM page tables active
at any given time.  The GPUVM page tables can contain a mix
VRAM pages and system pages (both memory and MMIO) and system pages
can be mapped as snooped (cached system pages) or unsnooped
(uncached system pages).

Each active GPUVM has an ID associated with it and there is a page table
linked with each VMID.  When executing a command buffer,
the kernel tells the engine what VMID to use for that command
buffer.  VMIDs are allocated dynamically as commands are submitted.
The userspace drivers maintain their own address space and the kernel
sets up their pages tables accordingly when they submit their
command buffers and a VMID is assigned.
The hardware supports up to 16 active GPUVMs at any given time.

Each GPUVM is represented by a 1-2 or 1-5 level page table, depending
on the ASIC family.  GPUVM supports RWX attributes on each page as well
as other features such as encryption and caching attributes.

VMID 0 is special.  It is the GPUVM used for the kernel driver.  In
addition to an aperture managed by a page table, VMID 0 also has
several other apertures.  There is an aperture for direct access to VRAM
and there is a legacy AGP aperture which just forwards accesses directly
to the matching system physical addresses (or IOVAs when an IOMMU is
present).  These apertures provide direct access to these memories without
incurring the overhead of a page table.  VMID 0 is used by the kernel
driver for tasks like memory management.

GPU clients (i.e., engines on the GPU) use GPUVM VMIDs to access memory.
For user applications, each application can have their own unique GPUVM
address space.  The application manages the address space and the kernel
driver manages the GPUVM page tables for each process.  If an GPU client
accesses an invalid page, it will generate a GPU page fault, similar to
accessing an invalid page on a CPU.



#### <a id="c-struct-amdgpu_prt_cb"></a>`struct amdgpu_prt_cb`

Helper to disable partial resident texture feature from a fence callback

**Definition**

```c
struct amdgpu_prt_cb {
    struct amdgpu_device *adev;
    struct dma_fence_cb cb;
};
```

**Members**

- `adev`: amdgpu device
- `cb`: callback

#### <a id="c-struct-amdgpu_vm_tlb_seq_struct"></a>`struct amdgpu_vm_tlb_seq_struct`

Helper to increment the TLB flush sequence

**Definition**

```c
struct amdgpu_vm_tlb_seq_struct {
    struct amdgpu_vm *vm;
    struct dma_fence_cb cb;
};
```

**Members**

- `vm`: pointer to the amdgpu_vm structure to set the fence sequence on
- `cb`: callback

#### <a id="c-amdgpu_vm_assert_locked"></a>`amdgpu_vm_assert_locked()`

```c
void amdgpu_vm_assert_locked(struct amdgpu_vm *vm)
```

check if VM is correctly locked

**Parameters**

- `struct amdgpu_vm *vm`: the VM which schould be tested

**Description**

Asserts that the VM root PD is locked.

#### <a id="c-amdgpu_vm_bo_evicted"></a>`amdgpu_vm_bo_evicted()`

```c
void amdgpu_vm_bo_evicted(struct amdgpu_vm_bo_base *vm_bo)
```

vm_bo is evicted

**Parameters**

- `struct amdgpu_vm_bo_base *vm_bo`: vm_bo which is evicted

**Description**

State for PDs/PTs and per VM BOs which are not at the location they should
be.

#### <a id="c-amdgpu_vm_bo_moved"></a>`amdgpu_vm_bo_moved()`

```c
void amdgpu_vm_bo_moved(struct amdgpu_vm_bo_base *vm_bo)
```

vm_bo is moved

**Parameters**

- `struct amdgpu_vm_bo_base *vm_bo`: vm_bo which is moved

**Description**

State for per VM BOs which are moved, but that change is not yet reflected
in the page tables.

#### <a id="c-amdgpu_vm_bo_idle"></a>`amdgpu_vm_bo_idle()`

```c
void amdgpu_vm_bo_idle(struct amdgpu_vm_bo_base *vm_bo)
```

vm_bo is idle

**Parameters**

- `struct amdgpu_vm_bo_base *vm_bo`: vm_bo which is now idle

**Description**

State for PDs/PTs and per VM BOs which have gone through the state machine
and are now idle.

#### <a id="c-amdgpu_vm_bo_invalidated"></a>`amdgpu_vm_bo_invalidated()`

```c
void amdgpu_vm_bo_invalidated(struct amdgpu_vm_bo_base *vm_bo)
```

vm_bo is invalidated

**Parameters**

- `struct amdgpu_vm_bo_base *vm_bo`: vm_bo which is now invalidated

**Description**

State for normal BOs which are invalidated and that change not yet reflected
in the PTs.

#### <a id="c-amdgpu_vm_bo_evicted_user"></a>`amdgpu_vm_bo_evicted_user()`

```c
void amdgpu_vm_bo_evicted_user(struct amdgpu_vm_bo_base *vm_bo)
```

vm_bo is evicted

**Parameters**

- `struct amdgpu_vm_bo_base *vm_bo`: vm_bo which is evicted

**Description**

State for BOs used by user mode queues which are not at the location they
should be.

#### <a id="c-amdgpu_vm_bo_relocated"></a>`amdgpu_vm_bo_relocated()`

```c
void amdgpu_vm_bo_relocated(struct amdgpu_vm_bo_base *vm_bo)
```

vm_bo is reloacted

**Parameters**

- `struct amdgpu_vm_bo_base *vm_bo`: vm_bo which is relocated

**Description**

State for PDs/PTs which needs to update their parent PD.
For the root PD, just move to idle state.

#### <a id="c-amdgpu_vm_bo_done"></a>`amdgpu_vm_bo_done()`

```c
void amdgpu_vm_bo_done(struct amdgpu_vm_bo_base *vm_bo)
```

vm_bo is done

**Parameters**

- `struct amdgpu_vm_bo_base *vm_bo`: vm_bo which is now done

**Description**

State for normal BOs which are invalidated and that change has been updated
in the PTs.

#### <a id="c-amdgpu_vm_bo_reset_state_machine"></a>`amdgpu_vm_bo_reset_state_machine()`

```c
void amdgpu_vm_bo_reset_state_machine(struct amdgpu_vm *vm)
```

reset the vm_bo state machine

**Parameters**

- `struct amdgpu_vm *vm`: the VM which state machine to reset

**Description**

Move all vm_bo object in the VM into a state where they will be updated
again during validation.

#### <a id="c-amdgpu_vm_update_shared"></a>`amdgpu_vm_update_shared()`

```c
void amdgpu_vm_update_shared(struct amdgpu_vm_bo_base *base)
```

helper to update shared memory stat

**Parameters**

- `struct amdgpu_vm_bo_base *base`: base structure for tracking BO usage in a VM

**Description**

Takes the vm status_lock and updates the shared memory stat. If the basic
stat changed (e.g. buffer was moved) amdgpu_vm_update_stats need to be called
as well.

#### <a id="c-amdgpu_vm_bo_update_shared"></a>`amdgpu_vm_bo_update_shared()`

```c
void amdgpu_vm_bo_update_shared(struct amdgpu_bo *bo)
```

callback when bo gets shared/unshared

**Parameters**

- `struct amdgpu_bo *bo`: amdgpu buffer object

**Description**

Update the per VM stats for all the vm if needed from private to shared or
vice versa.

#### <a id="c-amdgpu_vm_update_stats_locked"></a>`amdgpu_vm_update_stats_locked()`

```c
void amdgpu_vm_update_stats_locked(struct amdgpu_vm_bo_base *base, struct ttm_resource *res, int sign)
```

helper to update normal memory stat

**Parameters**

- `struct amdgpu_vm_bo_base *base`: base structure for tracking BO usage in a VM
- `struct ttm_resource *res`: the ttm_resource to use for the purpose of accounting, may or may not
  be bo->tbo.resource
- `int sign`: if we should add (+1) or subtract (-1) from the stat

**Description**

Caller need to have the vm status_lock held. Useful for when multiple update
need to happen at the same time.

#### <a id="c-amdgpu_vm_update_stats"></a>`amdgpu_vm_update_stats()`

```c
void amdgpu_vm_update_stats(struct amdgpu_vm_bo_base *base, struct ttm_resource *res, int sign)
```

helper to update normal memory stat

**Parameters**

- `struct amdgpu_vm_bo_base *base`: base structure for tracking BO usage in a VM
- `struct ttm_resource *res`: the ttm_resource to use for the purpose of accounting, may or may not
  be bo->tbo.resource
- `int sign`: if we should add (+1) or subtract (-1) from the stat

**Description**

Updates the basic memory stat when bo is added/deleted/moved.

#### <a id="c-amdgpu_vm_bo_base_init"></a>`amdgpu_vm_bo_base_init()`

```c
void amdgpu_vm_bo_base_init(struct amdgpu_vm_bo_base *base, struct amdgpu_vm *vm, struct amdgpu_bo *bo)
```

Adds bo to the list of bos associated with the vm

**Parameters**

- `struct amdgpu_vm_bo_base *base`: base structure for tracking BO usage in a VM
- `struct amdgpu_vm *vm`: vm to which bo is to be added
- `struct amdgpu_bo *bo`: amdgpu buffer object

**Description**

Initialize a bo_va_base structure and add it to the appropriate lists

#### <a id="c-amdgpu_vm_lock_pd"></a>`amdgpu_vm_lock_pd()`

```c
int amdgpu_vm_lock_pd(struct amdgpu_vm *vm, struct drm_exec *exec, unsigned int num_fences)
```

lock PD in drm_exec

**Parameters**

- `struct amdgpu_vm *vm`: vm providing the BOs
- `struct drm_exec *exec`: drm execution context
- `unsigned int num_fences`: number of extra fences to reserve

**Description**

Lock the VM root PD in the DRM execution context.

#### <a id="c-amdgpu_vm_lock_done_list"></a>`amdgpu_vm_lock_done_list()`

```c
int amdgpu_vm_lock_done_list(struct amdgpu_vm *vm, struct drm_exec *exec, unsigned int num_fences)
```

lock all BOs on the done list

**Parameters**

- `struct amdgpu_vm *vm`: vm providing the BOs
- `struct drm_exec *exec`: drm execution context
- `unsigned int num_fences`: number of extra fences to reserve

**Description**

Lock the BOs on the done list in the DRM execution context.

#### <a id="c-amdgpu_vm_move_to_lru_tail"></a>`amdgpu_vm_move_to_lru_tail()`

```c
void amdgpu_vm_move_to_lru_tail(struct amdgpu_device *adev, struct amdgpu_vm *vm)
```

move all BOs to the end of LRU

**Parameters**

- `struct amdgpu_device *adev`: amdgpu device pointer
- `struct amdgpu_vm *vm`: vm providing the BOs

**Description**

Move all BOs to the end of LRU and remember their positions to put them
together.

#### <a id="c-amdgpu_vm_generation"></a>`amdgpu_vm_generation()`

```c
uint64_t amdgpu_vm_generation(struct amdgpu_device *adev, struct amdgpu_vm *vm)
```

return the page table re-generation counter

**Parameters**

- `struct amdgpu_device *adev`: the amdgpu_device
- `struct amdgpu_vm *vm`: optional VM to check, might be NULL

**Description**

Returns a page table re-generation token to allow checking if submissions
are still valid to use this VM. The VM parameter might be NULL in which case
just the VRAM lost counter will be used.

#### <a id="c-amdgpu_vm_validate"></a>`amdgpu_vm_validate()`

```c
int amdgpu_vm_validate(struct amdgpu_device *adev, struct amdgpu_vm *vm, struct ww_acquire_ctx *ticket, int (*validate)(void *p, struct amdgpu_bo *bo), void *param)
```

validate evicted BOs tracked in the VM

**Parameters**

- `struct amdgpu_device *adev`: amdgpu device pointer
- `struct amdgpu_vm *vm`: vm providing the BOs
- `struct ww_acquire_ctx *ticket`: optional reservation ticket used to reserve the VM
- `int (*validate)(void *p, struct amdgpu_bo *bo)`: callback to do the validation
- `void *param`: parameter for the validation callback

**Description**

Validate the page table BOs and per-VM BOs on command submission if
necessary. If a ticket is given, also try to validate evicted user queue
BOs. They must already be reserved with the given ticket.

**Return**

Validation result.

#### <a id="c-amdgpu_vm_ready"></a>`amdgpu_vm_ready()`

```c
bool amdgpu_vm_ready(struct amdgpu_vm *vm)
```

check VM is ready for updates

**Parameters**

- `struct amdgpu_vm *vm`: VM to check

**Description**

Check if all VM PDs/PTs are ready for updates

**Return**

True if VM is not evicting and all VM entities are not stopped

#### <a id="c-amdgpu_vm_check_compute_bug"></a>`amdgpu_vm_check_compute_bug()`

```c
void amdgpu_vm_check_compute_bug(struct amdgpu_device *adev)
```

check whether asic has compute vm bug

**Parameters**

- `struct amdgpu_device *adev`: amdgpu_device pointer

#### <a id="c-amdgpu_vm_need_pipeline_sync"></a>`amdgpu_vm_need_pipeline_sync()`

```c
bool amdgpu_vm_need_pipeline_sync(struct amdgpu_ring *ring, struct amdgpu_job *job)
```

Check if pipe sync is needed for job.

**Parameters**

- `struct amdgpu_ring *ring`: ring on which the job will be submitted
- `struct amdgpu_job *job`: job to submit

**Return**

True if sync is needed.

#### <a id="c-amdgpu_vm_flush"></a>`amdgpu_vm_flush()`

```c
int amdgpu_vm_flush(struct amdgpu_ring *ring, struct amdgpu_job *job, bool need_pipe_sync)
```

hardware flush the vm

**Parameters**

- `struct amdgpu_ring *ring`: ring to use for flush
- `struct amdgpu_job *job`: related job
- `bool need_pipe_sync`: is pipe sync needed

**Description**

Emit a VM flush when it is necessary.

**Return**

0 on success, errno otherwise.

#### <a id="c-amdgpu_vm_bo_find"></a>`amdgpu_vm_bo_find()`

```c
struct amdgpu_bo_va * amdgpu_vm_bo_find(struct amdgpu_vm *vm, struct amdgpu_bo *bo)
```

find the bo_va for a specific vm & bo

**Parameters**

- `struct amdgpu_vm *vm`: requested vm
- `struct amdgpu_bo *bo`: requested buffer object

**Description**

Find **bo** inside the requested vm.
Search inside the **bos** vm list for the requested vm
Returns the found bo_va or NULL if none is found

Object has to be reserved!

**Return**

Found bo_va or NULL.

#### <a id="c-amdgpu_vm_map_gart"></a>`amdgpu_vm_map_gart()`

```c
uint64_t amdgpu_vm_map_gart(const dma_addr_t *pages_addr, uint64_t addr)
```

Resolve gart mapping of addr

**Parameters**

- `const dma_addr_t *pages_addr`: optional DMA address to use for lookup
- `uint64_t addr`: the unmapped addr

**Description**

Look up the physical address of the page that the pte resolves
to.

**Return**

The pointer for the page table entry.

#### <a id="c-amdgpu_vm_update_pdes"></a>`amdgpu_vm_update_pdes()`

```c
int amdgpu_vm_update_pdes(struct amdgpu_device *adev, struct amdgpu_vm *vm, bool immediate)
```

make sure that all directories are valid

**Parameters**

- `struct amdgpu_device *adev`: amdgpu_device pointer
- `struct amdgpu_vm *vm`: requested vm
- `bool immediate`: submit immediately to the paging queue

**Description**

Makes sure all directories are up to date.

**Return**

0 for success, error for failure.

#### <a id="c-amdgpu_vm_tlb_seq_cb"></a>`amdgpu_vm_tlb_seq_cb()`

```c
void amdgpu_vm_tlb_seq_cb(struct dma_fence *fence, struct dma_fence_cb *cb)
```

make sure to increment tlb sequence

**Parameters**

- `struct dma_fence *fence`: unused
- `struct dma_fence_cb *cb`: the callback structure

**Description**

Increments the tlb sequence to make sure that future CS execute a VM flush.

#### <a id="c-amdgpu_vm_tlb_flush"></a>`amdgpu_vm_tlb_flush()`

```c
void amdgpu_vm_tlb_flush(struct amdgpu_vm_update_params *params, struct dma_fence **fence, struct amdgpu_vm_tlb_seq_struct *tlb_cb)
```

prepare TLB flush

**Parameters**

- `struct amdgpu_vm_update_params *params`: parameters for update
- `struct dma_fence **fence`: input fence to sync TLB flush with
- `struct amdgpu_vm_tlb_seq_struct *tlb_cb`: the callback structure

**Description**

Increments the tlb sequence to make sure that future CS execute a VM flush.

#### <a id="c-amdgpu_vm_update_range"></a>`amdgpu_vm_update_range()`

```c
int amdgpu_vm_update_range(struct amdgpu_device *adev, struct amdgpu_vm *vm, bool immediate, bool unlocked, bool flush_tlb, bool allow_override, struct amdgpu_sync *sync, uint64_t start, uint64_t last, uint64_t flags, uint64_t offset, uint64_t vram_base, struct ttm_resource *res, dma_addr_t *pages_addr, struct dma_fence **fence)
```

update a range in the vm page table

**Parameters**

- `struct amdgpu_device *adev`: amdgpu_device pointer to use for commands
- `struct amdgpu_vm *vm`: the VM to update the range
- `bool immediate`: immediate submission in a page fault
- `bool unlocked`: unlocked invalidation during MM callback
- `bool flush_tlb`: trigger tlb invalidation after update completed
- `bool allow_override`: change MTYPE for local NUMA nodes
- `struct amdgpu_sync *sync`: fences we need to sync to
- `uint64_t start`: start of mapped range
- `uint64_t last`: last mapped entry
- `uint64_t flags`: flags for the entries
- `uint64_t offset`: offset into nodes and pages_addr
- `uint64_t vram_base`: base for vram mappings
- `struct ttm_resource *res`: ttm_resource to map
- `dma_addr_t *pages_addr`: DMA addresses to use for mapping
- `struct dma_fence **fence`: optional resulting fence

**Description**

Fill in the page table entries between **start** and **last**.

**Return**

0 for success, negative erro code for failure.

#### <a id="c-amdgpu_vm_bo_update"></a>`amdgpu_vm_bo_update()`

```c
int amdgpu_vm_bo_update(struct amdgpu_device *adev, struct amdgpu_bo_va *bo_va, bool clear)
```

update all BO mappings in the vm page table

**Parameters**

- `struct amdgpu_device *adev`: amdgpu_device pointer
- `struct amdgpu_bo_va *bo_va`: requested BO and VM object
- `bool clear`: if true clear the entries

**Description**

Fill in the page table entries for **bo_va**.

**Return**

0 for success, -EINVAL for failure.

#### <a id="c-amdgpu_vm_update_prt_state"></a>`amdgpu_vm_update_prt_state()`

```c
void amdgpu_vm_update_prt_state(struct amdgpu_device *adev)
```

update the global PRT state

**Parameters**

- `struct amdgpu_device *adev`: amdgpu_device pointer

#### <a id="c-amdgpu_vm_prt_get"></a>`amdgpu_vm_prt_get()`

```c
void amdgpu_vm_prt_get(struct amdgpu_device *adev)
```

add a PRT user

**Parameters**

- `struct amdgpu_device *adev`: amdgpu_device pointer

#### <a id="c-amdgpu_vm_prt_put"></a>`amdgpu_vm_prt_put()`

```c
void amdgpu_vm_prt_put(struct amdgpu_device *adev)
```

drop a PRT user

**Parameters**

- `struct amdgpu_device *adev`: amdgpu_device pointer

#### <a id="c-amdgpu_vm_prt_cb"></a>`amdgpu_vm_prt_cb()`

```c
void amdgpu_vm_prt_cb(struct dma_fence *fence, struct dma_fence_cb *_cb)
```

callback for updating the PRT status

**Parameters**

- `struct dma_fence *fence`: fence for the callback
- `struct dma_fence_cb *_cb`: the callback function

#### <a id="c-amdgpu_vm_add_prt_cb"></a>`amdgpu_vm_add_prt_cb()`

```c
void amdgpu_vm_add_prt_cb(struct amdgpu_device *adev, struct dma_fence *fence)
```

add callback for updating the PRT status

**Parameters**

- `struct amdgpu_device *adev`: amdgpu_device pointer
- `struct dma_fence *fence`: fence for the callback

#### <a id="c-amdgpu_vm_free_mapping"></a>`amdgpu_vm_free_mapping()`

```c
void amdgpu_vm_free_mapping(struct amdgpu_device *adev, struct amdgpu_vm *vm, struct amdgpu_bo_va_mapping *mapping, struct dma_fence *fence)
```

free a mapping

**Parameters**

- `struct amdgpu_device *adev`: amdgpu_device pointer
- `struct amdgpu_vm *vm`: requested vm
- `struct amdgpu_bo_va_mapping *mapping`: mapping to be freed
- `struct dma_fence *fence`: fence of the unmap operation

**Description**

Free a mapping and make sure we decrease the PRT usage count if applicable.

#### <a id="c-amdgpu_vm_prt_fini"></a>`amdgpu_vm_prt_fini()`

```c
void amdgpu_vm_prt_fini(struct amdgpu_device *adev, struct amdgpu_vm *vm)
```

finish all prt mappings

**Parameters**

- `struct amdgpu_device *adev`: amdgpu_device pointer
- `struct amdgpu_vm *vm`: requested vm

**Description**

Register a cleanup callback to disable PRT support after VM dies.

#### <a id="c-amdgpu_vm_clear_freed"></a>`amdgpu_vm_clear_freed()`

```c
int amdgpu_vm_clear_freed(struct amdgpu_device *adev, struct amdgpu_vm *vm, struct dma_fence **fence)
```

clear freed BOs in the PT

**Parameters**

- `struct amdgpu_device *adev`: amdgpu_device pointer
- `struct amdgpu_vm *vm`: requested vm
- `struct dma_fence **fence`: optional resulting fence (unchanged if no work needed to be done
  or if an error occurred)

**Description**

Make sure all freed BOs are cleared in the PT.
PTs have to be reserved and mutex must be locked!

**Return**

0 for success.

#### <a id="c-amdgpu_vm_handle_moved"></a>`amdgpu_vm_handle_moved()`

```c
int amdgpu_vm_handle_moved(struct amdgpu_device *adev, struct amdgpu_vm *vm, struct ww_acquire_ctx *ticket)
```

handle moved BOs in the PT

**Parameters**

- `struct amdgpu_device *adev`: amdgpu_device pointer
- `struct amdgpu_vm *vm`: requested vm
- `struct ww_acquire_ctx *ticket`: optional reservation ticket used to reserve the VM

**Description**

Make sure all BOs which are moved are updated in the PTs.

PTs have to be reserved!

**Return**

0 for success.

#### <a id="c-amdgpu_vm_flush_compute_tlb"></a>`amdgpu_vm_flush_compute_tlb()`

```c
int amdgpu_vm_flush_compute_tlb(struct amdgpu_device *adev, struct amdgpu_vm *vm, uint32_t flush_type, uint32_t xcc_mask)
```

Flush TLB on compute VM

**Parameters**

- `struct amdgpu_device *adev`: amdgpu_device pointer
- `struct amdgpu_vm *vm`: requested vm
- `uint32_t flush_type`: flush type
- `uint32_t xcc_mask`: mask of XCCs that belong to the compute partition in need of a TLB flush.

**Description**

Flush TLB if needed for a compute VM.

**Return**

0 for success.

#### <a id="c-amdgpu_vm_bo_add"></a>`amdgpu_vm_bo_add()`

```c
struct amdgpu_bo_va * amdgpu_vm_bo_add(struct amdgpu_device *adev, struct amdgpu_vm *vm, struct amdgpu_bo *bo)
```

add a bo to a specific vm

**Parameters**

- `struct amdgpu_device *adev`: amdgpu_device pointer
- `struct amdgpu_vm *vm`: requested vm
- `struct amdgpu_bo *bo`: amdgpu buffer object

**Description**

Add **bo** into the requested vm.
Add **bo** to the list of bos associated with the vm

Object has to be reserved!

**Return**

Newly added bo_va or NULL for failure

#### <a id="c-amdgpu_vm_bo_insert_map"></a>`amdgpu_vm_bo_insert_map()`

```c
void amdgpu_vm_bo_insert_map(struct amdgpu_device *adev, struct amdgpu_bo_va *bo_va, struct amdgpu_bo_va_mapping *mapping)
```

insert a new mapping

**Parameters**

- `struct amdgpu_device *adev`: amdgpu_device pointer
- `struct amdgpu_bo_va *bo_va`: bo_va to store the address
- `struct amdgpu_bo_va_mapping *mapping`: the mapping to insert

**Description**

Insert a new mapping into all structures.

#### <a id="c-amdgpu_vm_bo_map"></a>`amdgpu_vm_bo_map()`

```c
int amdgpu_vm_bo_map(struct amdgpu_device *adev, struct amdgpu_bo_va *bo_va, uint64_t saddr, uint64_t offset, uint64_t size, uint32_t flags)
```

map bo inside a vm

**Parameters**

- `struct amdgpu_device *adev`: amdgpu_device pointer
- `struct amdgpu_bo_va *bo_va`: bo_va to store the address
- `uint64_t saddr`: where to map the BO
- `uint64_t offset`: requested offset in the BO
- `uint64_t size`: BO size in bytes
- `uint32_t flags`: attributes of pages (read/write/valid/etc.)

**Description**

Add a mapping of the BO at the specefied addr into the VM.

Object has to be reserved and unreserved outside!

**Return**

0 for success, error for failure.

#### <a id="c-amdgpu_vm_bo_replace_map"></a>`amdgpu_vm_bo_replace_map()`

```c
int amdgpu_vm_bo_replace_map(struct amdgpu_device *adev, struct amdgpu_bo_va *bo_va, uint64_t saddr, uint64_t offset, uint64_t size, uint32_t flags)
```

map bo inside a vm, replacing existing mappings

**Parameters**

- `struct amdgpu_device *adev`: amdgpu_device pointer
- `struct amdgpu_bo_va *bo_va`: bo_va to store the address
- `uint64_t saddr`: where to map the BO
- `uint64_t offset`: requested offset in the BO
- `uint64_t size`: BO size in bytes
- `uint32_t flags`: attributes of pages (read/write/valid/etc.)

**Description**

Add a mapping of the BO at the specefied addr into the VM. Replace existing
mappings as we do so.

Object has to be reserved and unreserved outside!

**Return**

0 for success, error for failure.

#### <a id="c-amdgpu_vm_bo_unmap"></a>`amdgpu_vm_bo_unmap()`

```c
int amdgpu_vm_bo_unmap(struct amdgpu_device *adev, struct amdgpu_bo_va *bo_va, uint64_t saddr)
```

remove bo mapping from vm

**Parameters**

- `struct amdgpu_device *adev`: amdgpu_device pointer
- `struct amdgpu_bo_va *bo_va`: bo_va to remove the address from
- `uint64_t saddr`: where to the BO is mapped

**Description**

Remove a mapping of the BO at the specefied addr from the VM.

Object has to be reserved and unreserved outside!

**Return**

0 for success, error for failure.

#### <a id="c-amdgpu_vm_bo_clear_mappings"></a>`amdgpu_vm_bo_clear_mappings()`

```c
int amdgpu_vm_bo_clear_mappings(struct amdgpu_device *adev, struct amdgpu_vm *vm, uint64_t saddr, uint64_t size)
```

remove all mappings in a specific range

**Parameters**

- `struct amdgpu_device *adev`: amdgpu_device pointer
- `struct amdgpu_vm *vm`: VM structure to use
- `uint64_t saddr`: start of the range
- `uint64_t size`: size of the range

**Description**

Remove all mappings in a range, split them as appropriate.

**Return**

0 for success, error for failure.

#### <a id="c-amdgpu_vm_bo_lookup_mapping"></a>`amdgpu_vm_bo_lookup_mapping()`

```c
struct amdgpu_bo_va_mapping * amdgpu_vm_bo_lookup_mapping(struct amdgpu_vm *vm, uint64_t addr)
```

find mapping by address

**Parameters**

- `struct amdgpu_vm *vm`: the requested VM
- `uint64_t addr`: the address

**Description**

Find a mapping by it's address.

**Return**

The amdgpu_bo_va_mapping matching for addr or NULL

#### <a id="c-amdgpu_vm_bo_trace_cs"></a>`amdgpu_vm_bo_trace_cs()`

```c
void amdgpu_vm_bo_trace_cs(struct amdgpu_vm *vm, struct ww_acquire_ctx *ticket)
```

trace all reserved mappings

**Parameters**

- `struct amdgpu_vm *vm`: the requested vm
- `struct ww_acquire_ctx *ticket`: CS ticket

**Description**

Trace all mappings of BOs reserved during a command submission.

#### <a id="c-amdgpu_vm_bo_del"></a>`amdgpu_vm_bo_del()`

```c
void amdgpu_vm_bo_del(struct amdgpu_device *adev, struct amdgpu_bo_va *bo_va)
```

remove a bo from a specific vm

**Parameters**

- `struct amdgpu_device *adev`: amdgpu_device pointer
- `struct amdgpu_bo_va *bo_va`: requested bo_va

**Description**

Remove **bo_va->bo** from the requested vm.

Object have to be reserved!

#### <a id="c-amdgpu_vm_evictable"></a>`amdgpu_vm_evictable()`

```c
bool amdgpu_vm_evictable(struct amdgpu_bo *bo)
```

check if we can evict a VM

**Parameters**

- `struct amdgpu_bo *bo`: A page table of the VM.

**Description**

Check if it is possible to evict a VM.

#### <a id="c-amdgpu_vm_bo_invalidate"></a>`amdgpu_vm_bo_invalidate()`

```c
void amdgpu_vm_bo_invalidate(struct amdgpu_bo *bo, bool evicted)
```

mark the bo as invalid

**Parameters**

- `struct amdgpu_bo *bo`: amdgpu buffer object
- `bool evicted`: is the BO evicted

**Description**

Mark **bo** as invalid.

#### <a id="c-amdgpu_vm_bo_move"></a>`amdgpu_vm_bo_move()`

```c
void amdgpu_vm_bo_move(struct amdgpu_bo *bo, struct ttm_resource *new_mem, bool evicted)
```

handle BO move

**Parameters**

- `struct amdgpu_bo *bo`: amdgpu buffer object
- `struct ttm_resource *new_mem`: the new placement of the BO move
- `bool evicted`: is the BO evicted

**Description**

Update the memory stats for the new placement and mark **bo** as invalid.

#### <a id="c-amdgpu_vm_get_block_size"></a>`amdgpu_vm_get_block_size()`

```c
uint32_t amdgpu_vm_get_block_size(uint64_t vm_size)
```

calculate VM page table size as power of two

**Parameters**

- `uint64_t vm_size`: VM size

**Return**

VM page table as power of two

#### <a id="c-amdgpu_vm_adjust_size"></a>`amdgpu_vm_adjust_size()`

```c
void amdgpu_vm_adjust_size(struct amdgpu_device *adev, uint32_t min_vm_size, uint32_t fragment_size_default, unsigned max_level, unsigned max_bits)
```

adjust vm size, block size and fragment size

**Parameters**

- `struct amdgpu_device *adev`: amdgpu_device pointer
- `uint32_t min_vm_size`: the minimum vm size in GB if it's set auto
- `uint32_t fragment_size_default`: Default PTE fragment size
- `unsigned max_level`: max VMPT level
- `unsigned max_bits`: max address space size in bits

#### <a id="c-amdgpu_vm_wait_idle"></a>`amdgpu_vm_wait_idle()`

```c
long amdgpu_vm_wait_idle(struct amdgpu_vm *vm, long timeout)
```

wait for the VM to become idle

**Parameters**

- `struct amdgpu_vm *vm`: VM object to wait for
- `long timeout`: timeout to wait for VM to become idle

#### <a id="c-amdgpu_vm_put_task_info"></a>`amdgpu_vm_put_task_info()`

```c
void amdgpu_vm_put_task_info(struct amdgpu_task_info *task_info)
```

reference down the vm task_info ptr

**Parameters**

- `struct amdgpu_task_info *task_info`: task_info struct under discussion.

**Description**

frees the vm task_info ptr at the last put

#### <a id="c-amdgpu_vm_get_task_info_vm"></a>`amdgpu_vm_get_task_info_vm()`

```c
struct amdgpu_task_info * amdgpu_vm_get_task_info_vm(struct amdgpu_vm *vm)
```

Extracts task info for a vm.

**Parameters**

- `struct amdgpu_vm *vm`: VM to get info from

**Description**

Returns the reference counted task_info structure, which must be
referenced down with amdgpu_vm_put_task_info.

#### <a id="c-amdgpu_vm_get_task_info_pasid"></a>`amdgpu_vm_get_task_info_pasid()`

```c
struct amdgpu_task_info * amdgpu_vm_get_task_info_pasid(struct amdgpu_device *adev, u32 pasid)
```

Extracts task info for a PASID.

**Parameters**

- `struct amdgpu_device *adev`: drm device pointer
- `u32 pasid`: PASID identifier for VM

**Description**

Returns the reference counted task_info structure, which must be
referenced down with amdgpu_vm_put_task_info.

#### <a id="c-amdgpu_vm_set_task_info"></a>`amdgpu_vm_set_task_info()`

```c
void amdgpu_vm_set_task_info(struct amdgpu_vm *vm)
```

Sets VMs task info.

**Parameters**

- `struct amdgpu_vm *vm`: vm for which to set the info

#### <a id="c-amdgpu_vm_init"></a>`amdgpu_vm_init()`

```c
int amdgpu_vm_init(struct amdgpu_device *adev, struct amdgpu_vm *vm, int32_t xcp_id, uint32_t pasid)
```

initialize a vm instance

**Parameters**

- `struct amdgpu_device *adev`: amdgpu_device pointer
- `struct amdgpu_vm *vm`: requested vm
- `int32_t xcp_id`: GPU partition selection id
- `uint32_t pasid`: the pasid the VM is using on this GPU

**Description**

Init **vm** fields.

**Return**

0 for success, error for failure.

#### <a id="c-amdgpu_vm_make_compute"></a>`amdgpu_vm_make_compute()`

```c
int amdgpu_vm_make_compute(struct amdgpu_device *adev, struct amdgpu_vm *vm)
```

Turn a GFX VM into a compute VM

**Parameters**

- `struct amdgpu_device *adev`: amdgpu_device pointer
- `struct amdgpu_vm *vm`: requested vm

**Description**

This only works on GFX VMs that don't have any BOs added and no
page tables allocated yet.

Changes the following VM parameters:
- use_cpu_for_update
- pte_supports_ats

Reinitializes the page directory to reflect the changed ATS
setting.

**Return**

0 for success, -errno for errors.

#### <a id="c-amdgpu_vm_fini"></a>`amdgpu_vm_fini()`

```c
void amdgpu_vm_fini(struct amdgpu_device *adev, struct amdgpu_vm *vm)
```

tear down a vm instance

**Parameters**

- `struct amdgpu_device *adev`: amdgpu_device pointer
- `struct amdgpu_vm *vm`: requested vm

**Description**

Tear down **vm**.
Unbind the VM and remove all bos from the vm bo list

#### <a id="c-amdgpu_vm_manager_init"></a>`amdgpu_vm_manager_init()`

```c
void amdgpu_vm_manager_init(struct amdgpu_device *adev)
```

init the VM manager

**Parameters**

- `struct amdgpu_device *adev`: amdgpu_device pointer

**Description**

Initialize the VM manager structures

#### <a id="c-amdgpu_vm_manager_fini"></a>`amdgpu_vm_manager_fini()`

```c
void amdgpu_vm_manager_fini(struct amdgpu_device *adev)
```

cleanup VM manager

**Parameters**

- `struct amdgpu_device *adev`: amdgpu_device pointer

**Description**

Cleanup the VM manager and free resources.

#### <a id="c-amdgpu_vm_ioctl"></a>`amdgpu_vm_ioctl()`

```c
int amdgpu_vm_ioctl(struct drm_device *dev, void *data, struct drm_file *filp)
```

Manages VMID reservation for vm hubs.

**Parameters**

- `struct drm_device *dev`: drm device pointer
- `void *data`: drm_amdgpu_vm
- `struct drm_file *filp`: drm file pointer

**Return**

0 for success, -errno for errors.

#### <a id="c-amdgpu_vm_handle_fault"></a>`amdgpu_vm_handle_fault()`

```c
bool amdgpu_vm_handle_fault(struct amdgpu_device *adev, u32 pasid, u32 vmid, u32 node_id, uint64_t addr, uint64_t ts, bool write_fault)
```

graceful handling of VM faults.

**Parameters**

- `struct amdgpu_device *adev`: amdgpu device pointer
- `u32 pasid`: PASID of the VM
- `u32 vmid`: VMID, only used for GFX 9.4.3.
- `u32 node_id`: Node_id received in IH cookie. Only applicable for
  GFX 9.4.3.
- `uint64_t addr`: Address of the fault
- `uint64_t ts`: Timestamp of the fault
- `bool write_fault`: true is write fault, false is read fault

**Description**

Try to gracefully handle a VM fault. Return true if the fault was handled and
shouldn't be reported any more.

#### <a id="c-amdgpu_debugfs_vm_bo_info"></a>`amdgpu_debugfs_vm_bo_info()`

```c
void amdgpu_debugfs_vm_bo_info(struct amdgpu_vm *vm, struct seq_file *m)
```

print BO info for the VM

**Parameters**

- `struct amdgpu_vm *vm`: Requested VM for printing BO info
- `struct seq_file *m`: debugfs file

**Description**

Print BO information in debugfs file for the VM

#### <a id="c-amdgpu_vm_update_fault_cache"></a>`amdgpu_vm_update_fault_cache()`

```c
void amdgpu_vm_update_fault_cache(struct amdgpu_device *adev, unsigned int pasid, uint64_t addr, uint32_t status, unsigned int vmhub)
```

update cached fault into.

**Parameters**

- `struct amdgpu_device *adev`: amdgpu device pointer
- `unsigned int pasid`: PASID of the VM
- `uint64_t addr`: Address of the fault
- `uint32_t status`: GPUVM fault status register
- `unsigned int vmhub`: which vmhub got the fault

**Description**

Cache the fault info for later use by userspace in debugging.

#### <a id="c-amdgpu_vm_is_bo_always_valid"></a>`amdgpu_vm_is_bo_always_valid()`

```c
bool amdgpu_vm_is_bo_always_valid(struct amdgpu_vm *vm, struct amdgpu_bo *bo)
```

check if the BO is VM always valid

**Parameters**

- `struct amdgpu_vm *vm`: VM to test against.
- `struct amdgpu_bo *bo`: BO to be tested.

**Description**

Returns true if the BO shares the dma_resv object with the root PD and is
always guaranteed to be valid inside the VM.


<a id="rst-interrupt-handling"></a>

## Interrupt Handling


Interrupts generated within GPU hardware raise interrupt requests that are
passed to amdgpu IRQ handler which is responsible for detecting source and
type of the interrupt and dispatching matching handlers. If handling an
interrupt requires calling kernel functions that may sleep processing is
dispatched to work handlers.

If MSI functionality is not disabled by module parameter then MSI
support will be enabled.

For GPU interrupt sources that may be driven by another driver, IRQ domain
support is used (with mapping between virtual and hardware IRQs).



#### <a id="c-amdgpu_irq_disable_all"></a>`amdgpu_irq_disable_all()`

```c
void amdgpu_irq_disable_all(struct amdgpu_device *adev)
```

disable *all* interrupts

**Parameters**

- `struct amdgpu_device *adev`: amdgpu device pointer

**Description**

Disable all types of interrupts from all sources.

#### <a id="c-amdgpu_irq_handler"></a>`amdgpu_irq_handler()`

```c
irqreturn_t amdgpu_irq_handler(int irq, void *arg)
```

IRQ handler

**Parameters**

- `int irq`: IRQ number (unused)
- `void *arg`: pointer to DRM device

**Description**

IRQ handler for amdgpu driver (all ASICs).

**Return**

result of handling the IRQ, as defined by `irqreturn_t`

#### <a id="c-amdgpu_irq_handle_ih1"></a>`amdgpu_irq_handle_ih1()`

```c
void amdgpu_irq_handle_ih1(struct work_struct *work)
```

kick of processing for IH1

**Parameters**

- `struct work_struct *work`: work structure in struct amdgpu_irq

**Description**

Kick of processing IH ring 1.

#### <a id="c-amdgpu_irq_handle_ih2"></a>`amdgpu_irq_handle_ih2()`

```c
void amdgpu_irq_handle_ih2(struct work_struct *work)
```

kick of processing for IH2

**Parameters**

- `struct work_struct *work`: work structure in struct amdgpu_irq

**Description**

Kick of processing IH ring 2.

#### <a id="c-amdgpu_irq_handle_ih_soft"></a>`amdgpu_irq_handle_ih_soft()`

```c
void amdgpu_irq_handle_ih_soft(struct work_struct *work)
```

kick of processing for ih_soft

**Parameters**

- `struct work_struct *work`: work structure in struct amdgpu_irq

**Description**

Kick of processing IH soft ring.

#### <a id="c-amdgpu_msi_ok"></a>`amdgpu_msi_ok()`

```c
bool amdgpu_msi_ok(struct amdgpu_device *adev)
```

check whether MSI functionality is enabled

**Parameters**

- `struct amdgpu_device *adev`: amdgpu device pointer (unused)

**Description**

Checks whether MSI functionality has been disabled via module parameter
(all ASICs).

**Return**

*true* if MSIs are allowed to be enabled or *false* otherwise

#### <a id="c-amdgpu_irq_init"></a>`amdgpu_irq_init()`

```c
int amdgpu_irq_init(struct amdgpu_device *adev)
```

initialize interrupt handling

**Parameters**

- `struct amdgpu_device *adev`: amdgpu device pointer

**Description**

Sets up work functions for hotplug and reset interrupts, enables MSI
functionality, initializes vblank, hotplug and reset interrupt handling.

**Return**

0 on success or error code on failure

#### <a id="c-amdgpu_irq_fini_sw"></a>`amdgpu_irq_fini_sw()`

```c
void amdgpu_irq_fini_sw(struct amdgpu_device *adev)
```

shut down interrupt handling

**Parameters**

- `struct amdgpu_device *adev`: amdgpu device pointer

**Description**

Tears down work functions for hotplug and reset interrupts, disables MSI
functionality, shuts down vblank, hotplug and reset interrupt handling,
turns off interrupts from all sources (all ASICs).

#### <a id="c-amdgpu_irq_add_id"></a>`amdgpu_irq_add_id()`

```c
int amdgpu_irq_add_id(struct amdgpu_device *adev, unsigned int client_id, unsigned int src_id, struct amdgpu_irq_src *source)
```

register IRQ source

**Parameters**

- `struct amdgpu_device *adev`: amdgpu device pointer
- `unsigned int client_id`: client id
- `unsigned int src_id`: source id
- `struct amdgpu_irq_src *source`: IRQ source pointer

**Description**

Registers IRQ source on a client.

**Return**

0 on success or error code otherwise

#### <a id="c-amdgpu_irq_dispatch"></a>`amdgpu_irq_dispatch()`

```c
void amdgpu_irq_dispatch(struct amdgpu_device *adev, struct amdgpu_ih_ring *ih)
```

dispatch IRQ to IP blocks

**Parameters**

- `struct amdgpu_device *adev`: amdgpu device pointer
- `struct amdgpu_ih_ring *ih`: interrupt ring instance

**Description**

Dispatches IRQ to IP blocks.

#### <a id="c-amdgpu_irq_delegate"></a>`amdgpu_irq_delegate()`

```c
void amdgpu_irq_delegate(struct amdgpu_device *adev, struct amdgpu_iv_entry *entry, unsigned int num_dw)
```

delegate IV to soft IH ring

**Parameters**

- `struct amdgpu_device *adev`: amdgpu device pointer
- `struct amdgpu_iv_entry *entry`: IV entry
- `unsigned int num_dw`: size of IV

**Description**

Delegate the IV to the soft IH ring and schedule processing of it. Used
if the hardware delegation to IH1 or IH2 doesn't work for some reason.

#### <a id="c-amdgpu_irq_update"></a>`amdgpu_irq_update()`

```c
int amdgpu_irq_update(struct amdgpu_device *adev, struct amdgpu_irq_src *src, unsigned int type)
```

update hardware interrupt state

**Parameters**

- `struct amdgpu_device *adev`: amdgpu device pointer
- `struct amdgpu_irq_src *src`: interrupt source pointer
- `unsigned int type`: type of interrupt

**Description**

Updates interrupt state for the specific source (all ASICs).

#### <a id="c-amdgpu_irq_gpu_reset_resume_helper"></a>`amdgpu_irq_gpu_reset_resume_helper()`

```c
void amdgpu_irq_gpu_reset_resume_helper(struct amdgpu_device *adev)
```

update interrupt states on all sources

**Parameters**

- `struct amdgpu_device *adev`: amdgpu device pointer

**Description**

Updates state of all types of interrupts on all sources on resume after
reset.

#### <a id="c-amdgpu_irq_get"></a>`amdgpu_irq_get()`

```c
int amdgpu_irq_get(struct amdgpu_device *adev, struct amdgpu_irq_src *src, unsigned int type)
```

enable interrupt

**Parameters**

- `struct amdgpu_device *adev`: amdgpu device pointer
- `struct amdgpu_irq_src *src`: interrupt source pointer
- `unsigned int type`: type of interrupt

**Description**

Enables specified type of interrupt on the specified source (all ASICs).

**Return**

0 on success or error code otherwise

#### <a id="c-amdgpu_irq_put"></a>`amdgpu_irq_put()`

```c
int amdgpu_irq_put(struct amdgpu_device *adev, struct amdgpu_irq_src *src, unsigned int type)
```

disable interrupt

**Parameters**

- `struct amdgpu_device *adev`: amdgpu device pointer
- `struct amdgpu_irq_src *src`: interrupt source pointer
- `unsigned int type`: type of interrupt

**Description**

Enables specified type of interrupt on the specified source (all ASICs).

**Return**

0 on success or error code otherwise

#### <a id="c-amdgpu_irq_enabled"></a>`amdgpu_irq_enabled()`

```c
bool amdgpu_irq_enabled(struct amdgpu_device *adev, struct amdgpu_irq_src *src, unsigned int type)
```

check whether interrupt is enabled or not

**Parameters**

- `struct amdgpu_device *adev`: amdgpu device pointer
- `struct amdgpu_irq_src *src`: interrupt source pointer
- `unsigned int type`: type of interrupt

**Description**

Checks whether the given type of interrupt is enabled on the given source.

**Return**

*true* if interrupt is enabled, *false* if interrupt is disabled or on
invalid parameters

#### <a id="c-amdgpu_irqdomain_map"></a>`amdgpu_irqdomain_map()`

```c
int amdgpu_irqdomain_map(struct irq_domain *d, unsigned int irq, irq_hw_number_t hwirq)
```

create mapping between virtual and hardware IRQ numbers

**Parameters**

- `struct irq_domain *d`: amdgpu IRQ domain pointer (unused)
- `unsigned int irq`: virtual IRQ number
- `irq_hw_number_t hwirq`: hardware irq number

**Description**

Current implementation assigns simple interrupt handler to the given virtual
IRQ.

**Return**

0 on success or error code otherwise

#### <a id="c-amdgpu_irq_add_domain"></a>`amdgpu_irq_add_domain()`

```c
int amdgpu_irq_add_domain(struct amdgpu_device *adev)
```

create a linear IRQ domain

**Parameters**

- `struct amdgpu_device *adev`: amdgpu device pointer

**Description**

Creates an IRQ domain for GPU interrupt sources
that may be driven by another driver (e.g., ACP).

**Return**

0 on success or error code otherwise

#### <a id="c-amdgpu_irq_remove_domain"></a>`amdgpu_irq_remove_domain()`

```c
void amdgpu_irq_remove_domain(struct amdgpu_device *adev)
```

remove the IRQ domain

**Parameters**

- `struct amdgpu_device *adev`: amdgpu device pointer

**Description**

Removes the IRQ domain for GPU interrupt sources
that may be driven by another driver (e.g., ACP).

#### <a id="c-amdgpu_irq_create_mapping"></a>`amdgpu_irq_create_mapping()`

```c
unsigned int amdgpu_irq_create_mapping(struct amdgpu_device *adev, unsigned int src_id)
```

create mapping between domain Linux IRQs

**Parameters**

- `struct amdgpu_device *adev`: amdgpu device pointer
- `unsigned int src_id`: IH source id

**Description**

Creates mapping between a domain IRQ (GPU IH src id) and a Linux IRQ
Use this for components that generate a GPU interrupt, but are driven
by a different driver (e.g., ACP).

**Return**

Linux IRQ


<a id="rst-ip-blocks"></a>

## IP Blocks


GPUs are composed of IP (intellectual property) blocks. These
IP blocks provide various functionalities: display, graphics,
video decode, etc. The IP blocks that comprise a particular GPU
are listed in the GPU's respective SoC file. amdgpu_device.c
acquires the list of IP blocks for the GPU in use on initialization.
It can then operate on this list to perform standard driver operations
such as: init, fini, suspend, resume, etc.

IP block implementations are named using the following convention:
\<functionality>_v\<version> (E.g.: gfx_v6_0).



#### <a id="c-enum-amd_ip_block_type"></a>`enum amd_ip_block_type`

Used to classify IP blocks by functionality.

**Constants**

- `AMD_IP_BLOCK_TYPE_COMMON`: GPU Family
- `AMD_IP_BLOCK_TYPE_GMC`: Graphics Memory Controller
- `AMD_IP_BLOCK_TYPE_IH`: Interrupt Handler
- `AMD_IP_BLOCK_TYPE_SMC`: System Management Controller
- `AMD_IP_BLOCK_TYPE_PSP`: Platform Security Processor
- `AMD_IP_BLOCK_TYPE_DCE`: Display and Compositing Engine
- `AMD_IP_BLOCK_TYPE_GFX`: Graphics and Compute Engine
- `AMD_IP_BLOCK_TYPE_SDMA`: System DMA Engine
- `AMD_IP_BLOCK_TYPE_UVD`: Unified Video Decoder
- `AMD_IP_BLOCK_TYPE_VCE`: Video Compression Engine
- `AMD_IP_BLOCK_TYPE_ACP`: Audio Co-Processor
- `AMD_IP_BLOCK_TYPE_VCN`: Video Core/Codec Next
- `AMD_IP_BLOCK_TYPE_MES`: Micro-Engine Scheduler
- `AMD_IP_BLOCK_TYPE_JPEG`: JPEG Engine
- `AMD_IP_BLOCK_TYPE_VPE`: Video Processing Engine
- `AMD_IP_BLOCK_TYPE_UMSCH_MM`: User Mode Scheduler for Multimedia
- `AMD_IP_BLOCK_TYPE_ISP`: Image Signal Processor
- `AMD_IP_BLOCK_TYPE_RAS`: Reliability, Availability, Serviceability
- `AMD_IP_BLOCK_TYPE_NUM`: Total number of IP block types

#### <a id="c-enum-DC_FEATURE_MASK"></a>`enum DC_FEATURE_MASK`

Bits that control DC feature defaults

**Constants**

- `DC_FBC_MASK`: (0x1) disabled by default
- `DC_MULTI_MON_PP_MCLK_SWITCH_MASK`: (0x2) enabled by default
- `DC_DISABLE_FRACTIONAL_PWM_MASK`: (0x4) disabled by default
- `DC_PSR_MASK`: (0x8) disabled by default for DCN \< 3.1
- `DC_EDP_NO_POWER_SEQUENCING`: (0x10) disabled by default
- `DC_DISABLE_LTTPR_DP1_4A`: (0x20) disabled by default
- `DC_DISABLE_LTTPR_DP2_0`: (0x40) disabled by default
- `DC_PSR_ALLOW_SMU_OPT`: (0x80) disabled by default
- `DC_PSR_ALLOW_MULTI_DISP_OPT`: (0x100) disabled by default
- `DC_REPLAY_MASK`: (0x200) disabled by default for DCN \< 3.1.4

#### <a id="c-enum-DC_DEBUG_MASK"></a>`enum DC_DEBUG_MASK`

Bits that are useful for debugging the Display Core IP

**Constants**

- `DC_DISABLE_PIPE_SPLIT`: (0x1) If set, disable pipe-splitting
- `DC_DISABLE_STUTTER`: (0x2) If set, disable memory stutter mode
- `DC_DISABLE_DSC`: (0x4) If set, disable display stream compression
- `DC_DISABLE_CLOCK_GATING`: (0x8) If set, disable clock gating optimizations
- `DC_DISABLE_PSR`: (0x10) If set, disable Panel self refresh v1 and PSR-SU
- `DC_FORCE_SUBVP_MCLK_SWITCH`: (0x20) If set, force mclk switch in subvp, even
  if mclk switch in vblank is possible
- `DC_DISABLE_MPO`: (0x40) If set, disable multi-plane offloading
- `DC_ENABLE_DPIA_TRACE`: (0x80) If set, enable trace logging for DPIA
- `DC_ENABLE_DML2`: (0x100) If set, force usage of DML2, even if the DCN version
  does not default to it.
- `DC_DISABLE_PSR_SU`: (0x200) If set, disable PSR SU
- `DC_DISABLE_REPLAY`: (0x400) If set, disable Panel Replay
- `DC_DISABLE_IPS`: (0x800) If set, disable all Idle Power States, all the time.
  If more than one IPS debug bit is set, the lowest bit takes
  precedence. For example, if DC_FORCE_IPS_ENABLE and
  DC_DISABLE_IPS_DYNAMIC are set, then DC_DISABLE_IPS_DYNAMIC takes
  precedence.
- `DC_DISABLE_IPS_DYNAMIC`: (0x1000) If set, disable all IPS, all the time,
  *except* when driver goes into suspend.
- `DC_DISABLE_IPS2_DYNAMIC`: (0x2000) If set, disable IPS2 (IPS1 allowed) if
  there is an enabled display. Otherwise, enable all IPS.
- `DC_FORCE_IPS_ENABLE`: (0x4000) If set, force enable all IPS, all the time.
- `DC_DISABLE_ACPI_EDID`: (0x8000) If set, don't attempt to fetch EDID for
  eDP display from ACPI _DDC method.
- `DC_DISABLE_HDMI_CEC`: (0x10000) If set, disable HDMI-CEC feature in amdgpu driver.
- `DC_DISABLE_SUBVP_FAMS`: (0x20000) If set, disable DCN Sub-Viewport & Firmware Assisted
  Memory Clock Switching (FAMS) feature in amdgpu driver.
- `DC_DISABLE_CUSTOM_BRIGHTNESS_CURVE`: (0x40000) If set, disable support for custom
  brightness curves
- `DC_HDCP_LC_FORCE_FW_ENABLE`: (0x80000) If set, use HDCP Locality Check FW
  path regardless of reported HW capabilities.
- `DC_HDCP_LC_ENABLE_SW_FALLBACK`: (0x100000) If set, upon HDCP Locality Check FW
  path failure, retry using legacy SW path.
- `DC_SKIP_DETECTION_LT`: (0x200000) If set, skip detection link training

#### <a id="c-struct-amd_ip_funcs"></a>`struct amd_ip_funcs`

general hooks for managing amdgpu IP Blocks

**Definition**

```c
struct amd_ip_funcs {
    char *name;
    int (*early_init)(struct amdgpu_ip_block *ip_block);
    int (*late_init)(struct amdgpu_ip_block *ip_block);
    int (*sw_init)(struct amdgpu_ip_block *ip_block);
    int (*sw_fini)(struct amdgpu_ip_block *ip_block);
    int (*early_fini)(struct amdgpu_ip_block *ip_block);
    int (*hw_init)(struct amdgpu_ip_block *ip_block);
    int (*hw_fini)(struct amdgpu_ip_block *ip_block);
    void (*late_fini)(struct amdgpu_ip_block *ip_block);
    int (*prepare_suspend)(struct amdgpu_ip_block *ip_block);
    int (*suspend)(struct amdgpu_ip_block *ip_block);
    int (*resume)(struct amdgpu_ip_block *ip_block);
    void (*complete)(struct amdgpu_ip_block *ip_block);
    bool (*is_idle)(struct amdgpu_ip_block *ip_block);
    int (*wait_for_idle)(struct amdgpu_ip_block *ip_block);
    bool (*check_soft_reset)(struct amdgpu_ip_block *ip_block);
    int (*pre_soft_reset)(struct amdgpu_ip_block *ip_block);
    int (*soft_reset)(struct amdgpu_ip_block *ip_block);
    int (*post_soft_reset)(struct amdgpu_ip_block *ip_block);
    int (*set_clockgating_state)(struct amdgpu_ip_block *ip_block, enum amd_clockgating_state state);
    int (*set_powergating_state)(struct amdgpu_ip_block *ip_block, enum amd_powergating_state state);
    void (*get_clockgating_state)(struct amdgpu_ip_block *ip_block, u64 *flags);
    void (*dump_ip_state)(struct amdgpu_ip_block *ip_block);
    void (*print_ip_state)(struct amdgpu_ip_block *ip_block, struct drm_printer *p);
};
```

**Members**

- `name`: Name of IP block
- `early_init`: sets up early driver state (pre sw_init),
  does not configure hw - Optional
- `late_init`: sets up late driver/hw state (post hw_init) - Optional
- `sw_init`: sets up driver state, does not configure hw
- `sw_fini`: tears down driver state, does not configure hw
- `early_fini`: tears down stuff before dev detached from driver
- `hw_init`: sets up the hw state
- `hw_fini`: tears down the hw state
- `late_fini`: final cleanup
- `prepare_suspend`: handle IP specific changes to prepare for suspend
  (such as allocating any required memory)
- `suspend`: handles IP specific hw/sw changes for suspend
- `resume`: handles IP specific hw/sw changes for resume
- `complete`: handles IP specific changes after resume
- `is_idle`: returns current IP block idle status
- `wait_for_idle`: poll for idle
- `check_soft_reset`: check soft reset the IP block
- `pre_soft_reset`: pre soft reset the IP block
- `soft_reset`: soft reset the IP block
- `post_soft_reset`: post soft reset the IP block
- `set_clockgating_state`: enable/disable cg for the IP block
- `set_powergating_state`: enable/disable pg for the IP block
- `get_clockgating_state`: get current clockgating status
- `dump_ip_state`: dump the IP state of the ASIC during a gpu hang
- `print_ip_state`: print the IP state in devcoredump for each IP of the ASIC

**Description**

These hooks provide an interface for controlling the operational state
of IP blocks. After acquiring a list of IP blocks for the GPU in use,
the driver can make chip-wide state changes by walking this list and
making calls to hooks from each IP block. This list is ordered to ensure
that the driver initializes the IP blocks in a safe sequence.

---

# Misc AMDGPU driver information

_Peios Kernel / Hardware and drivers / Graphics / amdgpu_

> Information about the GPU can be obtained on certain cards via sysfs

<a id="rst-misc-amdgpu-driver-information"></a>

<a id="rst-gpu-product-information"></a>

## GPU Product Information

Information about the GPU can be obtained on certain cards via sysfs

<a id="rst-product-name"></a>

### product_name


The amdgpu driver provides a sysfs API for reporting the product name
for the device
The file product_name is used for this and returns the product name
as returned from the FRU.
NOTE: This is only available for certain server cards


<a id="rst-product-number"></a>

### product_number


The amdgpu driver provides a sysfs API for reporting the part number
for the device
The file product_number is used for this and returns the part number
as returned from the FRU.
NOTE: This is only available for certain server cards


<a id="rst-serial-number"></a>

### serial_number


The amdgpu driver provides a sysfs API for reporting the serial number
for the device
The file serial_number is used for this and returns the serial number
as returned from the FRU.
NOTE: This is only available for certain server cards


<a id="rst-fru-id"></a>

### fru_id


The amdgpu driver provides a sysfs API for reporting FRU File Id
for the device.
The file fru_id is used for this and returns the File Id value
as returned from the FRU.
NOTE: This is only available for certain server cards


<a id="rst-manufacturer"></a>

### manufacturer


The amdgpu driver provides a sysfs API for reporting manufacturer name from
FRU information.
The file manufacturer returns the value as returned from the FRU.
NOTE: This is only available for certain server cards


<a id="rst-unique-id"></a>

### unique_id


The amdgpu driver provides a sysfs API for providing a unique ID for the GPU
The file unique_id is used for this.
This will provide a Unique ID that will persist from machine to machine

NOTE: This will only work for GFX9 and newer. This file will be absent
on unsupported ASICs (GFX8 and older)


<a id="rst-board-info"></a>

### board_info


The amdgpu driver provides a sysfs API for giving board related information.
It provides the form factor information in the format

type : form factor

Possible form factor values

- "cem"              - PCIE CEM card
- "oam"              - Open Compute Accelerator Module
- "unknown"  - Not known


<a id="rst-gpu-memory-usage-information"></a>

## GPU Memory Usage Information

Various memory accounting can be accessed via sysfs

<a id="rst-mem-info-vram-total"></a>

### mem_info_vram_total


The amdgpu driver provides a sysfs API for reporting current total VRAM
available on the device
The file mem_info_vram_total is used for this and returns the total
amount of VRAM in bytes


<a id="rst-mem-info-vram-used"></a>

### mem_info_vram_used


The amdgpu driver provides a sysfs API for reporting current total VRAM
available on the device
The file mem_info_vram_used is used for this and returns the total
amount of currently used VRAM in bytes


<a id="rst-mem-info-vis-vram-total"></a>

### mem_info_vis_vram_total


The amdgpu driver provides a sysfs API for reporting current total
visible VRAM available on the device
The file mem_info_vis_vram_total is used for this and returns the total
amount of visible VRAM in bytes


<a id="rst-mem-info-vis-vram-used"></a>

### mem_info_vis_vram_used


The amdgpu driver provides a sysfs API for reporting current total of
used visible VRAM
The file mem_info_vis_vram_used is used for this and returns the total
amount of currently used visible VRAM in bytes


<a id="rst-mem-info-gtt-total"></a>

### mem_info_gtt_total


The amdgpu driver provides a sysfs API for reporting current total size of
the GTT.
The file mem_info_gtt_total is used for this, and returns the total size of
the GTT block, in bytes


<a id="rst-mem-info-gtt-used"></a>

### mem_info_gtt_used


The amdgpu driver provides a sysfs API for reporting current total amount of
used GTT.
The file mem_info_gtt_used is used for this, and returns the current used
size of the GTT block, in bytes


<a id="rst-pcie-accounting-information"></a>

## PCIe Accounting Information

<a id="rst-pcie-bw"></a>

### pcie_bw


The amdgpu driver provides a sysfs API for estimating how much data
has been received and sent by the GPU in the last second through PCIe.
The file pcie_bw is used for this.
The Perf counters count the number of received and sent messages and return
those values, as well as the maximum payload size of a PCIe packet (mps).
Note that it is not possible to easily and quickly obtain the size of each
packet transmitted, so we output the max payload size (mps) to allow for
quick estimation of the PCIe bandwidth usage


<a id="rst-pcie-replay-count"></a>

### pcie_replay_count


The amdgpu driver provides a sysfs API for reporting the total number
of PCIe replays (NAKs).
The file pcie_replay_count is used for this and returns the total
number of replays as a sum of the NAKs generated and NAKs received.


<a id="rst-gpu-smartshift-information"></a>

## GPU SmartShift Information

GPU SmartShift information via sysfs

<a id="rst-smartshift-apu-power"></a>

### smartshift_apu_power


The amdgpu driver provides a sysfs API for reporting APU power
shift in percentage if platform supports smartshift. Value 0 means that
there is no powershift and values between \[1-100\] means that the power
is shifted to APU, the percentage of boost is with respect to APU power
limit on the platform.


<a id="rst-smartshift-dgpu-power"></a>

### smartshift_dgpu_power


The amdgpu driver provides a sysfs API for reporting dGPU power
shift in percentage if platform supports smartshift. Value 0 means that
there is no powershift and values between \[1-100\] means that the power is
shifted to dGPU, the percentage of boost is with respect to dGPU power
limit on the platform.


<a id="rst-smartshift-bias"></a>

### smartshift_bias


The amdgpu driver provides a sysfs API for reporting the
smartshift(SS2.0) bias level. The value ranges from -100 to 100
and the default is 0. -100 sets maximum preference to APU
and 100 sets max perference to dGPU.


<a id="rst-uma-carveout"></a>

## UMA Carveout

Some versions of Atom ROM expose available options for the VRAM carveout sizes, and allow changes to the carveout size via the ATCS function code 0xA on supported BIOS implementations.

For those platforms, users can use the following files under uma/ to set the carveout size, in a way similar to what Windows users can do in the "Tuning" tab in AMD Adrenalin.

Note that for BIOS implementations that don't support this, these files will not be created at all.

<a id="rst-uma-carveout-options"></a>

### uma/carveout_options


This is a read-only file that lists all available UMA allocation
options and their corresponding indices. Example output:

```text
$ cat uma/carveout_options
0: Minimum (512 MB)
1:  (1 GB)
2:  (2 GB)
3:  (4 GB)
4:  (6 GB)
5:  (8 GB)
6:  (12 GB)
7: Medium (16 GB)
8:  (24 GB)
9: High (32 GB)
```


<a id="rst-uma-carveout-1"></a>

### uma/carveout


This file is both readable and writable. When read, it shows the
index of the current setting. Writing a valid index to this file
allows users to change the UMA carveout size to the selected option
on the next boot.

The available options and their corresponding indices can be read
from the uma/carveout_options file.

---

# dGPU firmware flashing

_Peios Kernel / Hardware and drivers / Graphics / amdgpu_

> Flashing the dGPU integrated firmware image (IFWI) is supported by GPUs that use the PSP to orchestrate the update (Navi3x or newer GPUs). For supported GPUs, amdgpu will export a series of sysfs files that can be used for the flash…

<a id="rst-dgpu-firmware-flashing"></a>

<a id="rst-ifwi"></a>

## IFWI

Flashing the dGPU integrated firmware image (IFWI) is supported by GPUs that use the PSP to orchestrate the update (Navi3x or newer GPUs). For supported GPUs, `amdgpu` will export a series of sysfs files that can be used for the flash process.

The IFWI flash process is:

1. Ensure the IFWI image is intended for the dGPU on the system.

2. "Write" the IFWI image to the sysfs file `psp_vbflash`. This will stage the IFWI in memory.

3. "Read" from the `psp_vbflash` sysfs file to initiate the flash process.

4. Poll the `psp_vbflash_status` sysfs file to determine when the flash process completes.

<a id="rst-usb-c-pd-f-w"></a>

## USB-C PD F/W

On GPUs that support flashing an updated USB-C PD firmware image, the process is done using the `usbc_pd_fw` sysfs file.

- Reading the file will provide the current firmware version.

- Writing the name of a firmware payload stored in `/lib/firmware/amdgpu` to the sysfs file will initiate the flash process.

The firmware payload stored in `/lib/firmware/amdgpu` can be named any name as long as it doesn't conflict with other existing binaries that are used by `amdgpu`.

<a id="rst-sysfs-files"></a>

## sysfs files


**usbc_pd_fw**

Reading from this file will retrieve the USB-C PD firmware version. Writing to
this file will trigger the update process.

**psp_vbflash**

Writing to this file will stage an IFWI for update. Reading from this file
will trigger the update process.

**psp_vbflash_status**

The status of the flash process.
0: IFWI flash not complete.
1: IFWI flash complete.

---

# Module Parameters

_Peios Kernel / Hardware and drivers / Graphics / amdgpu_

> The amdgpu driver supports the following module parameters:

<a id="rst-module-parameters"></a>

The amdgpu driver supports the following module parameters:


**vramlimit (int)**

Restrict the total amount of VRAM in MiB for testing.  The default is 0 (Use full VRAM).

**vis_vramlimit (int)**

Restrict the amount of CPU visible VRAM in MiB for testing.  The default is 0 (Use full CPU visible VRAM).

**gartsize (uint)**

Restrict the size of GART (for kernel use) in Mib (32, 64, etc.) for testing.
The default is -1 (The size depends on asic).

**gttsize (int)**

Restrict the size of GTT domain (for userspace use) in MiB for testing.
The default is -1 (Use value specified by TTM).
This parameter is deprecated and will be removed in the future.

**moverate (int)**

Set maximum buffer migration rate in MB/s. The default is -1 (8 MB/s).

**audio (int)**

Set HDMI/DPAudio. Only affects non-DC display handling. The default is -1 (Enabled), set 0 to disabled it.

**disp_priority (int)**

Set display Priority (1 = normal, 2 = high). Only affects non-DC display handling. The default is 0 (auto).

**hw_i2c (int)**

To enable hw i2c engine. Only affects non-DC display handling. The default is 0 (Disabled).

**pcie_gen2 (int)**

To disable PCIE Gen2/3 mode (0 = disable, 1 = enable). The default is -1 (auto, enabled).

**msi (int)**

To disable Message Signaled Interrupts (MSI) functionality (1 = enable, 0 = disable). The default is -1 (auto, enabled).

**svm_default_granularity (uint)**

Used in buffer migration and handling of recoverable page faults

**lockup_timeout (string)**

Set GPU scheduler timeout value in ms.

The format can be \[single value\] for setting all timeouts at once or
\[GFX,Compute,SDMA,Video\] to set individual timeouts.
Negative values mean infinity.

By default(with no lockup_timeout settings), the timeout for all queues is 2000.

**dpm (int)**

Override for dynamic power management setting
(0 = disable, 1 = enable)
The default is -1 (auto).

**fw_load_type (int)**

Set different firmware loading type for debugging, if supported.
Set to 0 to force direct loading if supported by the ASIC.  Set
to -1 to select the default loading mode for the ASIC, as defined
by the driver.  The default is -1 (auto).

**aspm (int)**

To disable ASPM (1 = enable, 0 = disable). The default is -1 (auto, enabled).

**runpm (int)**

Override for runtime power management control for dGPUs. The amdgpu driver can dynamically power down
the dGPUs when they are idle if supported. The default is -1 (auto enable).
Setting the value to 0 disables this functionality.
Setting the value to -2 is auto enabled with power down when displays are attached.

**ip_block_mask (uint)**

Override what IP blocks are enabled on the GPU. Each GPU is a collection of IP blocks (gfx, display, video, etc.).
Use this parameter to disable specific blocks. Note that the IP blocks do not have a fixed index. Some asics may not have
some IPs or may include multiple instances of an IP so the ordering various from asic to asic. See the driver output in
the kernel log for the list of IPs on the asic. The default is 0xffffffff (enable all blocks on a device).

**bapm (int)**

Bidirectional Application Power Management (BAPM) used to dynamically share TDP between CPU and GPU. Set value 0 to disable it.
The default -1 (auto, enabled)

**deep_color (int)**

Set 1 to enable Deep Color support. Only affects non-DC display handling. The default is 0 (disabled).

**vm_size (int)**

Override the size of the GPU's per client virtual address space in GiB.  The default is -1 (automatic for each asic).

**vm_fragment_size (int)**

Override VM fragment size in bits (4, 5, etc. 4 = 64K, 9 = 2M). The default is -1 (automatic for each asic).

**vm_block_size (int)**

Override VM page table size in bits (default depending on vm_size and hw setup). The default is -1 (automatic for each asic).

**vm_fault_stop (int)**

Stop on VM fault for debugging (0 = never, 1 = print first, 2 = always). The default is 0 (No stop).

**vm_update_mode (int)**

Override VM update mode. VM updated by using CPU (0 = never, 1 = Graphics only, 2 = Compute only, 3 = Both). The default
is -1 (Only in large BAR(LB) systems Compute VM tables will be updated by CPU, otherwise 0, never).

**exp_hw_support (int)**

Enable experimental hw support (1 = enable). The default is 0 (disabled).

**dc (int)**

Disable/Enable Display Core driver for debugging (1 = enable, 0 = disable). The default is -1 (automatic for each asic).

**sched_jobs (int)**

Override the max number of jobs supported in the sw queue. The default is 32.

**sched_hw_submission (int)**

Override the max number of HW submissions. The default is 2.

**ppfeaturemask (hexint)**

Override power features enabled. See enum PP_FEATURE_MASK in drivers/gpu/drm/amd/include/amd_shared.h.
The default is the current set of stable power features.

**forcelongtraining (uint)**

Force long memory training in resume.
The default is zero, indicates short training in resume.

**pcie_gen_cap (uint)**

Override PCIE gen speed capabilities. See the CAIL flags in drivers/gpu/drm/amd/include/amd_pcie.h.
The default is 0 (automatic for each asic).

**pcie_lane_cap (uint)**

Override PCIE lanes capabilities. See the CAIL flags in drivers/gpu/drm/amd/include/amd_pcie.h.
The default is 0 (automatic for each asic).

**cg_mask (ullong)**

Override Clockgating features enabled on GPU (0 = disable clock gating). See the AMD_CG_SUPPORT flags in
drivers/gpu/drm/amd/include/amd_shared.h. The default is 0xffffffffffffffff (all enabled).

**pg_mask (uint)**

Override Powergating features enabled on GPU (0 = disable power gating). See the AMD_PG_SUPPORT flags in
drivers/gpu/drm/amd/include/amd_shared.h. The default is 0xffffffff (all enabled).

**sdma_phase_quantum (uint)**

Override SDMA context switch phase quantum (x 1K GPU clock cycles, 0 = no change). The default is 32.

**disable_cu (charp)**

Set to disable CUs (It's set like se.sh.cu,...). The default is NULL.

**virtual_display (charp)**

Set to enable virtual display feature. This feature provides a virtual display hardware on headless boards
or in virtualized environments. It will be set like xxxx:xx:xx.x,x;xxxx:xx:xx.x,x. It's the pci address of
the device, plus the number of crtcs to expose. E.g., 0000:26:00.0,4 would enable 4 virtual crtcs on the pci
device at 26:00.0. The default is NULL.

**lbpw (int)**

Override Load Balancing Per Watt (LBPW) support (1 = enable, 0 = disable). The default is -1 (auto, enabled).

**gpu_recovery (int)**

Set to enable GPU recovery mechanism (1 = enable, 0 = disable). The default is -1 (auto, disabled except SRIOV).

**emu_mode (int)**

Set value 1 to enable emulation mode. This is only needed when running on an emulator. The default is 0 (disabled).

**ras_enable (int)**

Enable RAS features on the GPU (0 = disable, 1 = enable, -1 = auto (default))

**ras_mask (uint)**

Mask of RAS features to enable (default 0xffffffff), only valid when ras_enable == 1
See the flags in drivers/gpu/drm/amd/amdgpu/amdgpu_ras.h

**timeout_fatal_disable (bool)**

Disable Watchdog timeout fatal error event

**timeout_period (uint)**

Modify the watchdog timeout max_cycles as (1 \<\< period)

**si_support (int)**

1 = enabled, 0 = disabled, -1 = default

SI (Southern Islands) are first generation GCN GPUs, supported by both
drivers: radeon (old) and amdgpu (new). This parameter controls whether
amdgpu should support SI.
By default, SI dedicated GPUs are supported by amdgpu.
Only relevant when CONFIG_DRM_AMDGPU_SI is enabled to build SI support in amdgpu.
See also radeon.si_support which should be disabled when amdgpu.si_support is
enabled, and vice versa.

**cik_support (int)**

1 = enabled, 0 = disabled, -1 = default

CIK (Sea Islands) are second generation GCN GPUs, supported by both
drivers: radeon (old) and amdgpu (new). This parameter controls whether
amdgpu should support CIK.
By default:
- CIK dedicated GPUs are supported by amdgpu.
- CIK APUs are supported by radeon (except when radeon is not built).
Only relevant when CONFIG_DRM_AMDGPU_CIK is enabled to build CIK support in amdgpu.
See also radeon.cik_support which should be disabled when amdgpu.cik_support is
enabled, and vice versa.

**smu_memory_pool_size (uint)**

It is used to reserve gtt for smu debug usage, setting value 0 to disable it. The actual size is value * 256MiB.
E.g. 0x1 = 256Mbyte, 0x2 = 512Mbyte, 0x4 = 1 Gbyte, 0x8 = 2GByte. The default is 0 (disabled).

**async_gfx_ring (int)**

It is used to enable gfx rings that could be configured with different prioritites or equal priorities

**mcbp (int)**

It is used to enable mid command buffer preemption. (0 = disabled, 1 = enabled, -1 auto (default))

**discovery (int)**

Allow driver to discover hardware IP information from IP Discovery table at the top of VRAM.
(-1 = auto (default), 0 = disabled, 1 = enabled, 2 = use ip_discovery table from file)

**mes (int)**

Enable Micro Engine Scheduler. This is a new hw scheduling engine for gfx, sdma, and compute.
(0 = disabled (default), 1 = enabled)

**mes_log_enable (int)**

Enable Micro Engine Scheduler log. This is used to enable/disable MES internal log.
(0 = disabled (default), 1 = enabled)

**mes_kiq (int)**

Enable Micro Engine Scheduler KIQ. This is a new engine pipe for kiq.
(0 = disabled (default), 1 = enabled)

**uni_mes (int)**

Enable Unified Micro Engine Scheduler. This is a new engine pipe for unified scheduler.
(0 = disabled (default), 1 = enabled)

**noretry (int)**

Disable XNACK retry in the SQ by default on GFXv9 hardware. On ASICs that
do not support per-process XNACK this also disables retry page faults.
(0 = retry enabled, 1 = retry disabled, -1 auto (default))

**force_asic_type (int)**

A non negative value used to specify the asic type for all supported GPUs.

**use_xgmi_p2p (int)**

Enables/disables XGMI P2P interface (0 = disable, 1 = enable).

**sched_policy (int)**

Set scheduling policy. Default is HWS(hardware scheduling) with over-subscription.
Setting 1 disables over-subscription. Setting 2 disables HWS and statically
assigns queues to HQDs.

**hws_max_conc_proc (int)**

Maximum number of processes that HWS can schedule concurrently. The maximum is the
number of VMIDs assigned to the HWS, which is also the default.

**cwsr_enable (int)**

CWSR(compute wave store and resume) allows the GPU to preempt shader execution in
the middle of a compute wave. Default is 1 to enable this feature. Setting 0
disables it.

**max_num_of_queues_per_device (int)**

Maximum number of queues per device. Valid setting is between 1 and 4096. Default
is 4096.

**send_sigterm (int)**

Send sigterm to HSA process on unhandled exceptions. Default is not to send sigterm
but just print errors on dmesg. Setting 1 enables sending sigterm.

**halt_if_hws_hang (int)**

Halt if HWS hang is detected. Default value, 0, disables the halt on hang.
Setting 1 enables halt on hang.

**hws_gws_support(bool)**

Assume that HWS supports GWS barriers regardless of what firmware version
check says. Default value: false (rely on MEC2 firmware version check).

**queue_preemption_timeout_ms (int)**

queue preemption timeout in ms (1 = Minimum, 9000 = default)

**debug_evictions(bool)**

Enable extra debug messages to help determine the cause of evictions

**no_system_mem_limit(bool)**

Disable system memory limit, to support multiple process shared memory

**no_queue_eviction_on_vm_fault (int)**

If set, process queues will not be evicted on gpuvm fault. This is to keep the wavefront context for debugging (0 = queue eviction, 1 = no queue eviction). The default is 0 (queue eviction).

**mtype_local (int)**

**pcie_p2p (bool)**

Enable PCIe P2P (requires large-BAR). Default value: true (on)

**dcfeaturemask (uint)**

Override display features enabled. See enum DC_FEATURE_MASK in drivers/gpu/drm/amd/include/amd_shared.h.
The default is the current set of stable display features.

**dcdebugmask (uint)**

Display debug options. See enum DC_DEBUG_MASK in drivers/gpu/drm/amd/include/amd_shared.h.

**abmlevel (uint)**

Override the default ABM (Adaptive Backlight Management) level used for DC
enabled hardware. Requires DMCU to be supported and loaded.
Valid levels are 0-4. A value of 0 indicates that ABM should be disabled by
default. Values 1-4 control the maximum allowable brightness reduction via
the ABM algorithm, with 1 being the least reduction and 4 being the most
reduction.

Defaults to -1, or auto. Userspace can only override this level after
boot if it's set to auto.

**damageclips (int)**

Enable or disable damage clips support. If damage clips support is disabled,
we will force full frame updates, irrespective of what user space sends to
us.

Defaults to -1 (where it is enabled unless a PSR-SU display is detected).

**tmz (int)**

Trusted Memory Zone (TMZ) is a method to protect data being written
to or read from memory.

The default value: 0 (off).  TODO: change to auto till it is completed.

**freesync_video (uint)**

Enable the optimization to adjust front porch timing to achieve seamless
mode change experience when setting a freesync supported mode for which full
modeset is not needed.

The Display Core will add a set of modes derived from the base FreeSync
video mode into the corresponding connector's mode list based on commonly
used refresh rates and VRR range of the connected display, when users enable
this feature. From the userspace perspective, they can see a seamless mode
change experience when the change between different refresh rates under the
same resolution. Additionally, userspace applications such as Video playback
can read this modeset list and change the refresh rate based on the video
frame rate. Finally, the userspace can also derive an appropriate mode for a
particular refresh rate based on the FreeSync Mode and add it to the
connector's mode list.

Note: This is an experimental feature.

The default value: 0 (off).

**reset_method (int)**

GPU reset method (-1 = auto (default), 0 = legacy, 1 = mode0, 2 = mode1, 3 = mode2, 4 = baco)

**bad_page_threshold (int) Bad page threshold is specifies the**

threshold value of faulty pages detected by RAS ECC, which may
result in the GPU entering bad status when the number of total
faulty pages by ECC exceeds the threshold value.

**vcnfw_log (int)**

Enable vcnfw log output for debugging, the default is disabled.

**sg_display (int)**

Disable S/G (scatter/gather) display (i.e., display from system memory).
This option is only relevant on APUs.  Set this option to 0 to disable
S/G display if you experience flickering or other issues under memory
pressure and report the issue.

**umsch_mm (int)**

Enable Multi Media User Mode Scheduler. This is a HW scheduling engine for VCN and VPE.
(0 = disabled (default), 1 = enabled)

**umsch_mm_fwlog (int)**

Enable umschfw log output for debugging, the default is disabled.

**smu_pptable_id (int)**

Used to override pptable id. id = 0 use VBIOS pptable.
id > 0 use the soft pptable with specicfied id.

**partition_mode (int)**

Used to override the default SPX mode.

**enforce_isolation (int)**

enforce process isolation between graphics and compute.
(-1 = auto, 0 = disable, 1 = enable, 2 = enable legacy mode, 3 = enable without cleaner shader)

**modeset (int)**

Override nomodeset (1 = override, -1 = auto). The default is -1 (auto).

**seamless (int)**

Seamless boot will keep the image on the screen during the boot process.

**debug_mask (uint)**

Debug options for amdgpu, work as a binary mask with the following options:

- 0x1: Debug VM handling
- 0x2: Enable simulating large-bar capability on non-large bar system. This
  limits the VRAM size reported to ROCm applications to the visible
  size, usually 256MB.
- 0x4: Disable GPU soft recovery, always do a full reset
- 0x8: Use VRAM for firmware loading
- 0x10: Enable ACA based RAS logging
- 0x20: Enable experimental resets
- 0x40: Disable ring resets
- 0x80: Use VRAM for SMU pool

**agp (int)**

Enable the AGP aperture.  This provides an aperture in the GPU's internal
address space for direct access to system memory.  Note that these accesses
are non-snooped, so they are only used for access to uncached memory.

**wbrf (int)**

Enable Wifi RFI interference mitigation feature.
Due to electrical and mechanical constraints there may be likely interference of
relatively high-powered harmonics of the (G-)DDR memory clocks with local radio
module frequency bands used by Wifi 6/6e/7. To mitigate the possible RFI interference,
with this feature enabled, PMFW will use either “shadowed P-State” or “P-State” based
on active list of frequencies in-use (to be avoided) as part of initial setting or
P-state transition. However, there may be potential performance impact with this
feature enabled.
(0 = disabled, 1 = enabled, -1 = auto (default setting, will be enabled if supported))

**rebar (int)**

Allow BAR resizing.  Disable this to prevent the driver from attempting
to resize the BAR if the GPU supports it and there is available MMIO space.
Note that this just prevents the driver from resizing the BAR.  The BIOS
may have already resized the BAR at boot time.

**user_queue (int)**

Enable user queues on systems that support user queues. Possible values:

- -1 = auto (ASIC specific default)
- 0 = user queues disabled
- 1 = user queues enabled and kernel queues enabled (if supported)
- 2 = user queues enabled and kernel queues disabled

---

# AMDGPU Process Isolation

_Peios Kernel / Hardware and drivers / Graphics / amdgpu_

> The AMDGPU driver includes a feature that enables automatic process isolation on the graphics engine. This feature serializes access to the graphics engine and adds a cleaner shader which clears the Local Data Store (LDS) and General…

<a id="rst-amdgpu-process-isolation-1"></a>

<a id="rst-amdgpu-process-isolation"></a>



<!-- SPDX-License-Identifier: GPL-2.0 -->

The AMDGPU driver includes a feature that enables automatic process isolation on the graphics engine. This feature serializes access to the graphics engine and adds a cleaner shader which clears the Local Data Store (LDS) and General Purpose Registers (GPRs) between jobs. All processes using the GPU, including both graphics and compute workloads, are serialized when this feature is enabled. On GPUs that support partitionable graphics engines, this feature can be enabled on a per-partition basis.

In addition, there is an interface to manually run the cleaner shader when the use of the GPU is complete. This may be preferable in some use cases, such as a single-user system where the login manager triggers the cleaner shader when the user logs out.

<a id="rst-process-isolation"></a>

## Process Isolation

The `run_cleaner_shader` and `enforce_isolation` sysfs interfaces allow users to manually execute the cleaner shader and control the process isolation feature, respectively.

<a id="rst-partition-handling"></a>

### Partition Handling

The `enforce_isolation` file in sysfs can be used to enable process isolation and automatic shader cleanup between processes. On GPUs that support graphics engine partitioning, this can be enabled per partition. The partition and its current setting (0 disabled, 1 enabled) can be read from sysfs. On GPUs that do not support graphics engine partitioning, only a single partition will be present. Writing 1 to the partition position enables enforce isolation, writing 0 disables it.

Example of enabling enforce isolation on a GPU with multiple partitions:



```console
$ echo 1 0 1 0 > /sys/class/drm/card0/device/enforce_isolation
$ cat /sys/class/drm/card0/device/enforce_isolation
1 0 1 0
```

The output indicates that enforce isolation is enabled on zeroth and second partition and disabled on first and third partition.

For devices with a single partition or those that do not support partitions, there will be only one element:



```console
$ echo 1 > /sys/class/drm/card0/device/enforce_isolation
$ cat /sys/class/drm/card0/device/enforce_isolation
1
```

<a id="rst-cleaner-shader-execution"></a>

## Cleaner Shader Execution

The driver can trigger a cleaner shader to clean up the LDS and GPR state on the graphics engine. When process isolation is enabled, this happens automatically between processes. In addition, there is a sysfs file to manually trigger cleaner shader execution.

To manually trigger the execution of the cleaner shader, write `0` to the `run_cleaner_shader` sysfs file:



```console
$ echo 0 > /sys/class/drm/card0/device/run_cleaner_shader
```

For multi-partition devices, you can specify the partition index when triggering the cleaner shader:



```console
$ echo 0 > /sys/class/drm/card0/device/run_cleaner_shader # For partition 0
$ echo 1 > /sys/class/drm/card0/device/run_cleaner_shader # For partition 1
$ echo 2 > /sys/class/drm/card0/device/run_cleaner_shader # For partition 2
# ... and so on for each partition
```

This command initiates the cleaner shader, which will run and complete before any new tasks are scheduled on the GPU.

---

# AMDGPU RAS Support

_Peios Kernel / Hardware and drivers / Graphics / amdgpu_

> The AMDGPU RAS interfaces are exposed via sysfs (for informational queries) and debugfs (for error injection).

<a id="rst-amdgpu-ras-support"></a>

The AMDGPU RAS interfaces are exposed via sysfs (for informational queries) and debugfs (for error injection).

<a id="rst-ras-debugfs-sysfs-control-and-error-injection-interfaces"></a>

## RAS debugfs/sysfs Control and Error Injection Interfaces


The control interface accepts struct ras_debug_if which has two members.

First member: ras_debug_if::head or ras_debug_if::inject.

head is used to indicate which IP block will be under control.

head has four members, they are block, type, sub_block_index, name.
block: which IP will be under control.
type: what kind of error will be enabled/disabled/injected.
sub_block_index: some IPs have subcomponets. say, GFX, sDMA.
name: the name of IP.

inject has three more members than head, they are address, value and mask.
As their names indicate, inject operation will write the
value to the address.

The second member: struct ras_debug_if::op.
It has three kinds of operations.

- 0: disable RAS on the block. Take ::head as its data.
- 1: enable RAS on the block. Take ::head as its data.
- 2: inject errors on the block. Take ::inject as its data.

How to use the interface?

In a program

Copy the struct ras_debug_if in your code and initialize it.
Write the struct to the control interface.

From shell

```bash
echo "disable <block>" > /sys/kernel/debug/dri/<N>/ras/ras_ctrl
echo "enable  <block> <error>" > /sys/kernel/debug/dri/<N>/ras/ras_ctrl
echo "inject  <block> <error> <sub-block> <address> <value> <mask>" > /sys/kernel/debug/dri/<N>/ras/ras_ctrl
```

Where N, is the card which you want to affect.

"disable" requires only the block.
"enable" requires the block and error type.
"inject" requires the block, error type, address, and value.

- The block is one of: umc, sdma, gfx, etc.

  see ras_block_string\[\] for details

- The error type is one of: ue, ce and poison where,

  ue is multi-uncorrectable
  ce is single-correctable
  poison is poison

The sub-block is a the sub-block index, pass 0 if there is no sub-block.
The address and value are hexadecimal numbers, leading 0x is optional.
The mask means instance mask, is optional, default value is 0x1.

For instance,

```bash
echo inject umc ue 0x0 0x0 0x0 > /sys/kernel/debug/dri/0/ras/ras_ctrl
echo inject umc ce 0 0 0 3 > /sys/kernel/debug/dri/0/ras/ras_ctrl
echo disable umc > /sys/kernel/debug/dri/0/ras/ras_ctrl
```

How to check the result of the operation?

To check disable/enable, see "ras" features at,
/sys/class/drm/card\[0/1/2...\]/device/ras/features

To check inject, see the corresponding error count at,
/sys/class/drm/card\[0/1/2...\]/device/ras/\[gfx|sdma|umc|...\]_err_count

> [!NOTE]
> Operations are only allowed on blocks which are supported.
> Check the "ras" mask at /sys/module/amdgpu/parameters/ras_mask
> to see which blocks support RAS on a particular asic.


<a id="rst-ras-reboot-behavior-for-unrecoverable-errors"></a>

## RAS Reboot Behavior for Unrecoverable Errors


Normally when there is an uncorrectable error, the driver will reset
the GPU to recover.  However, in the event of an unrecoverable error,
the driver provides an interface to reboot the system automatically
in that event.

The following file in debugfs provides that interface:
/sys/kernel/debug/dri/\[0/1/2...\]/ras/auto_reboot

Usage:

```bash
echo true > .../ras/auto_reboot
```


<a id="rst-ras-error-count-sysfs-interface"></a>

## RAS Error Count sysfs Interface


It allows the user to read the error count for each IP block on the gpu through
/sys/class/drm/card\[0/1/2...\]/device/ras/\[gfx/sdma/...\]_err_count

It outputs the multiple lines which report the uncorrected (ue) and corrected
(ce) error counts.

The format of one line is below,

\[ce|ue\]: count

Example:

```bash
ue: 0
ce: 1
```


<a id="rst-ras-eeprom-debugfs-interface"></a>

## RAS EEPROM debugfs Interface


Some boards contain an EEPROM which is used to persistently store a list of
bad pages which experiences ECC errors in vram.  This interface provides
a way to reset the EEPROM, e.g., after testing error injection.

Usage:

```bash
echo 1 > ../ras/ras_eeprom_reset
```

will reset EEPROM table to 0 entries.


<a id="rst-ras-vram-bad-pages-sysfs-interface"></a>

## RAS VRAM Bad Pages sysfs Interface


It allows user to read the bad pages of vram on the gpu through
/sys/class/drm/card\[0/1/2...\]/device/ras/gpu_vram_bad_pages

It outputs multiple lines, and each line stands for one gpu page.

The format of one line is below,
gpu pfn : gpu page size : flags

gpu pfn and gpu page size are printed in hex format.
flags can be one of below character,

R: reserved, this gpu page is reserved and not able to use.

P: pending for reserve, this gpu page is marked as bad, will be reserved
in next window of page_reserve.

F: unable to reserve. this gpu page can't be reserved due to some reasons.

Examples:

```bash
0x00000001 : 0x00001000 : R
0x00000002 : 0x00001000 : P
```


<a id="rst-sample-code"></a>

## Sample Code

Sample code for testing error injection can be found here: [https://cgit.freedesktop.org/mesa/drm/tree/tests/amdgpu/ras_tests.c](<https://cgit.freedesktop.org/mesa/drm/tree/tests/amdgpu/ras_tests.c>)

This is part of the libdrm amdgpu unit tests which cover several areas of the GPU. There are four sets of tests:

RAS Basic Test

The test verifies the RAS feature enabled status and makes sure the necessary sysfs and debugfs files are present.

RAS Query Test

This test checks the RAS availability and enablement status for each supported IP block as well as the error counts.

RAS Inject Test

This test injects errors for each IP.

RAS Disable Test

This test tests disabling of RAS features for each IP block.

---

# Ring Buffer

_Peios Kernel / Hardware and drivers / Graphics / amdgpu_

> To handle communication between user space and kernel space, AMD GPUs use a ring buffer design to feed the engines (GFX, Compute, SDMA, UVD, VCE, VCN, VPE, etc.). See the figure below that illustrates how this communication works:

<a id="rst-ring-buffer"></a>

To handle communication between user space and kernel space, AMD GPUs use a ring buffer design to feed the engines (GFX, Compute, SDMA, UVD, VCE, VCN, VPE, etc.). See the figure below that illustrates how this communication works:

![](/kernel/hardware/gpu/amdgpu/asset-ed164df88abc-ring-buffers.svg)

Ring buffers in the amdgpu work as a producer-consumer model, where userspace acts as the producer, constantly filling the ring buffer with GPU commands to be executed. Meanwhile, the GPU retrieves the information from the ring, parses it, and distributes the specific set of instructions between the different amdgpu blocks.

Notice from the diagram that the ring has a Read Pointer (rptr), which indicates where the engine is currently reading packets from the ring, and a Write Pointer (wptr), which indicates how many packets software has added to the ring. When the rptr and wptr are equal, the ring is idle. When software adds packets to the ring, it updates the wptr, this causes the engine to start fetching and processing packets. As the engine processes packets, the rptr gets updates until the rptr catches up to the wptr and they are equal again.

Usually, ring buffers in the driver have a limited size (search for occurrences of `amdgpu_ring_init()`). One of the reasons for the small ring buffer size is that CP (Command Processor) is capable of following addresses inserted into the ring; this is illustrated in the image by the reference to the IB (Indirect Buffer). The IB gives userspace the possibility to have an area in memory that CP can read and feed the hardware with extra instructions.

All ASICs pre-GFX11 use what is called a kernel queue, which means the ring is allocated in kernel space and has some restrictions, such as not being able to be [preempted directly by the scheduler](</kernel/hardware/gpu/amdgpu-gc/mes.md#rst-amdgpu-mes>). GFX11 and newer support kernel queues, but also provide a new mechanism named [user queues](</kernel/hardware/gpu/amdgpu/userq.md#rst-amdgpu-userq>), where the queue is moved to the user space and can be mapped and unmapped via the scheduler. In practice, both queues insert user-space-generated GPU commands from different jobs into the requested component ring.

<a id="rst-enforce-isolation"></a>

## Enforce Isolation

> [!NOTE]
>
> After reading this section, you might want to check the [Process Isolation](</kernel/hardware/gpu/amdgpu/process-isolation.md#rst-amdgpu-process-isolation>) page for more details.

Before examining the Enforce Isolation mechanism in the ring buffer context, it is helpful to briefly discuss how instructions from the ring buffer are processed in the graphics pipeline. Let’s expand on this topic by checking the diagram below that illustrates the graphics pipeline:

![](/kernel/hardware/gpu/amdgpu/asset-b8b460055c21-gfx-pipeline-seq.svg)

In terms of executing instructions, the GFX pipeline follows the sequence: Shader Export (SX), Geometry Engine (GE), Shader Process or Input (SPI), Scan Converter (SC), Primitive Assembler (PA), and cache manipulation (which may vary across ASICs). Another common way to describe the pipeline is to use Pixel Shader (PS), raster, and Vertex Shader (VS) to symbolize the two shader stages. Now, with this pipeline in mind, let's assume that Job B causes a hang issue, but Job C's instruction might already be executing, leading developers to incorrectly identify Job C as the problematic one. This problem can be mitigated on multiple levels; the diagram below illustrates how to minimize part of this problem:

![](/kernel/hardware/gpu/amdgpu/asset-54e071359aed-no-enforce-isolation.svg)

Note from the diagram that there is no guarantee of order or a clear separation between instructions, which is not a problem most of the time, and is also good for performance. Furthermore, notice some circles between jobs in the diagram that represent a **fence wait** used to avoid overlapping work in the ring. At the end of the fence, a cache flush occurs, ensuring that when the next job starts, it begins in a clean state and, if issues arise, the developer can pinpoint the problematic process more precisely.

To increase the level of isolation between jobs, there is the "Enforce Isolation" method described in the picture below:

![](/kernel/hardware/gpu/amdgpu/asset-ef3b143fcbf4-enforce-isolation.svg)

As shown in the diagram, enforcing isolation introduces ordering between submissions, since the access to GFX/Compute is serialized, think about it as single process at a time mode for gfx/compute. Notice that this approach has a significant performance impact, as it allows only one job to submit commands at a time. However, this option can help pinpoint the job that caused the problem. Although enforcing isolation improves the situation, it does not fully resolve the issue of precisely pinpointing bad jobs, since isolation might mask the problem. In summary, identifying which job caused the issue may not be precise, but enforcing isolation might help with the debugging.

<a id="rst-ring-operations"></a>

## Ring Operations


#### <a id="c-amdgpu_ring_max_ibs"></a>`amdgpu_ring_max_ibs()`

```c
unsigned int amdgpu_ring_max_ibs(enum amdgpu_ring_type type)
```

Return max IBs that fit in a single submission.

**Parameters**

- `enum amdgpu_ring_type type`: ring type for which to return the limit.

#### <a id="c-amdgpu_ring_alloc"></a>`amdgpu_ring_alloc()`

```c
int amdgpu_ring_alloc(struct amdgpu_ring *ring, unsigned int ndw)
```

allocate space on the ring buffer

**Parameters**

- `struct amdgpu_ring *ring`: amdgpu_ring structure holding ring information
- `unsigned int ndw`: number of dwords to allocate in the ring buffer

**Description**

Allocate **ndw** dwords in the ring buffer. The number of dwords should be the
sum of all commands written to the ring.

**Return**

0 on success, otherwise -ENOMEM if it tries to allocate more than the
maximum dword allowed for one submission.

#### <a id="c-amdgpu_ring_alloc_reemit"></a>`amdgpu_ring_alloc_reemit()`

```c
void amdgpu_ring_alloc_reemit(struct amdgpu_ring *ring, unsigned int ndw)
```

allocate space on the ring buffer for reemit

**Parameters**

- `struct amdgpu_ring *ring`: amdgpu_ring structure holding ring information
- `unsigned int ndw`: number of dwords to allocate in the ring buffer

**Description**

Allocate **ndw** dwords in the ring buffer (all asics).
doesn't check the max_dw limit as we may be reemitting
several submissions.

#### <a id="c-amdgpu_ring_insert_nop"></a>`amdgpu_ring_insert_nop()`

```c
void amdgpu_ring_insert_nop(struct amdgpu_ring *ring, uint32_t count)
```

insert NOP packets

**Parameters**

- `struct amdgpu_ring *ring`: amdgpu_ring structure holding ring information
- `uint32_t count`: the number of NOP packets to insert

**Description**

This is the generic insert_nop function for rings except SDMA

#### <a id="c-amdgpu_ring_generic_pad_ib"></a>`amdgpu_ring_generic_pad_ib()`

```c
void amdgpu_ring_generic_pad_ib(struct amdgpu_ring *ring, struct amdgpu_ib *ib)
```

pad IB with NOP packets

**Parameters**

- `struct amdgpu_ring *ring`: amdgpu_ring structure holding ring information
- `struct amdgpu_ib *ib`: IB to add NOP packets to

**Description**

This is the generic pad_ib function for rings except SDMA

#### <a id="c-amdgpu_ring_commit"></a>`amdgpu_ring_commit()`

```c
void amdgpu_ring_commit(struct amdgpu_ring *ring)
```

tell the GPU to execute the new commands on the ring buffer

**Parameters**

- `struct amdgpu_ring *ring`: amdgpu_ring structure holding ring information

**Description**

Update the wptr (write pointer) to tell the GPU to
execute new commands on the ring buffer (all asics).

#### <a id="c-amdgpu_ring_undo"></a>`amdgpu_ring_undo()`

```c
void amdgpu_ring_undo(struct amdgpu_ring *ring)
```

reset the wptr

**Parameters**

- `struct amdgpu_ring *ring`: amdgpu_ring structure holding ring information

**Description**

Reset the driver's copy of the wptr (all asics).

#### <a id="c-amdgpu_ring_init"></a>`amdgpu_ring_init()`

```c
int amdgpu_ring_init(struct amdgpu_device *adev, struct amdgpu_ring *ring, unsigned int max_dw, struct amdgpu_irq_src *irq_src, unsigned int irq_type, unsigned int hw_prio, atomic_t *sched_score)
```

init driver ring struct.

**Parameters**

- `struct amdgpu_device *adev`: amdgpu_device pointer
- `struct amdgpu_ring *ring`: amdgpu_ring structure holding ring information
- `unsigned int max_dw`: maximum number of dw for ring alloc
- `struct amdgpu_irq_src *irq_src`: interrupt source to use for this ring
- `unsigned int irq_type`: interrupt type to use for this ring
- `unsigned int hw_prio`: ring priority (NORMAL/HIGH)
- `atomic_t *sched_score`: optional score atomic shared with other schedulers

**Description**

Initialize the driver information for the selected ring (all asics).
Returns 0 on success, error on failure.

#### <a id="c-amdgpu_ring_fini"></a>`amdgpu_ring_fini()`

```c
void amdgpu_ring_fini(struct amdgpu_ring *ring)
```

tear down the driver ring struct.

**Parameters**

- `struct amdgpu_ring *ring`: amdgpu_ring structure holding ring information

**Description**

Tear down the driver information for the selected ring (all asics).

#### <a id="c-amdgpu_ring_emit_reg_write_reg_wait_helper"></a>`amdgpu_ring_emit_reg_write_reg_wait_helper()`

```c
void amdgpu_ring_emit_reg_write_reg_wait_helper(struct amdgpu_ring *ring, uint32_t reg0, uint32_t reg1, uint32_t ref, uint32_t mask)
```

ring helper

**Parameters**

- `struct amdgpu_ring *ring`: ring to write to
- `uint32_t reg0`: register to write
- `uint32_t reg1`: register to wait on
- `uint32_t ref`: reference value to write/wait on
- `uint32_t mask`: mask to wait on

**Description**

Helper for rings that don't support write and wait in a
single oneshot packet.

#### <a id="c-amdgpu_ring_soft_recovery"></a>`amdgpu_ring_soft_recovery()`

```c
bool amdgpu_ring_soft_recovery(struct amdgpu_ring *ring, unsigned int vmid, struct dma_fence *fence)
```

try to soft recover a ring lockup

**Parameters**

- `struct amdgpu_ring *ring`: ring to try the recovery on
- `unsigned int vmid`: VMID we try to get going again
- `struct dma_fence *fence`: timedout fence

**Description**

Tries to get a ring proceeding again when it is stuck.

#### <a id="c-amdgpu_ring_test_helper"></a>`amdgpu_ring_test_helper()`

```c
int amdgpu_ring_test_helper(struct amdgpu_ring *ring)
```

tests ring and set sched readiness status

**Parameters**

- `struct amdgpu_ring *ring`: ring to try the recovery on

**Description**

Tests ring and set sched readiness status

Returns 0 on success, error on failure.

---

# GPU Power/Thermal Controls and Monitoring

_Peios Kernel / Hardware and drivers / Graphics / amdgpu_

> GPU power controls are exposed via sysfs files.

<a id="rst-gpu-power-thermal-controls-and-monitoring"></a>

<a id="rst-hwmon-interfaces"></a>

## HWMON Interfaces


The amdgpu driver exposes the following sensor interfaces:

- GPU temperature (via the on-die sensor)

- GPU voltage

- Northbridge voltage (APUs only)

- GPU power

- GPU fan

- GPU gfx/compute engine clock

- GPU memory clock (dGPU only)

hwmon interfaces for GPU temperature:

- temp\[1-3\]_input: the on die GPU temperature in millidegrees Celsius
  - temp2_input and temp3_input are supported on SOC15 dGPUs only

- temp\[1-3\]_label: temperature channel label
  - temp2_label and temp3_label are supported on SOC15 dGPUs only

- temp\[1-3\]_crit: temperature critical max value in millidegrees Celsius
  - temp2_crit and temp3_crit are supported on SOC15 dGPUs only

- temp\[1-3\]_crit_hyst: temperature hysteresis for critical limit in millidegrees Celsius
  - temp2_crit_hyst and temp3_crit_hyst are supported on SOC15 dGPUs only

- temp\[1-3\]_emergency: temperature emergency max value(asic shutdown) in millidegrees Celsius
  - these are supported on SOC15 dGPUs only

hwmon interfaces for GPU voltage:

- in0_input: the voltage on the GPU in millivolts

- in1_input: the voltage on the Northbridge in millivolts

hwmon interfaces for GPU power:

- power1_average: average power used by the SoC in microWatts.  On APUs this includes the CPU.

- power1_input: instantaneous power used by the SoC in microWatts.  On APUs this includes the CPU.

- power1_cap_min: minimum cap supported in microWatts

- power1_cap_max: maximum cap supported in microWatts

- power1_cap: selected power cap in microWatts

hwmon interfaces for GPU fan:

- pwm1: pulse width modulation fan level (0-255)

- pwm1_enable: pulse width modulation fan control method (0: no fan speed control, 1: manual fan speed control using pwm interface, 2: automatic fan speed control)

- pwm1_min: pulse width modulation fan control minimum level (0)

- pwm1_max: pulse width modulation fan control maximum level (255)

- fan1_min: a minimum value Unit: revolution/min (RPM)

- fan1_max: a maximum value Unit: revolution/max (RPM)

- fan1_input: fan speed in RPM

- fan\[1-\*\]_target: Desired fan speed Unit: revolution/min (RPM)

- fan\[1-\*\]_enable: Enable or disable the sensors.1: Enable 0: Disable

NOTE: DO NOT set the fan speed via "pwm1" and "fan\[1-\*\]_target" interfaces at the same time.
That will get the former one overridden.

hwmon interfaces for GPU clocks:

- freq1_input: the gfx/compute clock in hertz

- freq2_input: the memory clock in hertz

You can use hwmon tools like sensors to view this information on your system.


<a id="rst-gpu-sysfs-power-state-interfaces"></a>

## GPU sysfs Power State Interfaces

GPU power controls are exposed via sysfs files.

<a id="rst-power-dpm-state"></a>

### power_dpm_state


The power_dpm_state file is a legacy interface and is only provided for
backwards compatibility. The amdgpu driver provides a sysfs API for adjusting
certain power related parameters.  The file power_dpm_state is used for this.
It accepts the following arguments:

- battery

- balanced

- performance

battery

On older GPUs, the vbios provided a special power state for battery
operation.  Selecting battery switched to this state.  This is no
longer provided on newer GPUs so the option does nothing in that case.

balanced

On older GPUs, the vbios provided a special power state for balanced
operation.  Selecting balanced switched to this state.  This is no
longer provided on newer GPUs so the option does nothing in that case.

performance

On older GPUs, the vbios provided a special power state for performance
operation.  Selecting performance switched to this state.  This is no
longer provided on newer GPUs so the option does nothing in that case.


<a id="rst-power-dpm-force-performance-level"></a>

### power_dpm_force_performance_level


The amdgpu driver provides a sysfs API for adjusting certain power
related parameters.  The file power_dpm_force_performance_level is
used for this.  It accepts the following arguments:

- auto

- low

- high

- manual

- profile_standard

- profile_min_sclk

- profile_min_mclk

- profile_peak

auto

When auto is selected, the driver will attempt to dynamically select
the optimal power profile for current conditions in the driver.

low

When low is selected, the clocks are forced to the lowest power state.

high

When high is selected, the clocks are forced to the highest power state.

manual

When manual is selected, the user can manually adjust which power states
are enabled for each clock domain via the sysfs pp_dpm_mclk, pp_dpm_sclk,
and pp_dpm_pcie files and adjust the power state transition heuristics
via the pp_power_profile_mode sysfs file.

profile_standard
profile_min_sclk
profile_min_mclk
profile_peak

When the profiling modes are selected, clock and power gating are
disabled and the clocks are set for different profiling cases. This
mode is recommended for profiling specific work loads where you do
not want clock or power gating for clock fluctuation to interfere
with your results. profile_standard sets the clocks to a fixed clock
level which varies from asic to asic.  profile_min_sclk forces the sclk
to the lowest level.  profile_min_mclk forces the mclk to the lowest level.
profile_peak sets all clocks (mclk, sclk, pcie) to the highest levels.


<a id="rst-pp-table"></a>

### pp_table


The amdgpu driver provides a sysfs API for uploading new powerplay
tables.  The file pp_table is used for this.  Reading the file
will dump the current power play table.  Writing to the file
will attempt to upload a new powerplay table and re-initialize
powerplay using that new table.


<a id="rst-pp-od-clk-voltage"></a>

### pp_od_clk_voltage


The amdgpu driver provides a sysfs API for adjusting the clocks and voltages
in each power level within a power state.  The pp_od_clk_voltage is used for
this.

Note that the actual memory controller clock rate are exposed, not
the effective memory clock of the DRAMs. To translate it, use the
following formula:

Clock conversion (Mhz):

HBM: effective_memory_clock = memory_controller_clock * 1

G5: effective_memory_clock = memory_controller_clock * 1

G6: effective_memory_clock = memory_controller_clock * 2

DRAM data rate (MT/s):

HBM: effective_memory_clock * 2 = data_rate

G5: effective_memory_clock * 4 = data_rate

G6: effective_memory_clock * 8 = data_rate

Bandwidth (MB/s):

data_rate * vram_bit_width / 8 = memory_bandwidth

Some examples:

G5 on RX460:

memory_controller_clock = 1750 Mhz

effective_memory_clock = 1750 Mhz * 1 = 1750 Mhz

data rate = 1750 * 4 = 7000 MT/s

memory_bandwidth = 7000 * 128 bits / 8 = 112000 MB/s

G6 on RX5700:

memory_controller_clock = 875 Mhz

effective_memory_clock = 875 Mhz * 2 = 1750 Mhz

data rate = 1750 * 8 = 14000 MT/s

memory_bandwidth = 14000 * 256 bits / 8 = 448000 MB/s

\< For Vega10 and previous ASICs >

Reading the file will display:

- a list of engine clock levels and voltages labeled OD_SCLK

- a list of memory clock levels and voltages labeled OD_MCLK

- a list of valid ranges for sclk, mclk, and voltage labeled OD_RANGE

To manually adjust these settings, first select manual using
power_dpm_force_performance_level. Enter a new value for each
level by writing a string that contains "s/m level clock voltage" to
the file.  E.g., "s 1 500 820" will update sclk level 1 to be 500 MHz
at 820 mV; "m 0 350 810" will update mclk level 0 to be 350 MHz at
810 mV.  When you have edited all of the states as needed, write
"c" (commit) to the file to commit your changes.  If you want to reset to the
default power levels, write "r" (reset) to the file to reset them.

\< For Vega20 and newer ASICs >

Reading the file will display:

- minimum and maximum engine clock labeled OD_SCLK

- minimum(not available for Vega20 and Navi1x) and maximum memory
  clock labeled OD_MCLK

- three \<frequency, voltage> points labeled OD_VDDC_CURVE.
  They can be used to calibrate the sclk voltage curve. This is
  available for Vega20 and NV1X.

- voltage offset(in mV) applied on target voltage calculation.
  This is available for Sienna Cichlid, Navy Flounder, Dimgrey
  Cavefish and some later SMU13 ASICs. For these ASICs, the target
  voltage calculation can be illustrated by "voltage = voltage
  calculated from v/f curve + overdrive vddgfx offset"

- a list of valid ranges for sclk, mclk, voltage curve points
  or voltage offset labeled OD_RANGE

\< For APUs >

Reading the file will display:

- minimum and maximum engine clock labeled OD_SCLK

- a list of valid ranges for sclk labeled OD_RANGE

\< For VanGogh >

Reading the file will display:

- minimum and maximum engine clock labeled OD_SCLK
- minimum and maximum core clocks labeled OD_CCLK

- a list of valid ranges for sclk and cclk labeled OD_RANGE

To manually adjust these settings:

- First select manual using power_dpm_force_performance_level

- For clock frequency setting, enter a new value by writing a
  string that contains "s/m index clock" to the file. The index
  should be 0 if to set minimum clock. And 1 if to set maximum
  clock. E.g., "s 0 500" will update minimum sclk to be 500 MHz.
  "m 1 800" will update maximum mclk to be 800Mhz. For core
  clocks on VanGogh, the string contains "p core index clock".
  E.g., "p 2 0 800" would set the minimum core clock on core
  2 to 800Mhz.

  For sclk voltage curve supported by Vega20 and NV1X, enter the new
  values by writing a string that contains "vc point clock voltage"
  to the file. The points are indexed by 0, 1 and 2. E.g., "vc 0 300
  600" will update point1 with clock set as 300Mhz and voltage as 600mV.
  "vc 2 1000 1000" will update point3 with clock set as 1000Mhz and
  voltage 1000mV.

  For voltage offset supported by Sienna Cichlid, Navy Flounder, Dimgrey
  Cavefish and some later SMU13 ASICs, enter the new value by writing a
  string that contains "vo offset". E.g., "vo -10" will update the extra
  voltage offset applied to the whole v/f curve line as -10mv.

- When you have edited all of the states as needed, write "c" (commit)
  to the file to commit your changes

- If you want to reset to the default power levels, write "r" (reset)
  to the file to reset them


<a id="rst-pp-dpm"></a>

### pp_dpm\_\*


The amdgpu driver provides a sysfs API for adjusting what power levels
are enabled for a given power state.  The files pp_dpm_sclk, pp_dpm_mclk,
pp_dpm_socclk, pp_dpm_fclk, pp_dpm_dcefclk and pp_dpm_pcie are used for
this.

pp_dpm_socclk and pp_dpm_dcefclk interfaces are only available for
Vega10 and later ASICs.
pp_dpm_fclk interface is only available for Vega20 and later ASICs.

Reading back the files will show you the available power levels within
the power state and the clock information for those levels. If deep sleep is
applied to a clock, the level will be denoted by a special level 'S:'
E.g.,

```text
S: 19Mhz *
0: 615Mhz
1: 800Mhz
2: 888Mhz
3: 1000Mhz
```

To manually adjust these states, first select manual using
power_dpm_force_performance_level.
Secondly, enter a new value for each level by inputing a string that
contains " echo xx xx xx > pp_dpm_sclk/mclk/pcie"
E.g.,

```bash
echo "4 5 6" > pp_dpm_sclk
```

will enable sclk levels 4, 5, and 6.

NOTE: change to the dcefclk max dpm level is not supported now


<a id="rst-pp-power-profile-mode"></a>

### pp_power_profile_mode


The amdgpu driver provides a sysfs API for adjusting the heuristics
related to switching between power levels in a power state.  The file
pp_power_profile_mode is used for this.

Reading this file outputs a list of all of the predefined power profiles
and the relevant heuristics settings for that profile.

To select a profile or create a custom profile, first select manual using
power_dpm_force_performance_level.  Writing the number of a predefined
profile to pp_power_profile_mode will enable those heuristics.  To
create a custom set of heuristics, write a string of numbers to the file
starting with the number of the custom profile along with a setting
for each heuristic parameter.  Due to differences across asic families
the heuristic parameters vary from family to family. Additionally,
you can apply the custom heuristics to different clock domains.  Each
clock domain is considered a distinct operation so if you modify the
gfxclk heuristics and then the memclk heuristics, the all of the
custom heuristics will be retained until you switch to another profile.


<a id="rst-pm-policy"></a>

### pm_policy


Certain SOCs can support different power policies to optimize application
performance. However, this policy is provided only at SOC level and not at a
per-process level. This is useful especially when entire SOC is utilized for
dedicated workload.

The amdgpu driver provides a sysfs API for selecting the policy. Presently,
only two types of policies are supported through this interface.

Pstate Policy Selection - This is to select different Pstate profiles which
decides clock/throttling preferences.

XGMI PLPD Policy Selection - When multiple devices are connected over XGMI,
this helps to select policy to be applied for per link power down.

The list of available policies and policy levels vary between SOCs. They can
be viewed under pm_policy node directory. If SOC doesn't support any policy,
this node won't be available. The different policies supported will be
available as separate nodes under pm_policy.

cat /sys/bus/pci/devices/.../pm_policy/\<policy_type>

Reading the policy file shows the different levels supported. The level which
is applied presently is denoted by * (asterisk). E.g.,

```console
cat /sys/bus/pci/devices/.../pm_policy/soc_pstate
0 : soc_pstate_default
1 : soc_pstate_0
2 : soc_pstate_1*
3 : soc_pstate_2

cat /sys/bus/pci/devices/.../pm_policy/xgmi_plpd
0 : plpd_disallow
1 : plpd_default
2 : plpd_optimized*
```

To apply a specific policy

"echo  \<level> > /sys/bus/pci/devices/.../pm_policy/\<policy_type>"

For the levels listed in the example above, to select "plpd_optimized" for
XGMI and "soc_pstate_2" for soc pstate policy -

```console
echo "2" > /sys/bus/pci/devices/.../pm_policy/xgmi_plpd
echo "3" > /sys/bus/pci/devices/.../pm_policy/soc_pstate
```


<a id="rst-busy-percent"></a>

### \*\_busy_percent


The amdgpu driver provides a sysfs API for reading how busy the GPU
is as a percentage.  The file gpu_busy_percent is used for this.
The SMU firmware computes a percentage of load based on the
aggregate activity level in the IP cores.



The amdgpu driver provides a sysfs API for reading how busy the VRAM
is as a percentage.  The file mem_busy_percent is used for this.
The SMU firmware computes a percentage of load based on the
aggregate activity level in the IP cores.


<a id="rst-gpu-metrics"></a>

### gpu_metrics


The amdgpu driver provides a sysfs API for retrieving current gpu
metrics data. The file gpu_metrics is used for this. Reading the
file will dump all the current gpu metrics data.

These data include temperature, frequency, engines utilization,
power consume, throttler status, fan speed and cpu core statistics(
available for APU only). That's it will give a snapshot of all sensors
at the same time.


<a id="rst-fan-curve"></a>

### fan_curve


The amdgpu driver provides a sysfs API for checking and adjusting the fan
control curve line.

Reading back the file shows you the current settings(temperature in Celsius
degree and fan speed in pwm) applied to every anchor point of the curve line
and their permitted ranges if changable.

Writing a desired string(with the format like "anchor_point_index temperature
fan_speed_in_pwm") to the file, change the settings for the specific anchor
point accordingly.

When you have finished the editing, write "c" (commit) to the file to commit
your changes.

If you want to reset to the default value, write "r" (reset) to the file to
reset them

There are two fan control modes supported: auto and manual. With auto mode,
PMFW handles the fan speed control(how fan speed reacts to ASIC temperature).
While with manual mode, users can set their own fan curve line as what
described here. Normally the ASIC is booted up with auto mode. Any
settings via this interface will switch the fan control to manual mode
implicitly.


<a id="rst-acoustic-limit-rpm-threshold"></a>

### acoustic_limit_rpm_threshold


The amdgpu driver provides a sysfs API for checking and adjusting the
acoustic limit in RPM for fan control.

Reading back the file shows you the current setting and the permitted
ranges if changable.

Writing an integer to the file, change the setting accordingly.

When you have finished the editing, write "c" (commit) to the file to commit
your changes.

If you want to reset to the default value, write "r" (reset) to the file to
reset them

This setting works under auto fan control mode only. It adjusts the PMFW's
behavior about the maximum speed in RPM the fan can spin. Setting via this
interface will switch the fan control to auto mode implicitly.


<a id="rst-acoustic-target-rpm-threshold"></a>

### acoustic_target_rpm_threshold


The amdgpu driver provides a sysfs API for checking and adjusting the
acoustic target in RPM for fan control.

Reading back the file shows you the current setting and the permitted
ranges if changable.

Writing an integer to the file, change the setting accordingly.

When you have finished the editing, write "c" (commit) to the file to commit
your changes.

If you want to reset to the default value, write "r" (reset) to the file to
reset them

This setting works under auto fan control mode only. It can co-exist with
other settings which can work also under auto mode. It adjusts the PMFW's
behavior about the maximum speed in RPM the fan can spin when ASIC
temperature is not greater than target temperature. Setting via this
interface will switch the fan control to auto mode implicitly.


<a id="rst-fan-target-temperature"></a>

### fan_target_temperature


The amdgpu driver provides a sysfs API for checking and adjusting the
target tempeature in Celsius degree for fan control.

Reading back the file shows you the current setting and the permitted
ranges if changable.

Writing an integer to the file, change the setting accordingly.

When you have finished the editing, write "c" (commit) to the file to commit
your changes.

If you want to reset to the default value, write "r" (reset) to the file to
reset them

This setting works under auto fan control mode only. It can co-exist with
other settings which can work also under auto mode. Paring with the
acoustic_target_rpm_threshold setting, they define the maximum speed in
RPM the fan can spin when ASIC temperature is not greater than target
temperature. Setting via this interface will switch the fan control to
auto mode implicitly.


<a id="rst-fan-minimum-pwm"></a>

### fan_minimum_pwm


The amdgpu driver provides a sysfs API for checking and adjusting the
minimum fan speed in PWM.

Reading back the file shows you the current setting and the permitted
ranges if changable.

Writing an integer to the file, change the setting accordingly.

When you have finished the editing, write "c" (commit) to the file to commit
your changes.

If you want to reset to the default value, write "r" (reset) to the file to
reset them

This setting works under auto fan control mode only. It can co-exist with
other settings which can work also under auto mode. It adjusts the PMFW's
behavior about the minimum fan speed in PWM the fan should spin. Setting
via this interface will switch the fan control to auto mode implicitly.


<a id="rst-fan-zero-rpm-enable"></a>

### fan_zero_rpm_enable


The amdgpu driver provides a sysfs API for checking and adjusting the
zero RPM feature.

Reading back the file shows you the current setting and the permitted
ranges if changable.

Writing an integer to the file, change the setting accordingly.

When you have finished the editing, write "c" (commit) to the file to commit
your changes.

If you want to reset to the default value, write "r" (reset) to the file to
reset them.


<a id="rst-fan-zero-rpm-stop-temperature"></a>

### fan_zero_rpm_stop_temperature


The amdgpu driver provides a sysfs API for checking and adjusting the
zero RPM stop temperature feature.

Reading back the file shows you the current setting and the permitted
ranges if changable.

Writing an integer to the file, change the setting accordingly.

When you have finished the editing, write "c" (commit) to the file to commit
your changes.

If you want to reset to the default value, write "r" (reset) to the file to
reset them.

This setting works only if the Zero RPM setting is enabled. It adjusts the
temperature below which the fan can stop.


<a id="rst-gfxoff"></a>

## GFXOFF

GFXOFF is a feature found in most recent GPUs that saves power at runtime. The card's RLC (RunList Controller) firmware powers off the gfx engine dynamically when there is no workload on gfx or compute pipes. GFXOFF is on by default on supported GPUs.

Userspace can interact with GFXOFF through a debugfs interface (all values in `uint32_t`, unless otherwise noted):

<a id="rst-amdgpu-gfxoff"></a>

### `amdgpu_gfxoff`

Use it to enable/disable GFXOFF, and to check if it's current enabled/disabled:



```text
$ xxd -l1 -p /sys/kernel/debug/dri/0/amdgpu_gfxoff
01
```

- Write 0 to disable it, and 1 to enable it.

- Read 0 means it's disabled, 1 it's enabled.

If it's enabled, that means that the GPU is free to enter into GFXOFF mode as needed. Disabled means that it will never enter GFXOFF mode.

<a id="rst-amdgpu-gfxoff-status"></a>

### `amdgpu_gfxoff_status`

Read it to check current GFXOFF's status of a GPU:



```text
$ xxd -l1 -p /sys/kernel/debug/dri/0/amdgpu_gfxoff_status
02
```

- 0: GPU is in GFXOFF state, the gfx engine is powered down.

- 1: Transition out of GFXOFF state

- 2: Not in GFXOFF state

- 3: Transition into GFXOFF state

If GFXOFF is enabled, the value will be transitioning around \[0, 3\], always getting into 0 when possible. When it's disabled, it's always at 2. Returns `-EINVAL` if it's not supported.

<a id="rst-amdgpu-gfxoff-count"></a>

### `amdgpu_gfxoff_count`

Read it to get the total GFXOFF entry count at the time of query since system power-up. The value is an `uint64_t` type, however, due to firmware limitations, it can currently overflow as an `uint32_t`. *Only supported in vangogh*

<a id="rst-amdgpu-gfxoff-residency"></a>

### `amdgpu_gfxoff_residency`

Write 1 to amdgpu_gfxoff_residency to start logging, and 0 to stop. Read it to get average GFXOFF residency % multiplied by 100 during the last logging interval. E.g. a value of 7854 means 78.54% of the time in the last logging interval the GPU was in GFXOFF mode. *Only supported in vangogh*

---

# User Mode Queues

_Peios Kernel / Hardware and drivers / Graphics / amdgpu_

> Similar to the KFD, GPU engine queues move into userspace. The idea is to let user processes manage their submissions to the GPU engines directly, bypassing IOCTL calls to the driver to submit work. This reduces overhead and also allows…

<a id="rst-user-mode-queues"></a>
<a id="rst-amdgpu-userq"></a>

<a id="rst-introduction"></a>

## Introduction

Similar to the KFD, GPU engine queues move into userspace.  The idea is to let user processes manage their submissions to the GPU engines directly, bypassing IOCTL calls to the driver to submit work.  This reduces overhead and also allows the GPU to submit work to itself.  Applications can set up work graphs of jobs across multiple GPU engines without needing trips through the CPU.

UMDs directly interface with firmware via per application shared memory areas. The main vehicle for this is queue.  A queue is a ring buffer with a read pointer (rptr) and a write pointer (wptr).  The UMD writes IP specific packets into the queue and the firmware processes those packets, kicking off work on the GPU engines.  The CPU in the application (or another queue or device) updates the wptr to tell the firmware how far into the ring buffer to process packets and the rtpr provides feedback to the UMD on how far the firmware has progressed in executing those packets.  When the wptr and the rptr are equal, the queue is idle.

<a id="rst-theory-of-operation"></a>

## Theory of Operation

The various engines on modern AMD GPUs support multiple queues per engine with a scheduling firmware which handles dynamically scheduling user queues on the available hardware queue slots.  When the number of user queues outnumbers the available hardware queue slots, the scheduling firmware dynamically maps and unmaps queues based on priority and time quanta.  The state of each user queue is managed in the kernel driver in an MQD (Memory Queue Descriptor).  This is a buffer in GPU accessible memory that stores the state of a user queue.  The scheduling firmware uses the MQD to load the queue state into an HQD (Hardware Queue Descriptor) when a user queue is mapped.  Each user queue requires a number of additional buffers which represent the ring buffer and any metadata needed by the engine for runtime operation.  On most engines this consists of the ring buffer itself, a rptr buffer (where the firmware will shadow the rptr to userspace), a wptr buffer (where the application will write the wptr for the firmware to fetch it), and a doorbell.  A doorbell is a piece of one of the device's MMIO BARs which can be mapped to specific user queues.  When the application writes to the doorbell, it will signal the firmware to take some action. Writing to the doorbell wakes the firmware and causes it to fetch the wptr and start processing the packets in the queue. Each 4K page of the doorbell BAR supports specific offset ranges for specific engines.  The doorbell of a queue must be mapped into the aperture aligned to the IP used by the queue (e.g., GFX, VCN, SDMA, etc.).  These doorbell apertures are set up via NBIO registers.  Doorbells are 32 bit or 64 bit (depending on the engine) chunks of the doorbell BAR.  A 4K doorbell page provides 512 64-bit doorbells for up to 512 user queues.  A subset of each page is reserved for each IP type supported on the device.  The user can query the doorbell ranges for each IP via the INFO IOCTL.  See the IOCTL Interfaces section for more information.

When an application wants to create a user queue, it allocates the necessary buffers for the queue (ring buffer, wptr and rptr, context save areas, etc.). These can be separate buffers or all part of one larger buffer.  The application would map the buffer(s) into its GPUVM and use the GPU virtual addresses of for the areas of memory they want to use for the user queue.  They would also allocate a doorbell page for the doorbells used by the user queues.  The application would then populate the MQD in the USERQ IOCTL structure with the GPU virtual addresses and doorbell index they want to use.  The user can also specify the attributes for the user queue (priority, whether the queue is secure for protected content, etc.).  The application would then call the USERQ CREATE IOCTL to create the queue using the specified MQD details in the IOCTL. The kernel driver then validates the MQD provided by the application and translates the MQD into the engine specific MQD format for the IP.  The IP specific MQD would be allocated and the queue would be added to the run list maintained by the scheduling firmware.  Once the queue has been created, the application can write packets directly into the queue, update the wptr, and write to the doorbell offset to kick off work in the user queue.

When the application is done with the user queue, it would call the USERQ FREE IOCTL to destroy it.  The kernel driver would preempt the queue and remove it from the scheduling firmware's run list.  Then the IP specific MQD would be freed and the user queue state would be cleaned up.

Some engines may require the aggregated doorbell too if the engine does not support doorbells from unmapped queues.  The aggregated doorbell is a special page of doorbell space which wakes the scheduler.  In cases where the engine may be oversubscribed, some queues may not be mapped.  If the doorbell is rung when the queue is not mapped, the engine firmware may miss the request.  Some scheduling firmware may work around this by polling wptr shadows when the hardware is oversubscribed, other engines may support doorbell updates from unmapped queues.  In the event that one of these options is not available, the kernel driver will map a page of aggregated doorbell space into each GPUVM space.  The UMD will then update the doorbell and wptr as normal and then write to the aggregated doorbell as well.

<a id="rst-special-packets"></a>

### Special Packets

In order to support legacy implicit synchronization, as well as mixed user and kernel queues, we need a synchronization mechanism that is secure.  Because kernel queues or memory management tasks depend on kernel fences, we need a way for user queues to update memory that the kernel can use for a fence, that can't be messed with by a bad actor.  To support this, we've added a protected fence packet.  This packet works by writing a monotonically increasing value to a memory location that only privileged clients have write access to. User queues only have read access.  When this packet is executed, the memory location is updated and other queues (kernel or user) can see the results.  The user application would submit this packet in their command stream.  The actual packet format varies from IP to IP (GFX/Compute, SDMA, VCN, etc.), but the behavior is the same.  The packet submission is handled in userspace.  The kernel driver sets up the privileged memory used for each user queue when it sets the queues up when the application creates them.

<a id="rst-memory-management"></a>

## Memory Management

It is assumed that all buffers mapped into the GPUVM space for the process are valid when engines on the GPU are running.  The kernel driver will only allow user queues to run when all buffers are mapped.  If there is a memory event that requires buffer migration, the kernel driver will preempt the user queues, migrate buffers to where they need to be, update the GPUVM page tables and invaldidate the TLB, and then resume the user queues.

<a id="rst-interaction-with-kernel-queues"></a>

## Interaction with Kernel Queues

Depending on the IP and the scheduling firmware, you can enable kernel queues and user queues at the same time, however, you are limited by the HQD slots. Kernel queues are always mapped so any work that goes into kernel queues will take priority.  This limits the available HQD slots for user queues.

Not all IPs will support user queues on all GPUs.  As such, UMDs will need to support both user queues and kernel queues depending on the IP.  For example, a GPU may support user queues for GFX, compute, and SDMA, but not for VCN, JPEG, and VPE.  UMDs need to support both.  The kernel driver provides a way to determine if user queues and kernel queues are supported on a per IP basis. UMDs can query this information via the INFO IOCTL and determine whether to use kernel queues or user queues for each IP.

<a id="rst-queue-resets"></a>

## Queue Resets

For most engines, queues can be reset individually.  GFX, compute, and SDMA queues can be reset individually.  When a hung queue is detected, it can be reset either via the scheduling firmware or MMIO.  Since there are no kernel fences for most user queues, they will usually only be detected when some other event happens; e.g., a memory event which requires migration of buffers.  When the queues are preempted, if the queue is hung, the preemption will fail. Driver will then look up the queues that failed to preempt and reset them and record which queues are hung.

On the UMD side, we will add a USERQ QUERY_STATUS IOCTL to query the queue status.  UMD will provide the queue id in the IOCTL and the kernel driver will check if it has already recorded the queue as hung (e.g., due to failed peemption) and report back the status.

<a id="rst-ioctl-interfaces"></a>

## IOCTL Interfaces

GPU virtual addresses used for queues and related data (rptrs, wptrs, context save areas, etc.) should be validated by the kernel mode driver to prevent the user from specifying invalid GPU virtual addresses.  If the user provides invalid GPU virtual addresses or doorbell indicies, the IOCTL should return an error message.  These buffers should also be tracked in the kernel driver so that if the user attempts to unmap the buffer(s) from the GPUVM, the umap call would return an error.

<a id="rst-info"></a>

### INFO

There are several new INFO queries related to user queues in order to query the size of user queue meta data needed for a user queue (e.g., context save areas or shadow buffers), whether kernel or user queues or both are supported for each IP type, and the offsets for each IP type in each doorbell page.

<a id="rst-userq"></a>

### USERQ

The USERQ IOCTL is used for creating, freeing, and querying the status of user queues.  It supports 3 opcodes:

1. CREATE - Create a user queue.  The application provides an MQD-like structure that defines the type of queue and associated metadata and flags for that queue type.  Returns the queue id.

2. FREE - Free a user queue.

3. QUERY_STATUS - Query that status of a queue.  Used to check if the queue is healthy or not.  E.g., if the queue has been reset. (WIP)

<a id="rst-userq-signal"></a>

### USERQ_SIGNAL

The USERQ_SIGNAL IOCTL is used to provide a list of sync objects to be signaled.

<a id="rst-userq-wait"></a>

### USERQ_WAIT

The USERQ_WAIT IOCTL is used to provide a list of sync object to be waited on.

<a id="rst-kernel-and-user-queues"></a>

## Kernel and User Queues

In order to properly validate and test performance, we have a driver option to select what type of queues are enabled (kernel queues, user queues or both). The user_queue driver parameter allows you to enable kernel queues only (0), user queues and kernel queues (1), and user queues only (2).  Enabling user queues only will free up static queue assignments that would otherwise be used by kernel queues for use by the scheduling firmware.  Some kernel queues are required for kernel driver operation and they will always be created.  When the kernel queues are not enabled, they are not registered with the drm scheduler and the CS IOCTL will reject any incoming command submissions which target those queue types.  Kernel queues only mirrors the behavior on all existing GPUs. Enabling both queues allows for backwards compatibility with old userspace while still supporting user queues.

---

# AMDGPU XGMI Support

_Peios Kernel / Hardware and drivers / Graphics / amdgpu_

> Reference for AMDGPU XGMI Support.

<a id="rst-amdgpu-xgmi-support"></a>


**AMDGPU XGMI Support**

XGMI is a high speed interconnect that joins multiple GPU cards
into a homogeneous memory space that is organized by a collective
hive ID and individual node IDs, both of which are 64-bit numbers.

The file xgmi_device_id contains the unique per GPU device ID and
is stored in the /sys/class/drm/card${cardno}/device/ directory.

Inside the device directory a sub-directory 'xgmi_hive_info' is
created which contains the hive ID and the list of nodes.

- The hive ID is stored in:
  /sys/class/drm/card${cardno}/device/xgmi_hive_info/xgmi_hive_id

- The node information is stored in numbered directories:
  /sys/class/drm/card${cardno}/device/xgmi_hive_info/node${nodeno}/xgmi_device_id

Each device has their own xgmi_hive_info direction with a mirror
set of node sub-directories.

The XGMI memory space is built by contiguously adding the power of
two padded VRAM space from each node to each other.

---

# drm/amd/display - Display Core (DC)

_Peios Kernel / Hardware and drivers / Graphics / amdgpu / display_

> AMD display engine is partially shared with other operating systems; for this reason, our Display Core Driver is divided into two pieces:

<a id="rst-drm-amd-display-display-core-dc"></a>
<a id="rst-amdgpu-display-core"></a>

AMD display engine is partially shared with other operating systems; for this reason, our Display Core Driver is divided into two pieces:

1. **Display Core (DC)** contains the OS-agnostic components. Things like hardware programming and resource management are handled here.

2. **Display Manager (DM)** contains the OS-dependent components. Hooks to the amdgpu base driver and DRM are implemented here. For example, you can check display/amdgpu_dm/ folder.

<a id="rst-dc-code-validation"></a>

## DC Code validation

Maintaining the same code base across multiple OSes requires a lot of synchronization effort between repositories and exhaustive validation. In the DC case, we maintain a tree to centralize code from different parts. The shared repository has integration tests with our Internal Linux CI farm, and we run a comprehensive set of IGT tests in various AMD GPUs/APUs (mostly recent dGPUs and APUs). Our CI also checks ARM64/32, PPC64/32, and x86_64/32 compilation with DCN enabled and disabled.

When we upstream a new feature or some patches, we pack them in a patchset with the prefix **DC Patches for &lt;DATE&gt;**, which is created based on the latest [amd-staging-drm-next](<https://gitlab.freedesktop.org/agd5f/linux>)<a id="rst-amd-staging-drm-next"></a>. All of those patches are under a DC version tested as follows:

- Ensure that every patch compiles and the entire series pass our set of IGT test in different hardware.

- Prepare a branch with those patches for our validation team. If there is an error, a developer will debug as fast as possible; usually, a simple bisect in the series is enough to point to a bad change, and two possible actions emerge: fix the issue or drop the patch. If it is not an easy fix, the bad patch is dropped.

- Finally, developers wait a few days for community feedback before we merge the series.

It is good to stress that the test phase is something that we take extremely seriously, and we never merge anything that fails our validation. Follows an overview of our test set:

1. - **Manual test**

     - Multiple Hotplugs with DP and HDMI.

     - Stress test with multiple display configuration changes via the user interface.

     - Validate VRR behaviour.

     - Check PSR.

     - Validate MPO when playing video.

     - Test more than two displays connected at the same time.

     - Check suspend/resume.

     - Validate FPO.

     - Check MST.

2. - **Automated test**

     - IGT tests in a farm with GPUs and APUs that support DCN and DCE.

     - Compilation validation with the latest GCC and Clang from LTS distro.

     - Cross-compilation for PowerPC 64/32, ARM 64/32, and x86 32.

In terms of test setup for CI and manual tests, we usually use:

1. The latest Ubuntu LTS.

2. In terms of userspace, we only use fully updated open-source components provided by the distribution official package manager.

3. Regarding IGT, we use the latest code from the upstream.

4. Most of the manual tests are conducted in the GNome but we also use KDE.

Notice that someone from our test team will always reply to the cover letter with the test report.

<a id="rst-dc-information"></a>

## DC Information

The display pipe is responsible for "scanning out" a rendered frame from the GPU memory (also called VRAM, FrameBuffer, etc.) to a display. In other words, it would:

1. Read frame information from memory;

2. Perform required transformation;

3. Send pixel data to sink devices.

If you want to learn more about our driver details, take a look at the below table of content:

- [AMDgpu Display Manager](</kernel/hardware/gpu/amdgpu-display/display-manager.md>)
- [Display Core Next (DCN)](</kernel/hardware/gpu/amdgpu-display/dcn-overview.md>)
- [DCN Blocks](</kernel/hardware/gpu/amdgpu-display/dcn-blocks.md>)
- [DC Programming Model](</kernel/hardware/gpu/amdgpu-display/programming-model-dcn.md>)
- [Multiplane Overlay (MPO)](</kernel/hardware/gpu/amdgpu-display/mpo-overview.md>)
- [dc-debug](<https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/Documentation/gpu/amdgpu/display/dc-debug.rst?id=9021cc14f7d98b4a1d2c932f52c5343d4d0f6b92>)
- [AMDGPU - Display Contributions](</kernel/hardware/gpu/amdgpu-display/display-contributing.md>)
- [dc-glossary](<https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/Documentation/gpu/amdgpu/display/dc-glossary.rst?id=9021cc14f7d98b4a1d2c932f52c5343d4d0f6b92>)

---

# Display Core Debug tools

_Peios Kernel / Hardware and drivers / Graphics / amdgpu / display_

> In this section, you will find helpful information on debugging the amdgpu driver from the display perspective. This page introduces debug mechanisms and procedures to help you identify if some issues are related to display code.

<a id="rst-display-core-debug-tools"></a>

In this section, you will find helpful information on debugging the amdgpu driver from the display perspective. This page introduces debug mechanisms and procedures to help you identify if some issues are related to display code.

<a id="rst-narrow-down-display-issues"></a>

## Narrow down display issues

Since the display is the driver's visual component, it is common to see users reporting issues as a display when another component causes the problem. This section equips users to determine if a specific issue was caused by the display component or another part of the driver.

<a id="rst-dc-dmesg-important-messages"></a>

### DC dmesg important messages

The dmesg log is the first source of information to be checked, and amdgpu takes advantage of this feature by logging some valuable information. When looking for the issues associated with amdgpu, remember that each component of the driver (e.g., smu, PSP, dm, etc.) is loaded one by one, and this information can be found in the dmesg log. In this sense, look for the part of the log that looks like the below log snippet:



```text
[    4.254295] [drm] initializing kernel modesetting (IP DISCOVERY 0x1002:0x744C 0x1002:0x0E3B 0xC8).
[    4.254718] [drm] register mmio base: 0xFCB00000
[    4.254918] [drm] register mmio size: 1048576
[    4.260095] [drm] add ip block number 0 <soc21_common>
[    4.260318] [drm] add ip block number 1 <gmc_v11_0>
[    4.260510] [drm] add ip block number 2 <ih_v6_0>
[    4.260696] [drm] add ip block number 3 <psp>
[    4.260878] [drm] add ip block number 4 <smu>
[    4.261057] [drm] add ip block number 5 <dm>
[    4.261231] [drm] add ip block number 6 <gfx_v11_0>
[    4.261402] [drm] add ip block number 7 <sdma_v6_0>
[    4.261568] [drm] add ip block number 8 <vcn_v4_0>
[    4.261729] [drm] add ip block number 9 <jpeg_v4_0>
[    4.261887] [drm] add ip block number 10 <mes_v11_0>
```

From the above example, you can see the line that reports that `<dm>`, (<strong>Display Manager</strong>), was loaded, which means that display can be part of the issue. If you do not see that line, something else might have failed before amdgpu loads the display component, indicating that we don't have a display issue.

After you identified that the DM was loaded correctly, you can check for the display version of the hardware in use, which can be retrieved from the dmesg log with the command:



```text
dmesg | grep -i 'display core'
```

This command shows a message that looks like this:



```text
[    4.655828] [drm] Display Core v3.2.285 initialized on DCN 3.2
```

This message has two key pieces of information:

- <strong>The DC version (e.g., v3.2.285)</strong>: Display developers release a new DC version every week, and this information can be advantageous in a situation where a user/developer must find a good point versus a bad point based on a tested version of the display code. Remember from page [Display Core](</kernel/hardware/gpu/amdgpu-display/index.md#rst-amdgpu-display-core>), that every week the new patches for display are heavily tested with IGT and manual tests.

- <strong>The DCN version (e.g., DCN 3.2)</strong>: The DCN block is associated with the hardware generation, and the DCN version conveys the hardware generation that the driver is currently running. This information helps to narrow down the code debug area since each DCN version has its files in the DC folder per DCN component (from the example, the developer might want to focus on files/folders/functions/structs with the dcn32 label might be executed). However, keep in mind that DC reuses code across different DCN versions; for example, it is expected to have some callbacks set in one DCN that are the same as those from another DCN. In summary, use the DCN version just as a guide.

From the dmesg file, it is also possible to get the ATOM bios code by using:



```text
dmesg  | grep -i 'ATOM BIOS'
```

Which generates an output that looks like this:



```text
[    4.274534] amdgpu: ATOM BIOS: 113-D7020100-102
```

This type of information is useful to be reported.

<a id="rst-avoid-loading-display-core"></a>

### Avoid loading display core

Sometimes, it might be hard to figure out which part of the driver is causing the issue; if you suspect that the display is not part of the problem and your bug scenario is simple (e.g., some desktop configuration) you can try to remove the display component from the equation. First, you need to identify `dm` ID from the dmesg log; for example, search for the following log:



```text
[    4.254295] [drm] initializing kernel modesetting (IP DISCOVERY 0x1002:0x744C 0x1002:0x0E3B 0xC8).
[..]
[    4.260095] [drm] add ip block number 0 <soc21_common>
[    4.260318] [drm] add ip block number 1 <gmc_v11_0>
[..]
[    4.261057] [drm] add ip block number 5 <dm>
```

Notice from the above example that the `dm` id is 5 for this specific hardware. Next, you need to run the following binary operation to identify the IP block mask:



```text
0xffffffff & ~(1 << [DM ID])
```

From our example the IP mask is:



```text
0xffffffff & ~(1 << 5) = 0xffffffdf
```

Finally, to disable DC, you just need to set the below parameter in your bootloader:



```text
amdgpu.ip_block_mask = 0xffffffdf
```

If you can boot your system with the DC disabled and still see the issue, it means you can rule DC out of the equation. However, if the bug disappears, you still need to consider the DC part of the problem and keep narrowing down the issue. In some scenarios, disabling DC is impossible since it might be necessary to use the display component to reproduce the issue (e.g., play a game).

<strong>Note: This will probably lead to the absence of a display output.</strong>

<a id="rst-display-flickering"></a>

### Display flickering

Display flickering might have multiple causes; one is the lack of proper power to the GPU or problems in the DPM switches. A good first generic verification is to set the GPU to use high voltage:



```text
bash -c "echo high > /sys/class/drm/card0/device/power_dpm_force_performance_level"
```

The above command sets the GPU/APU to use the maximum power allowed which disables DPM switches. If forcing DPM levels high does not fix the issue, it is less likely that the issue is related to power management. If the issue disappears, there is a good chance that other components might be involved, and the display should not be ignored since this could be a DPM issues. From the display side, if the power increase fixes the issue, it is worth debugging the clock configuration and the pipe split police used in the specific configuration.

<a id="rst-display-artifacts"></a>

### Display artifacts

Users may see some screen artifacts that can be categorized into two different types: localized artifacts and general artifacts. The localized artifacts happen in some specific areas, such as around the UI window corners; if you see this type of issue, there is a considerable chance that you have a userspace problem, likely Mesa or similar. The general artifacts usually happen on the entire screen. They might be caused by a misconfiguration at the driver level of the display parameters, but the userspace might also cause this issue. One way to identify the source of the problem is to take a screenshot or make a desktop video capture when the problem happens; after checking the screenshot/video recording, if you don't see any of the artifacts, it means that the issue is likely on the driver side. If you can still see the problem in the data collected, it is an issue that probably happened during rendering, and the display code just got the framebuffer already corrupted.

<a id="rst-disabling-enabling-specific-features"></a>

## Disabling/Enabling specific features

DC has a struct named `dc_debug_options`, which is statically initialized by all DCE/DCN components based on the specific hardware characteristic. This structure usually facilitates the bring-up phase since developers can start with many disabled features and enable them individually. This is also an important debug feature since users can change it when debugging specific issues.

For example, dGPU users sometimes see a problem where a horizontal fillet of flickering happens in some specific part of the screen. This could be an indication of Sub-Viewport issues; after the users identified the target DCN, they can set the `force_disable_subvp` field to true in the statically initialized version of `dc_debug_options` to see if the issue gets fixed. Along the same lines, users/developers can also try to turn off `fams2_config` and `enable_single_display_2to1_odm_policy`. In summary, the `dc_debug_options` is an interesting form for identifying the problem.

<a id="rst-dc-visual-confirmation"></a>

## DC Visual Confirmation

Display core provides a feature named visual confirmation, which is a set of bars added at the scanout time by the driver to convey some specific information. In general, you can enable this debug option by using:



```text
echo <N> > /sys/kernel/debug/dri/0/amdgpu_dm_visual_confirm
```

Where `N` is an integer number for some specific scenarios that the developer wants to enable, you will see some of these debug cases in the following subsection.

<a id="rst-multiple-planes-debug"></a>

### Multiple Planes Debug

If you want to enable or debug multiple planes in a specific user-space application, you can leverage a debug feature named visual confirm. For enabling it, you will need:



```text
echo 1 > /sys/kernel/debug/dri/0/amdgpu_dm_visual_confirm
```

You need to reload your GUI to see the visual confirmation. When the plane configuration changes or a full update occurs there will be a colored bar at the bottom of each hardware plane being drawn on the screen.

- The color indicates the format - For example, red is AR24 and green is NV12

- The height of the bar indicates the index of the plane

- Pipe split can be observed if there are two bars with a difference in height covering the same plane

Consider the video playback case in which a video is played in a specific plane, and the desktop is drawn in another plane. The video plane should feature one or two green bars at the bottom of the video depending on pipe split configuration.

- There should <strong>not</strong> be any visual corruption

- There should <strong>not</strong> be any underflow or screen flashes

- There should <strong>not</strong> be any black screens

- There should <strong>not</strong> be any cursor corruption

- Multiple plane <strong>may</strong> be briefly disabled during window transitions or resizing but should come back after the action has finished

<a id="rst-pipe-split-debug"></a>

### Pipe Split Debug

Sometimes we need to debug if DCN is splitting pipes correctly, and visual confirmation is also handy for this case. Similar to the MPO case, you can use the below command to enable visual confirmation:



```text
echo 1 > /sys/kernel/debug/dri/0/amdgpu_dm_visual_confirm
```

In this case, if you have a pipe split, you will see one small red bar at the bottom of the display covering the entire display width and another bar covering the second pipe. In other words, you will see a bit high bar in the second pipe.

<a id="rst-dtn-debug"></a>

## DTN Debug

DC (DCN) provides an extensive log that dumps multiple details from our hardware configuration. Via debugfs, you can capture those status values by using Display Test Next (DTN) log, which can be captured via debugfs by using:



```text
cat /sys/kernel/debug/dri/0/amdgpu_dm_dtn_log
```

Since this log is updated accordingly with DCN status, you can also follow the change in real-time by using something like:



```text
sudo watch -d cat /sys/kernel/debug/dri/0/amdgpu_dm_dtn_log
```

When reporting a bug related to DC, consider attaching this log before and after you reproduce the bug.

<a id="rst-collect-firmware-information"></a>

## Collect Firmware information

When reporting issues, it is important to have the firmware information since it can be helpful for debugging purposes. To get all the firmware information, use the command:



```text
cat /sys/kernel/debug/dri/0/amdgpu_firmware_info
```

From the display perspective, pay attention to the firmware of the DMCU and DMCUB.

<a id="rst-dmub-firmware-debug"></a>

## DMUB Firmware Debug

Sometimes, dmesg logs aren't enough. This is especially true if a feature is implemented primarily in DMUB firmware. In such cases, all we see in dmesg when an issue arises is some generic timeout error. So, to get more relevant information, we can trace DMUB commands by enabling the relevant bits in `amdgpu_dm_dmub_trace_mask`.

Currently, we support the tracing of the following groups:

<a id="rst-trace-groups"></a>

### Trace Groups



| Name | Mask Value |
|---|---|
| INFO | 0x1 |
| IRQ SVC | 0x2 |
| VBIOS | 0x4 |
| REGISTER | 0x8 |
| PHY DBG | 0x10 |
| PSR | 0x20 |
| AUX | 0x40 |
| SMU | 0x80 |
| MALL | 0x100 |
| ABM | 0x200 |
| ALPM | 0x400 |
| TIMER | 0x800 |
| HW LOCK MGR | 0x1000 |
| INBOX1 | 0x2000 |
| PHY SEQ | 0x4000 |
| PSR STATE | 0x8000 |
| ZSTATE | 0x10000 |
| TRANSMITTER CTL | 0x20000 |
| PANEL CNTL | 0x40000 |
| FAMS | 0x80000 |
| DPIA | 0x100000 |
| SUBVP | 0x200000 |
| INBOX0 | 0x400000 |
| SDP | 0x4000000 |
| REPLAY | 0x8000000 |
| REPLAY RESIDENCY | 0x20000000 |
| CURSOR INFO | 0x80000000 |
| IPS | 0x100000000 |


<strong>Note: Not all ASICs support all of the listed trace groups</strong>

So, to enable just PSR tracing you can use the following command:



```text
# echo 0x8020 > /sys/kernel/debug/dri/0/amdgpu_dm_dmub_trace_mask
```

Then, you need to enable logging trace events to the buffer, which you can do using the following:



```text
# echo 1 > /sys/kernel/debug/dri/0/amdgpu_dm_dmcub_trace_event_en
```

Lastly, after you are able to reproduce the issue you are trying to debug, you can disable tracing and read the trace log by using the following:



```text
# echo 0 > /sys/kernel/debug/dri/0/amdgpu_dm_dmcub_trace_event_en
# cat /sys/kernel/debug/dri/0/amdgpu_dm_dmub_tracebuffer
```

So, when reporting bugs related to features such as PSR and ABM, consider enabling the relevant bits in the mask before reproducing the issue and attach the log that you obtain from the trace buffer in any bug reports that you create.

---

# DC Glossary

_Peios Kernel / Hardware and drivers / Graphics / amdgpu / display_

> On this page, we try to keep track of acronyms related to the display component. If you do not find what you are looking for, look at the 'Documentation/gpu/amdgpu/amdgpu-glossary.rst'; if you cannot find it anywhere, consider asking on…

<a id="rst-dc-glossary"></a>

On this page, we try to keep track of acronyms related to the display component. If you do not find what you are looking for, look at the '[Documentation/gpu/amdgpu/amdgpu-glossary.rst](/kernel/hardware/gpu/amdgpu/amdgpu-glossary.md)'; if you cannot find it anywhere, consider asking on the amd-gfx mailing list and update this page.



- **<a id="rst-term-abm"></a>ABM**

  Adaptive Backlight Modulation

- **<a id="rst-term-apu"></a>APU**

  Accelerated Processing Unit

- **<a id="rst-term-asic"></a>ASIC**

  Application-Specific Integrated Circuit

- **<a id="rst-term-assr"></a>ASSR**

  Alternate Scrambler Seed Reset

- **<a id="rst-term-az"></a>AZ**

  Azalia (HD audio DMA engine)

- **<a id="rst-term-bpc"></a>BPC**

  Bits Per Colour/Component

- **<a id="rst-term-bpp"></a>BPP**

  Bits Per Pixel

- **<a id="rst-term-clocks"></a>Clocks**

  - PCLK: Pixel Clock

  - SYMCLK: Symbol Clock

  - SOCCLK: GPU Engine Clock

  - DISPCLK: Display Clock

  - DPPCLK: DPP Clock

  - DCFCLK: Display Controller Fabric Clock

  - REFCLK: Real Time Reference Clock

  - PPLL: Pixel PLL

  - FCLK: Fabric Clock

  - MCLK: Memory Clock

- **<a id="rst-term-crc"></a>CRC**

  Cyclic Redundancy Check

- **<a id="rst-term-crtc"></a>CRTC**

  Cathode Ray Tube Controller - commonly called "Controller" - Generates raw stream of pixels, clocked at pixel clock

- **<a id="rst-term-cvt"></a>CVT**

  Coordinated Video Timings

- **<a id="rst-term-dal"></a>DAL**

  Display Abstraction layer

- **<a id="rst-term-dc-software"></a>DC (Software)**

  Display Core

- **<a id="rst-term-dc-hardware"></a>DC (Hardware)**

  Display Controller

- **<a id="rst-term-dcc"></a>DCC**

  Delta Colour Compression

- **<a id="rst-term-dce"></a>DCE**

  Display Controller Engine

- **<a id="rst-term-dchub"></a>DCHUB**

  Display Controller HUB

- **<a id="rst-term-arb"></a>ARB**

  Arbiter

- **<a id="rst-term-vtg"></a>VTG**

  Vertical Timing Generator

- **<a id="rst-term-dcn"></a>DCN**

  Display Core Next

- **<a id="rst-term-dccg"></a>DCCG**

  Display Clock Generator block

- **<a id="rst-term-ddc"></a>DDC**

  Display Data Channel

- **<a id="rst-term-dio"></a>DIO**

  Display IO

- **<a id="rst-term-dpp"></a>DPP**

  Display Pipes and Planes

- **<a id="rst-term-dsc"></a>DSC**

  Display Stream Compression (Reduce the amount of bits to represent pixel count while at the same pixel clock)

- **<a id="rst-term-dgpu"></a>dGPU**

  discrete GPU

- **<a id="rst-term-dmif"></a>DMIF**

  Display Memory Interface

- **<a id="rst-term-dml"></a>DML**

  Display Mode Library

- **<a id="rst-term-dmcu"></a>DMCU**

  Display Micro-Controller Unit

- **<a id="rst-term-dmcub"></a>DMCUB**

  Display Micro-Controller Unit, version B

- **<a id="rst-term-dpcd"></a>DPCD**

  DisplayPort Configuration Data

- **<a id="rst-term-dpm-s"></a>DPM(S)**

  Display Power Management (Signaling)

- **<a id="rst-term-drr"></a>DRR**

  Dynamic Refresh Rate

- **<a id="rst-term-dwb"></a>DWB**

  Display Writeback

- **<a id="rst-term-fb"></a>FB**

  Frame Buffer

- **<a id="rst-term-fbc"></a>FBC**

  Frame Buffer Compression

- **<a id="rst-term-fec"></a>FEC**

  Forward Error Correction

- **<a id="rst-term-frl"></a>FRL**

  Fixed Rate Link

- **<a id="rst-term-gco"></a>GCO**

  Graphical Controller Object

- **<a id="rst-term-gsl"></a>GSL**

  Global Swap Lock

- **<a id="rst-term-igpu"></a>iGPU**

  integrated GPU

- **<a id="rst-term-isr"></a>ISR**

  Interrupt Service Request

- **<a id="rst-term-isv"></a>ISV**

  Independent Software Vendor

- **<a id="rst-term-kmd"></a>KMD**

  Kernel Mode Driver

- **<a id="rst-term-lb"></a>LB**

  Line Buffer

- **<a id="rst-term-lfc"></a>LFC**

  Low Framerate Compensation

- **<a id="rst-term-lttpr"></a>LTTPR**

  Link Training Tunable Phy Repeater

- **<a id="rst-term-lut"></a>LUT**

  Lookup Table

- **<a id="rst-term-mall"></a>MALL**

  Memory Access at Last Level

- **<a id="rst-term-mpc-mpcc"></a>MPC/MPCC**

  Multiple pipes and plane combine

- **<a id="rst-term-mpo"></a>MPO**

  Multi Plane Overlay

- **<a id="rst-term-mst"></a>MST**

  Multi Stream Transport

- **<a id="rst-term-nbp-state"></a>NBP State**

  Northbridge Power State

- **<a id="rst-term-nbio"></a>NBIO**

  North Bridge Input/Output

- **<a id="rst-term-odm"></a>ODM**

  Output Data Mapping

- **<a id="rst-term-opm"></a>OPM**

  Output Protection Manager

- **<a id="rst-term-opp"></a>OPP**

  Output Plane Processor

- **<a id="rst-term-optc"></a>OPTC**

  Output Pipe Timing Combiner

- **<a id="rst-term-otg"></a>OTG**

  Output Timing Generator

- **<a id="rst-term-pcon"></a>PCON**

  Power Controller

- **<a id="rst-term-pgfsm"></a>PGFSM**

  Power Gate Finite State Machine

- **<a id="rst-term-psr"></a>PSR**

  Panel Self Refresh

- **<a id="rst-term-scl"></a>SCL**

  Scaler

- **<a id="rst-term-sdp"></a>SDP**

  Scalable Data Port

- **<a id="rst-term-sls"></a>SLS**

  Single Large Surface

- **<a id="rst-term-sst"></a>SST**

  Single Stream Transport

- **<a id="rst-term-tmds"></a>TMDS**

  Transition-Minimized Differential Signaling

- **<a id="rst-term-ttu"></a>TTU**

  Time to Underflow

- **<a id="rst-term-vrr"></a>VRR**

  Variable Refresh Rate

---

# DCN Blocks

_Peios Kernel / Hardware and drivers / Graphics / amdgpu / display_

> In this section, you will find some extra details about some of the DCN blocks and the code documentation when it is automatically generated.

<a id="rst-dcn-blocks-1"></a>
<a id="rst-dcn-blocks"></a>

In this section, you will find some extra details about some of the DCN blocks and the code documentation when it is automatically generated.

<a id="rst-dchubbub"></a>

## DCHUBBUB


There is only one common DCHUBBUB. It contains the common request and return
blocks for the Data Fabric Interface that are not clock/power gated.


<a id="rst-hubp"></a>

## HUBP


Display Controller Hub (DCHUB) is the gateway between the Scalable Data Port
(SDP) and DCN. This component has multiple features, such as memory
arbitration, rotation, and cursor manipulation.

There is one HUBP allocated per pipe, which fetches data and converts
different pixel formats (i.e. ARGB8888, NV12, etc) into linear, interleaved
and fixed-depth streams of pixel data.


<a id="rst-dpp"></a>

## DPP


The DPP (Display Pipe and Plane) block is the unified display data
processing engine in DCN for processing graphic or video data on per DPP
rectangle base. This rectangle can be a part of SLS (Single Large Surface),
or a layer to be blended with other DPP, or a rectangle associated with a
display tile.

It provides various functions including:
- graphic color keyer
- graphic cursor compositing
- graphic or video image source to destination scaling
- image sharping
- video format conversion from 4:2:0 or 4:2:2 to 4:4:4
- Color Space Conversion
- Host LUT gamma adjustment
- Color Gamut Remap
- brightness and contrast adjustment.

DPP pipe consists of Converter and Cursor (CNVC), Scaler (DSCL), Color
Management (CM), Output Buffer (OBUF) and Digital Bypass (DPB) module
connected in a video/graphics pipeline.



#### <a id="c-struct-cnv_alpha_2bit_lut"></a>`struct cnv_alpha_2bit_lut`

Set the 8bit alpha values based on the 2 bit alpha

**Definition**

```c
struct cnv_alpha_2bit_lut {
    int lut0;
    int lut1;
    int lut2;
    int lut3;
};
```

**Members**

- `lut0`: ALPHA_2BIT_LUT. ALPHA_2BIT_LUT0. Default: 0b00000000
- `lut1`: ALPHA_2BIT_LUT. ALPHA_2BIT_LUT1. Default: 0b01010101
- `lut2`: ALPHA_2BIT_LUT. ALPHA_2BIT_LUT2. Default: 0b10101010
- `lut3`: ALPHA_2BIT_LUT. ALPHA_2BIT_LUT3. Default: 0b11111111


<a id="rst-mpc"></a>

## MPC


Multiple Pipe/Plane Combiner (MPC) is a component in the hardware pipeline
that performs blending of multiple planes, using global and per-pixel alpha.
It also performs post-blending color correction operations according to the
hardware capabilities, such as color transformation matrix and gamma 1D and
3D LUT.

MPC receives output from all DPP pipes and combines them to multiple outputs
supporting "M MPC inputs -> N MPC outputs" flexible composition
architecture. It features:

- Programmable blending structure to allow software controlled blending and
  cascading;
- Programmable window location of each DPP in active region of display;
- Combining multiple DPP pipes in one active region when a single DPP pipe
  cannot process very large surface;
- Combining multiple DPP from different SLS with blending;
- Stereo formats from single DPP in top-bottom or side-by-side modes;
- Stereo formats from 2 DPPs;
- Alpha blending of multiple layers from different DPP pipes;
- Programmable background color;



#### <a id="c-struct-mpcc"></a>`struct mpcc`

MPCC connection and blending configuration for a single MPCC instance.

**Definition**

```c
struct mpcc {
    int mpcc_id;
    int dpp_id;
    struct mpcc *mpcc_bot;
    struct mpcc_blnd_cfg blnd_cfg;
    struct mpcc_sm_cfg sm_cfg;
    bool shared_bottom;
};
```

**Members**

- `mpcc_id`: MPCC physical instance.
- `dpp_id`: DPP input to this MPCC
- `mpcc_bot`: Pointer to bottom layer MPCC. NULL when not connected.
- `blnd_cfg`: The blending configuration for this MPCC.
- `sm_cfg`: stereo mix setting for this MPCC
- `shared_bottom`: If MPCC output to both OPP and DWB endpoints, true. Otherwise, false.

**Description**

This struct is used as a node in an MPC tree.

#### <a id="c-struct-mpc_tree"></a>`struct mpc_tree`

MPC tree represents all MPCC connections for a pipe.

**Definition**

```c
struct mpc_tree {
    int opp_id;
    struct mpcc *opp_list;
};
```

**Members**

- `opp_id`: The OPP instance that owns this MPC tree.
- `opp_list`: the top MPCC layer of the MPC tree that outputs to OPP endpoint

#### <a id="c-struct-mpc_funcs"></a>`struct mpc_funcs`

funcs

**Definition**

```c
struct mpc_funcs {
    void (*read_mpcc_state)( struct mpc *mpc, int mpcc_inst, struct mpcc_state *s);
    void (*mpc_read_reg_state)( struct mpc *mpc, int mpcc_inst, struct dcn_mpc_reg_state *mpc_reg_state);
    struct mpcc* (*insert_plane)( struct mpc *mpc, struct mpc_tree *tree, struct mpcc_blnd_cfg *blnd_cfg, struct mpcc_sm_cfg *sm_cfg, struct mpcc *insert_above_mpcc, int dpp_id, int mpcc_id);
    void (*remove_mpcc)( struct mpc *mpc, struct mpc_tree *tree, struct mpcc *mpcc);
    void (*mpc_init)(struct mpc *mpc);
    void (*mpc_init_single_inst)( struct mpc *mpc, unsigned int mpcc_id);
    void (*update_blending)( struct mpc *mpc, struct mpcc_blnd_cfg *blnd_cfg, int mpcc_id);
    void (*cursor_lock)( struct mpc *mpc, int opp_id, bool lock);
    struct mpcc* (*insert_plane_to_secondary)( struct mpc *mpc, struct mpc_tree *tree, struct mpcc_blnd_cfg *blnd_cfg, struct mpcc_sm_cfg *sm_cfg, struct mpcc *insert_above_mpcc, int dpp_id, int mpcc_id);
    void (*remove_mpcc_from_secondary)( struct mpc *mpc, struct mpc_tree *tree, struct mpcc *mpcc);
    struct mpcc* (*get_mpcc_for_dpp_from_secondary)( struct mpc_tree *tree, int dpp_id);
    struct mpcc* (*get_mpcc_for_dpp)( struct mpc_tree *tree, int dpp_id);
    void (*wait_for_idle)(struct mpc *mpc, int id);
    void (*assert_mpcc_idle_before_connect)(struct mpc *mpc, int mpcc_id);
    void (*init_mpcc_list_from_hw)( struct mpc *mpc, struct mpc_tree *tree);
    void (*set_denorm)(struct mpc *mpc, int opp_id, enum dc_color_depth output_depth);
    void (*set_denorm_clamp)( struct mpc *mpc, int opp_id, struct mpc_denorm_clamp denorm_clamp);
    void (*set_output_csc)(struct mpc *mpc, int opp_id, const uint16_t *regval, enum mpc_output_csc_mode ocsc_mode);
    void (*set_ocsc_default)(struct mpc *mpc, int opp_id, enum dc_color_space color_space, enum mpc_output_csc_mode ocsc_mode);
    void (*set_output_gamma)( struct mpc *mpc, int mpcc_id, const struct pwl_params *params);
    void (*power_on_mpc_mem_pwr)( struct mpc *mpc, int mpcc_id, bool power_on);
    void (*set_dwb_mux)( struct mpc *mpc, int dwb_id, int mpcc_id);
    void (*disable_dwb_mux)( struct mpc *mpc, int dwb_id);
    bool (*is_dwb_idle)( struct mpc *mpc, int dwb_id);
    void (*set_out_rate_control)( struct mpc *mpc, int opp_id, bool enable, bool rate_2x_mode, struct mpc_dwb_flow_control *flow_control);
    void (*set_gamut_remap)( struct mpc *mpc, int mpcc_id, const struct mpc_grph_gamut_adjustment *adjust);
    bool (*program_1dlut)( struct mpc *mpc, const struct pwl_params *params, uint32_t rmu_idx);
    bool (*program_shaper)( struct mpc *mpc, const struct pwl_params *params, uint32_t rmu_idx);
    uint32_t (*acquire_rmu)(struct mpc *mpc, int mpcc_id, int rmu_idx);
    bool (*program_3dlut)( struct mpc *mpc, const struct tetrahedral_params *params, int rmu_idx);
    int (*release_rmu)(struct mpc *mpc, int mpcc_id);
    unsigned int (*get_mpc_out_mux)( struct mpc *mpc, int opp_id);
    void (*set_bg_color)(struct mpc *mpc, struct tg_color *bg_color, int mpcc_id);
    void (*set_mpc_mem_lp_mode)(struct mpc *mpc);
    void (*set_movable_cm_location)(struct mpc *mpc, enum mpcc_movable_cm_location location, int mpcc_id);
    void (*update_3dlut_fast_load_select)(struct mpc *mpc, int mpcc_id, int hubp_idx);
    void (*populate_lut)(struct mpc *mpc, const enum MCM_LUT_ID id, const union mcm_lut_params params, bool lut_bank_a, int mpcc_id);
    void (*program_lut_read_write_control)(struct mpc *mpc, const enum MCM_LUT_ID id, bool lut_bank_a, int mpcc_id);
    void (*program_lut_mode)(struct mpc *mpc, const enum MCM_LUT_ID id, const enum MCM_LUT_XABLE xable, bool lut_bank_a, int mpcc_id);
    struct {
        void (*program_3dlut_size)(struct mpc *mpc, uint32_t width, int mpcc_id);
        void (*program_bias_scale)(struct mpc *mpc, uint16_t bias, uint16_t scale, int mpcc_id);
        void (*program_bit_depth)(struct mpc *mpc, uint16_t bit_depth, int mpcc_id);
        bool (*is_config_supported)(uint32_t width);
        void (*program_lut_read_write_control)(struct mpc *mpc, const enum MCM_LUT_ID id, bool lut_bank_a, bool enabled, int mpcc_id);
        void (*populate_lut)(struct mpc *mpc, const union mcm_lut_params params, bool lut_bank_a, int mpcc_id);
    } mcm;
    struct {
        void (*fl_3dlut_configure)(struct mpc *mpc, struct mpc_fl_3dlut_config *cfg, int mpcc_id);
        void (*enable_3dlut_fl)(struct mpc *mpc, bool enable, int mpcc_id);
        void (*update_3dlut_fast_load_select)(struct mpc *mpc, int mpcc_id, int hubp_idx);
        void (*program_lut_read_write_control)(struct mpc *mpc, const enum MCM_LUT_ID id, bool lut_bank_a, bool enabled, int mpcc_id);
        void (*program_lut_mode)(struct mpc *mpc, const enum MCM_LUT_XABLE xable, bool lut_bank_a, int mpcc_id);
        void (*program_3dlut_size)(struct mpc *mpc, uint32_t width, int mpcc_id);
        void (*program_bias_scale)(struct mpc *mpc, uint16_t bias, uint16_t scale, int mpcc_id);
        void (*program_bit_depth)(struct mpc *mpc, uint16_t bit_depth, int mpcc_id);
        bool (*is_config_supported)(uint32_t width);
        void (*power_on_shaper_3dlut)(struct mpc *mpc, uint32_t mpcc_id, bool power_on);
        void (*populate_lut)(struct mpc *mpc, const union mcm_lut_params params, bool lut_bank_a, int mpcc_id);
    } rmcm;
};
```

**Members**

- `read_mpcc_state`: Read register content from given MPCC physical instance.

  Parameters:

  - \[in/out\] mpc - MPC context
  - \[in\] mpcc_instance - MPC context instance
  - \[in\] mpcc_state - MPC context state

  Return:

  void
- `mpc_read_reg_state`: Read MPC register state for debugging underflow purposes.

  Parameters:

  - \[in\] mpc - MPC context
  - \[out\] reg_state - MPC register state structure

  Return:

  void
- `insert_plane`: Insert DPP into MPC tree based on specified blending position.
  Only used for planes that are part of blending chain for OPP output

  Parameters:

  - \[in/out\] mpc  - MPC context.
  - \[in/out\] tree - MPC tree structure that plane will be added to.
  - \[in\] blnd_cfg - MPCC blending configuration for the new blending layer.
  - \[in\] sm_cfg   - MPCC stereo mix configuration for the new blending layer.
    stereo mix must disable for the very bottom layer of the tree config.
  - \[in\] insert_above_mpcc - Insert new plane above this MPCC.
    If NULL, insert as bottom plane.
  - \[in\] dpp_id  - DPP instance for the plane to be added.
  - \[in\] mpcc_id - The MPCC physical instance to use for blending.

  Return:

  struct mpcc* - MPCC that was added.
- `remove_mpcc`: Remove a specified MPCC from the MPC tree.

  Parameters:

  - \[in/out\] mpc   - MPC context.
  - \[in/out\] tree  - MPC tree structure that plane will be removed from.
  - \[in/out\] mpcc  - MPCC to be removed from tree.

  Return:

  void
- `mpc_init`: Reset the MPCC HW status by disconnecting all muxes.

  Parameters:

  - \[in/out\] mpc - MPC context.

  Return:

  void
- `mpc_init_single_inst`: Initialize given MPCC physical instance.

  Parameters:
  - \[in/out\] mpc - MPC context.
  - \[in\] mpcc_id - The MPCC physical instance to be initialized.
- `update_blending`: Update the blending configuration for a specified MPCC.

  Parameters:

  - \[in/out\] mpc - MPC context.
  - \[in\] blnd_cfg - MPCC blending configuration.
  - \[in\] mpcc_id  - The MPCC physical instance.

  Return:

  void
- `cursor_lock`: Lock cursor updates for the specified OPP. OPP defines the set of
  MPCC that are locked together for cursor.

  Parameters:

  - \[in\] mpc - MPC context.
  - \[in\] opp_id  - The OPP to lock cursor updates on
  - \[in\] lock - lock/unlock the OPP

  Return:

  void
- `insert_plane_to_secondary`: Add DPP into secondary MPC tree based on specified blending
  position.  Only used for planes that are part of blending chain for
  DWB output

  Parameters:

  - \[in/out\] mpc  - MPC context.
  - \[in/out\] tree - MPC tree structure that plane will be added to.
  - \[in\] blnd_cfg - MPCC blending configuration for the new blending layer.
  - \[in\] sm_cfg   - MPCC stereo mix configuration for the new blending layer.
    stereo mix must disable for the very bottom layer of the tree config.
  - \[in\] insert_above_mpcc - Insert new plane above this MPCC.  If
    NULL, insert as bottom plane.
  - \[in\] dpp_id - DPP instance for the plane to be added.
  - \[in\] mpcc_id - The MPCC physical instance to use for blending.

  Return:

  struct mpcc* - MPCC that was added.
- `remove_mpcc_from_secondary`: Remove a specified DPP from the 'secondary' MPC tree.

  Parameters:

  - \[in/out\] mpc  - MPC context.
  - \[in/out\] tree - MPC tree structure that plane will be removed from.
  - \[in\]     mpcc - MPCC to be removed from tree.

  Return:

  void
- `get_mpcc_for_dpp_from_secondary`: Find, if it exists, a MPCC from a given 'secondary' MPC tree that
  is associated with specified plane.

  Parameters:
  - \[in/out\] tree - MPC tree structure to search for plane.
  - \[in\] dpp_id - DPP to be searched.

  Return:

  struct mpcc* - pointer to plane or NULL if no plane found.
- `get_mpcc_for_dpp`: Find, if it exists, a MPCC from a given MPC tree that
  is associated with specified plane.

  Parameters:
  - \[in/out\] tree - MPC tree structure to search for plane.
  - \[in\] dpp_id - DPP to be searched.

  Return:

  struct mpcc* - pointer to plane or NULL if no plane found.
- `wait_for_idle`: Wait for a MPCC in MPC context to enter idle state.

  Parameters:
  - \[in/out\] mpc - MPC Context.
  - \[in\] id - MPCC to wait for idle state.

  Return:

  void
- `assert_mpcc_idle_before_connect`: Assert if MPCC in MPC context is in idle state.

  Parameters:
  - \[in/out\] mpc - MPC context.
  - \[in\] id - MPCC to assert idle state.

  Return:

  void
- `init_mpcc_list_from_hw`: Iterate through the MPCC array from a given MPC context struct
  and configure each MPCC according to its registers' values.

  Parameters:
  - \[in/out\] mpc - MPC context to initialize MPCC array.
  - \[in/out\] tree - MPC tree structure containing MPCC contexts to initialize.

  Return:

  void
- `set_denorm`: Set corresponding OPP DENORM_CONTROL register value to specific denorm_mode
  based on given color depth.

  Parameters:
  - \[in/out\] mpc - MPC context.
  - \[in\] opp_id - Corresponding OPP to update register.
  - \[in\] output_depth - Arbitrary color depth to set denorm_mode.

  Return:

  void
- `set_denorm_clamp`: Set denorm clamp values on corresponding OPP DENORM CONTROL register.

  Parameters:
  - \[in/out\] mpc - MPC context.
  - \[in\] opp_id - Corresponding OPP to update register.
  - \[in\] denorm_clamp - Arbitrary denorm clamp to be set.

  Return:

  void
- `set_output_csc`: Set the Output Color Space Conversion matrix
  with given values and mode.

  Parameters:
  - \[in/out\] mpc - MPC context.
  - \[in\] opp_id - Corresponding OPP to update register.
  - \[in\] regval - Values to set in CSC matrix.
  - \[in\] ocsc_mode - Mode to set CSC.

  Return:

  void
- `set_ocsc_default`: Set the Output Color Space Conversion matrix
  to default values according to color space.

  Parameters:
  - \[in/out\] mpc - MPC context.
  - \[in\] opp_id - Corresponding OPP to update register.
  - \[in\] color_space - OCSC color space.
  - \[in\] ocsc_mode - Mode to set CSC.

  Return:

  void
- `set_output_gamma`: Set Output Gamma with given curve parameters.

  Parameters:
  - \[in/out\] mpc - MPC context.
  - \[in\] mpcc_id - Corresponding MPC to update registers.
  - \[in\] params - Parameters.

  Return:

  void
- `power_on_mpc_mem_pwr`: Power on/off memory LUT for given MPCC.
  Powering on enables LUT to be updated.
  Powering off allows entering low power mode.

  Parameters:
  - \[in/out\] mpc - MPC context.
  - \[in\] mpcc_id - MPCC to power on.
  - \[in\] power_on

  Return:

  void
- `set_dwb_mux`: Set corresponding Display Writeback mux
  MPC register field to given MPCC id.

  Parameters:
  - \[in/out\] mpc - MPC context.
  - \[in\] dwb_id - DWB to be set.
  - \[in\] mpcc_id - MPCC id to be stored in DWB mux register.

  Return:

  void
- `disable_dwb_mux`: Reset corresponding Display Writeback mux
  MPC register field.

  Parameters:
  - \[in/out\] mpc - MPC context.
  - \[in\] dwb_id - DWB to be set.

  Return:

  void
- `is_dwb_idle`: Check DWB status on MPC_DWB0_MUX_STATUS register field.
  Return if it is null.

  Parameters:
  - \[in/out\] mpc - MPC context.
  - \[in\] dwb_id - DWB to be checked.

  Return:

  bool - wheter DWB is idle or not
- `set_out_rate_control`: Set display output rate control.

  Parameters:
  - \[in/out\] mpc - MPC context.
  - \[in\] opp_id - OPP to be set.
  - \[in\] enable
  - \[in\] rate_2x_mode
  - \[in\] flow_control

  Return:

  void
- `set_gamut_remap`: Set post-blending CTM for given MPCC.

  Parameters:
  - \[in\] mpc - MPC context.
  - \[in\] mpcc_id - MPCC to set gamut map.
  - \[in\] adjust

  Return:

  void
- `program_1dlut`: Set 1 dimensional Lookup Table.

  Parameters:
  - \[in/out\] mpc - MPC context
  - \[in\] params - curve parameters for the LUT configuration
  - \[in\] rmu_idx

  bool - wheter LUT was set (set with given parameters) or not (params is NULL and LUT is disabled).
- `program_shaper`: Set shaper.

  Parameters:
  - \[in/out\] mpc - MPC context
  - \[in\] params - curve parameters to be set
  - \[in\] rmu_idx

  Return:

  bool - wheter shaper was set (set with given parameters) or not (params is NULL and LUT is disabled).
- `acquire_rmu`: Set given MPCC to be multiplexed to given RMU unit.

  Parameters:
  - \[in/out\] mpc - MPC context
  - \[in\] mpcc_id - MPCC
  - \[in\] rmu_idx - Given RMU unit to set MPCC to be multiplexed to.

  Return:

  unit32_t - rmu_idx if operation was successful, -1 else.
- `program_3dlut`: Set 3 dimensional Lookup Table.

  Parameters:
  - \[in/out\] mpc - MPC context
  - \[in\] params - tetrahedral parameters for the LUT configuration
  - \[in\] rmu_idx

  bool - wheter LUT was set (set with given parameters) or not (params is NULL and LUT is disabled).
- `release_rmu`: For a given MPCC, release the RMU unit it muliplexes to.

  Parameters:
  - \[in/out\] mpc - MPC context
  - \[in\] mpcc_id - MPCC

  Return:

  int - a valid rmu_idx representing released RMU unit or -1 if there was no RMU unit to release.
- `get_mpc_out_mux`: Return MPC out mux.

  Parameters:
  - \[in\] mpc - MPC context.
  - \[in\] opp_id - OPP

  Return:

  unsigned int - Out Mux
- `set_bg_color`: Find corresponding bottommost MPCC and
  set its bg color.

  Parameters:
  - \[in/out\] mpc - MPC context.
  - \[in\] bg_color - background color to be set.
  - \[in\] mpcc_id

  Return:

  void
- `set_mpc_mem_lp_mode`: Set mpc_mem_lp_mode.

  Parameters:
  - \[in/out\] mpc - MPC context.

  Return:

  void
- `set_movable_cm_location`: Set Movable CM Location.

  Parameters:
  - \[in/out\] mpc - MPC context.
  - \[in\] location
  - \[in\] mpcc_id

  Return:

  void
- `update_3dlut_fast_load_select`: Update 3D LUT fast load select.

  Parameters:
  - \[in/out\] mpc - MPC context.
  - \[in\] mpcc_id
  - \[in\] hubp_idx

  Return:

  void
- `populate_lut`: Populate LUT with given tetrahedral parameters.

  Parameters:
  - \[in/out\] mpc - MPC context.
  - \[in\] id
  - \[in\] params
  - \[in\] lut_bank_a
  - \[in\] mpcc_id

  Return:

  void
- `program_lut_read_write_control`: Program LUT RW control.

  Parameters:
  - \[in/out\] mpc - MPC context.
  - \[in\] id
  - \[in\] lut_bank_a
  - \[in\] mpcc_id

  Return:

  void
- `program_lut_mode`: Program LUT mode.

  Parameters:
  - \[in/out\] mpc - MPC context.
  - \[in\] id
  - \[in\] xable
  - \[in\] lut_bank_a
  - \[in\] mpcc_id

  Return:

  void
- `mcm`: MPC MCM new HW sequential programming functions
- `rmcm`: MPC RMCM new HW sequential programming functions


<a id="rst-opp"></a>

## OPP


The Output Plane Processor (OPP) block groups have functions that format
pixel streams such that they are suitable for display at the display device.
The key functions contained in the OPP are:

- Adaptive Backlight Modulation (ABM)
- Formatter (FMT) which provide pixel-by-pixel operations for format the
  incoming pixel stream.
- Output Buffer that provide pixel replication, and overlapping.
- Interface between MPC and OPTC.
- Clock and reset generation.
- CRC generation.



#### <a id="c-struct-pwl_float_data"></a>`struct pwl_float_data`

Fixed point RGB color

**Definition**

```c
struct pwl_float_data {
    struct fixed31_32 r;
    struct fixed31_32 g;
    struct fixed31_32 b;
};
```

**Members**

- `r`: Component Red.
- `g`: Component Green.
- `b`: Component Blue.


<a id="rst-dio"></a>

## DIO


Display Input Output (DIO), is the display input and output unit in DCN. It
includes output encoders to support different display output, like
DisplayPort, HDMI, DVI interface, and others. It also includes the control
and status channels for these interfaces.



#### <a id="c-can_use_dio_link_hwss"></a>`can_use_dio_link_hwss()`

```c
bool can_use_dio_link_hwss(const struct dc_link *link, const struct link_resource *link_res)
```

Check if the link_hwss is accessible

**Parameters**

- `const struct dc_link *link`: Reference a link struct containing one or more sinks and the
  connective status.
- `const struct link_resource *link_res`: Mappable hardware resource used to enable a link.

**Return**

Return true if the link encoder is accessible from link.

#### <a id="c-get_dio_link_hwss"></a>`get_dio_link_hwss()`

```c
const struct link_hwss * get_dio_link_hwss(void)
```

Return link_hwss reference

**Parameters**

- `void`: no arguments

**Description**

This function behaves like a get function to return the link_hwss populated
in the link_hwss_dio.c file.

**Return**

Return the reference to the filled struct of link_hwss.

---

# Display Core Next (DCN)

_Peios Kernel / Hardware and drivers / Graphics / amdgpu / display_

> To equip our readers with the basic knowledge of how AMD Display Core Next (DCN) works, we need to start with an overview of the hardware pipeline. Below you can see a picture that provides a DCN overview, keep in mind that this is a…

<a id="rst-display-core-next-dcn"></a>
<a id="rst-dcn-overview"></a>

To equip our readers with the basic knowledge of how AMD Display Core Next (DCN) works, we need to start with an overview of the hardware pipeline. Below you can see a picture that provides a DCN overview, keep in mind that this is a generic diagram, and we have variations per ASIC.

![](/kernel/hardware/gpu/amdgpu-display/asset-242f34babc4b-dc-pipeline-overview.svg)

Based on this diagram, we can pass through each block and briefly describe them:

- **Display Controller Hub (DCHUB)**: This is the gateway between the Scalable Data Port (SDP) and DCN. This component has multiple features, such as memory arbitration, rotation, and cursor manipulation.

- **Display Pipe and Plane (DPP)**: This block provides pre-blend pixel processing such as color space conversion, linearization of pixel data, tone mapping, and gamut mapping.

- **Multiple Pipe/Plane Combined (MPC)**: This component performs blending of multiple planes, using global or per-pixel alpha.

- **Output Pixel Processing (OPP)**: Process and format pixels to be sent to the display.

- **Output Pipe Timing Combiner (OPTC)**: It generates time output to combine streams or divide capabilities. CRC values are generated in this block.

- **Display Output (DIO)**: Codify the output to the display connected to our GPU.

- **Display Writeback (DWB)**: It provides the ability to write the output of the display pipe back to memory as video frames.

- **Multi-Media HUB (MMHUBBUB)**: Memory controller interface for DMCUB and DWB (Note that DWB is not hooked yet).

- **DCN Management Unit (DMU)**: It provides registers with access control and interrupts the controller to the SOC host interrupt unit. This block includes the Display Micro-Controller Unit - version B (DMCUB), which is handled via firmware.

- **DCN Clock Generator Block (DCCG)**: It provides the clocks and resets for all of the display controller clock domains.

- **Azalia (AZ)**: Audio engine.

The above diagram is an architecture generalization of DCN, which means that every ASIC has variations around this base model. Notice that the display pipeline is connected to the Scalable Data Port (SDP) via DCHUB; you can see the SDP as the element from our Data Fabric that feeds the display pipe.

Always approach the DCN architecture as something flexible that can be configured and reconfigured in multiple ways; in other words, each block can be setup or ignored accordingly with userspace demands. For example, if we want to drive an [8k@60Hz](<mailto:8k@60Hz>) with a DSC enabled, our DCN may require 4 DPP and 2 OPP. It is DC's responsibility to drive the best configuration for each specific scenario. Orchestrate all of these components together requires a sophisticated communication interface which is highlighted in the diagram by the edges that connect each block; from the chart, each connection between these blocks represents:

1. Pixel data interface (red): Represents the pixel data flow;

2. Global sync signals (green): It is a set of synchronization signals composed by VStartup, VUpdate, and VReady;

3. Config interface: Responsible to configure blocks;

4. Sideband signals: All other signals that do not fit the previous one.

These signals are essential and play an important role in DCN. Nevertheless, the Global Sync deserves an extra level of detail described in the next section.

All of these components are represented by a data structure named dc_state. From DCHUB to MPC, we have a representation called dc_plane; from MPC to OPTC, we have dc_stream, and the output (DIO) is handled by dc_link. Keep in mind that HUBP accesses a surface using a specific format read from memory, and our dc_plane should work to convert all pixels in the plane to something that can be sent to the display via dc_stream and dc_link.

<a id="rst-front-end-and-back-end"></a>

## Front End and Back End

Display pipeline can be broken down into two components that are usually referred as **Front End (FE)** and **Back End (BE)**, where FE consists of:

- DCHUB (Mainly referring to a subcomponent named HUBP)

- DPP

- MPC

On the other hand, BE consist of

- OPP

- OPTC

- DIO (DP/HDMI stream encoder and link encoder)

OPP and OPTC are two joining blocks between FE and BE. On a side note, this is a one-to-one mapping of the link encoder to PHY, but we can configure the DCN to choose which link encoder to connect to which PHY. FE's main responsibility is to change, blend and compose pixel data, while BE's job is to frame a generic pixel stream to a specific display's pixel stream.

<a id="rst-data-flow"></a>

## Data Flow

Initially, data is passed in from VRAM through Data Fabric (DF) in native pixel formats. Such data format stays through till HUBP in DCHUB, where HUBP unpacks different pixel formats and outputs them to DPP in uniform streams through 4 channels (1 for alpha + 3 for colors).

The Converter and Cursor (CNVC) in DPP would then normalize the data representation and convert them to a DCN specific floating-point format (i.e., different from the IEEE floating-point format). In the process, CNVC also applies a degamma function to transform the data from non-linear to linear space to relax the floating-point calculations following. Data would stay in this floating-point format from DPP to OPP.

Starting OPP, because color transformation and blending have been completed (i.e alpha can be dropped), and the end sinks do not require the precision and dynamic range that floating points provide (i.e. all displays are in integer depth format), bit-depth reduction/dithering would kick in. In OPP, we would also apply a regamma function to introduce the gamma removed earlier back. Eventually, we output data in integer format at DIO.

<a id="rst-amd-hardware-pipeline"></a>

## AMD Hardware Pipeline

When discussing graphics on Linux, the **pipeline** term can sometimes be overloaded with multiple meanings, so it is important to define what we mean when we say **pipeline**. In the DCN driver, we use the term **hardware pipeline** or **pipeline** or just **pipe** as an abstraction to indicate a sequence of DCN blocks instantiated to address some specific configuration. DC core treats DCN blocks as individual resources, meaning we can build a pipeline by taking resources for all individual hardware blocks to compose one pipeline. In actuality, we can't connect an arbitrary block from one pipe to a block from another pipe; they are routed linearly, except for DSC, which can be arbitrarily assigned as needed. We have this pipeline concept for trying to optimize bandwidth utilization.

![](/kernel/hardware/gpu/amdgpu-display/asset-436f6ea5ffc5-pipeline-4k-no-split.svg)

Additionally, let's take a look at parts of the DTN log (see '[Documentation/gpu/amdgpu/display/dc-debug.rst](https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/Documentation/gpu/amdgpu/display/dc-debug.rst?id=9021cc14f7d98b4a1d2c932f52c5343d4d0f6b92)' for more information) since this log can help us to see part of this pipeline behavior in real-time:



```text
HUBP:  format  addr_hi  width  height ...
[ 0]:      8h      81h   3840    2160
[ 1]:      0h       0h      0       0
[ 2]:      0h       0h      0       0
[ 3]:      0h       0h      0       0
[ 4]:      0h       0h      0       0
...
MPCC:  OPP  DPP ...
[ 0]:   0h   0h ...
```

The first thing to notice from the diagram and DTN log it is the fact that we have different clock domains for each part of the DCN blocks. In this example, we have just a single **pipeline** where the data flows from DCHUB to DIO, as we intuitively expect. Nonetheless, DCN is flexible, as mentioned before, and we can split this single pipe differently, as described in the below diagram:

![](/kernel/hardware/gpu/amdgpu-display/asset-afbdabad0f30-pipeline-4k-split.svg)

Now, if we inspect the DTN log again we can see some interesting changes:



```text
HUBP:  format  addr_hi  width  height ...
[ 0]:      8h      81h   1920    2160 ...
...
[ 4]:      0h       0h      0       0 ...
[ 5]:      8h      81h   1920    2160 ...
...
MPCC:  OPP  DPP ...
[ 0]:   0h   0h ...
[ 5]:   0h   5h ...
```

From the above example, we now split the display pipeline into two vertical parts of 1920x2160 (i.e., 3440x2160), and as a result, we could reduce the clock frequency in the DPP part. This is not only useful for saving power but also to better handle the required throughput. The idea to keep in mind here is that the pipe configuration can vary a lot according to the display configuration, and it is the DML's responsibility to set up all required configuration parameters for multiple scenarios supported by our hardware.

<a id="rst-global-sync"></a>

## Global Sync

Many DCN registers are double buffered, most importantly the surface address. This allows us to update DCN hardware atomically for page flips, as well as for most other updates that don't require enabling or disabling of new pipes.

(Note: There are many scenarios when DC will decide to reserve extra pipes in order to support outputs that need a very high pixel clock, or for power saving purposes.)

These atomic register updates are driven by global sync signals in DCN. In order to understand how atomic updates interact with DCN hardware, and how DCN signals page flip and vblank events it is helpful to understand how global sync is programmed.

Global sync consists of three signals, VSTARTUP, VUPDATE, and VREADY. These are calculated by the Display Mode Library - DML (drivers/gpu/drm/amd/display/dc/dml) based on a large number of parameters and ensure our hardware is able to feed the DCN pipeline without underflows or hangs in any given system configuration. The global sync signals always happen during VBlank, are independent from the VSync signal, and do not overlap each other.

VUPDATE is the only signal that is of interest to the rest of the driver stack or userspace clients as it signals the point at which hardware latches to atomically programmed (i.e. double buffered) registers. Even though it is independent of the VSync signal we use VUPDATE to signal the VSync event as it provides the best indication of how atomic commits and hardware interact.

Since DCN hardware is double-buffered the DC driver is able to program the hardware at any point during the frame.

The below picture illustrates the global sync signals:

![](/kernel/hardware/gpu/amdgpu-display/asset-b3d31376da96-global-sync-vblank.svg)

These signals affect core DCN behavior. Programming them incorrectly will lead to a number of negative consequences, most of them quite catastrophic.

The following picture shows how global sync allows for a mailbox style of updates, i.e. it allows for multiple re-configurations between VUpdate events where only the last configuration programmed before the VUpdate signal becomes effective.

![](/kernel/hardware/gpu/amdgpu-display/asset-76348db9b19f-config-example.svg)

---

# AMDGPU - Display Contributions

_Peios Kernel / Hardware and drivers / Graphics / amdgpu / display_

> First of all, if you are here, you probably want to give some technical contribution to the display code, and for that, we say thank you :)

<a id="rst-amdgpu-display-contributions"></a>
<a id="rst-display-todos"></a>

First of all, if you are here, you probably want to give some technical contribution to the display code, and for that, we say thank you :)

This page summarizes some of the issues you can help with; keep in mind that this is a static page, and it is always a good idea to try to reach developers on the amd-gfx mailing list or some of the maintainers. Finally, this page follows the DRM way of creating a TODO list; for more information, check '[Documentation/gpu/todo.rst](/kernel/hardware/gpu/todo.md)'.

<a id="rst-gitlab-issues"></a>

## Gitlab issues

Users can report issues associated with AMD GPUs at:

- [https://gitlab.freedesktop.org/drm/amd](<https://gitlab.freedesktop.org/drm/amd>)

Usually, we try to add a proper label to all new tickets to make it easy to filter issues. If you can reproduce any problem, you could help by adding more information or fixing the issue.

Level: diverse

<a id="rst-igt"></a>

## IGT

[IGT](<https://gitlab.freedesktop.org/drm/igt-gpu-tools>) provides many integration tests that can be run on your GPU. We always want to pass a large set of tests to increase the test coverage in our CI. If you wish to contribute to the display code but are unsure where a good place is, we recommend you run all IGT tests and try to fix any failure you see in your hardware. Keep in mind that this failure can be an IGT problem or a kernel issue; it is necessary to analyze case-by-case.

Level: diverse

<a id="rst-igt-1"></a>



<a id="rst-compilation"></a>

## Compilation

<a id="rst-fix-compilation-warnings"></a>

### Fix compilation warnings

Enable the W1 or W2 warning level in the kernel compilation and try to fix the issues on the display side.

Level: Starter

<a id="rst-fix-compilation-issues-when-using-um-architecture"></a>

### Fix compilation issues when using um architecture

Linux has a User-mode Linux (UML) feature, and the kernel can be compiled to the **um** architecture. Compiling for **um** can bring multiple advantages from the test perspective. We currently have some compilation issues in this area that we need to fix.

Level: Intermediate

<a id="rst-code-refactor"></a>

## Code Refactor

<a id="rst-add-prefix-to-dc-functions-to-improve-the-debug-with-ftrace"></a>

### Add prefix to DC functions to improve the debug with ftrace

The Ftrace debug feature (check '[Documentation/trace/ftrace.rst](https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/Documentation/trace/ftrace.rst?id=9021cc14f7d98b4a1d2c932f52c5343d4d0f6b92)') is a fantastic way to check the code path when developers try to make sense of a bug. Ftrace provides a filter mechanism that can be useful when the developer has some hunch of which part of the code can cause the issue; for this reason, if a set of functions has a proper prefix, it becomes easy to create a good filter. Additionally, prefixes can improve stack trace readability.

The DC code does not follow some prefix rules, which makes the Ftrace filter more complicated and reduces the readability of the stack trace. If you want something simple to start contributing to the display, you can make patches for adding prefixes to DC functions. To create those prefixes, use part of the file name as a prefix for all functions in the target file. Check the 'amdgpu_dm_crtc.c\` and `amdgpu_dm_plane.c` for some references. However, we strongly advise not to send huge patches changing these prefixes; otherwise, it will be hard to review and test, which can generate second thoughts from maintainers. Try small steps; in case of double, you can ask before you put in effort. We recommend first looking at folders like dceXYZ, dcnXYZ, basics, bios, core, clk_mgr, hwss, resource, and irq.

Level: Starter

<a id="rst-reduce-code-duplication"></a>

### Reduce code duplication

AMD has an extensive portfolio with various dGPUs and APUs that amdgpu supports. To maintain the new hardware release cadence, DCE/DCN was designed in a modular design, making the bring-up for new hardware fast. Over the years, amdgpu accumulated some technical debt in the code duplication area. For this task, it would be a good idea to find a tool that can discover code duplication (including patterns) and use it as guidance to reduce duplications.

Level: Intermediate

<a id="rst-make-atomic-commit-check-tail-more-readable"></a>

### Make atomic_commit\_\[check\|tail\] more readable

The functions responsible for atomic commit and tail are intricate and extensive. In particular `amdgpu_dm_atomic_commit_tail` is a long function and could benefit from being split into smaller helpers. Improvements in this area are more than welcome, but keep in mind that changes in this area will affect all ASICs, meaning that refactoring requires a comprehensive verification; in other words, this effort can take some time for validation.

Level: Advanced

<a id="rst-documentation"></a>

## Documentation

<a id="rst-expand-kernel-doc"></a>

### Expand kernel-doc

Many DC functions do not have a proper kernel-doc; understanding a function and adding documentation is a great way to learn more about the amdgpu driver and also leave an outstanding contribution to the entire community.

Level: Starter

<a id="rst-beyond-amdgpu"></a>

## Beyond AMDGPU

AMDGPU provides features that are not yet enabled in the userspace. This section highlights some of the coolest display features, which could be enabled with the userspace developer helper.

<a id="rst-enable-underlay"></a>

### Enable underlay

AMD display has this feature called underlay (which you can read more about at '[Documentation/gpu/amdgpu/display/mpo-overview.rst](/kernel/hardware/gpu/amdgpu-display/mpo-overview.md)') which is intended to save power when playing a video. The basic idea is to put a video in the underlay plane at the bottom and the desktop in the plane above it with a hole in the video area. This feature is enabled in ChromeOS, and from our data measurement, it can save power.

Level: Unknown

<a id="rst-adaptive-backlight-modulation-abm"></a>

### Adaptive Backlight Modulation (ABM)

ABM is a feature that adjusts the display panel's backlight level and pixel values depending on the displayed image. This power-saving feature can be very useful when the system starts to run off battery; since this will impact the display output fidelity, it would be good if this option was something that users could turn on or off.

Level: Unknown

<a id="rst-hdr-color-management-vrr"></a>

### HDR &amp; Color management &amp; VRR

HDR, Color Management, and VRR are huge topics and it's hard to put these into concise ToDos. If you are interested in this topic, we recommend checking some blog posts from the community developers to better understand some of the specific challenges and people working on the subject. If anyone wants to work on some particular part, we can try to help with some basic guidance. Finally, keep in mind that we already have some kernel-doc in place for those areas.

Level: Unknown

---

# AMDgpu Display Manager

_Peios Kernel / Hardware and drivers / Graphics / amdgpu / display_

> Lifecycle

<a id="rst-amdgpu-display-manager"></a>

<a id="rst-table-of-contents"></a>




The AMDgpu display manager, **amdgpu_dm** (or even simpler,
**dm**) sits between DRM and DC. It acts as a liaison, converting DRM
requests into DC requests, and DC responses into DRM responses.

The root control structure is [`struct amdgpu_display_manager`](#c-struct-amdgpu_display_manager).



#### <a id="c-struct-dm_compressor_info"></a>`struct dm_compressor_info`

Buffer info used by frame buffer compression

**Definition**

```c
struct dm_compressor_info {
    void *cpu_addr;
    struct amdgpu_bo *bo_ptr;
    uint64_t gpu_addr;
};
```

**Members**

- `cpu_addr`: MMIO cpu addr
- `bo_ptr`: Pointer to the buffer object
- `gpu_addr`: MMIO gpu addr

#### <a id="c-struct-dmub_hpd_work"></a>`struct dmub_hpd_work`

Handle time consuming work in low priority outbox IRQ

**Definition**

```c
struct dmub_hpd_work {
    struct work_struct handle_hpd_work;
    struct dmub_notification *dmub_notify;
    struct amdgpu_device *adev;
};
```

**Members**

- `handle_hpd_work`: Work to be executed in a separate thread to handle hpd_low_irq
- `dmub_notify`: notification for callback function
- `adev`: amdgpu_device pointer

#### <a id="c-struct-vblank_control_work"></a>`struct vblank_control_work`

Work data for vblank control

**Definition**

```c
struct vblank_control_work {
    struct work_struct work;
    struct amdgpu_display_manager *dm;
    struct amdgpu_crtc *acrtc;
    struct dc_stream_state *stream;
    bool enable;
};
```

**Members**

- `work`: Kernel work data for the work event
- `dm`: amdgpu display manager device
- `acrtc`: amdgpu CRTC instance for which the event has occurred
- `stream`: DC stream for which the event has occurred
- `enable`: true if enabling vblank

#### <a id="c-struct-idle_workqueue"></a>`struct idle_workqueue`

Work data for periodic action in idle

**Definition**

```c
struct idle_workqueue {
    struct work_struct work;
    struct amdgpu_display_manager *dm;
    bool enable;
    bool running;
};
```

**Members**

- `work`: Kernel work data for the work event
- `dm`: amdgpu display manager device
- `enable`: true if idle worker is enabled
- `running`: true if idle worker is running

#### <a id="c-struct-vupdate_offload_work"></a>`struct vupdate_offload_work`

Work data for offloading task from vupdate handler

**Definition**

```c
struct vupdate_offload_work {
    struct work_struct work;
    struct amdgpu_device *adev;
    struct dc_stream_state *stream;
    struct dc_crtc_timing_adjust *adjust;
};
```

**Members**

- `work`: Kernel work data for the work event
- `adev`: amdgpu_device back pointer
- `stream`: DC stream associated with the crtc
- `adjust`: DC CRTC timing adjust to be applied to the crtc

#### <a id="c-struct-amdgpu_dm_luminance_data"></a>`struct amdgpu_dm_luminance_data`

Custom luminance data

**Definition**

```c
struct amdgpu_dm_luminance_data {
    u8 luminance;
    u8 input_signal;
};
```

**Members**

- `luminance`: Luminance in percent
- `input_signal`: Input signal in range 0-255

#### <a id="c-struct-amdgpu_dm_backlight_caps"></a>`struct amdgpu_dm_backlight_caps`

Information about backlight

**Definition**

```c
struct amdgpu_dm_backlight_caps {
    union dpcd_sink_ext_caps *ext_caps;
    u32 aux_min_input_signal;
    u32 aux_max_input_signal;
    int min_input_signal;
    int max_input_signal;
    bool caps_valid;
    bool aux_support;
    u32 brightness_mask;
    u8 ac_level;
    u8 dc_level;
    u8 data_points;
    struct amdgpu_dm_luminance_data luminance_data[MAX_LUMINANCE_DATA_POINTS];
};
```

**Members**

- `ext_caps`: Keep the data struct with all the information about the
  display support for HDR.
- `aux_min_input_signal`: Min brightness value supported by the display
- `aux_max_input_signal`: Max brightness value supported by the display
  in nits.
- `min_input_signal`: minimum possible input in range 0-255.
- `max_input_signal`: maximum possible input in range 0-255.
- `caps_valid`: true if these values are from the ACPI interface.
- `aux_support`: Describes if the display supports AUX backlight.
- `brightness_mask`: After deriving brightness, OR it with this mask.
  Workaround for panels with issues with certain brightness values.
- `ac_level`: the default brightness if booted on AC
- `dc_level`: the default brightness if booted on DC
- `data_points`: the number of custom luminance data points
- `luminance_data`: custom luminance data

**Description**

Describe the backlight support for ACPI or eDP AUX.

#### <a id="c-struct-dal_allocation"></a>`struct dal_allocation`

Tracks mapped FB memory for SMU communication

**Definition**

```c
struct dal_allocation {
    struct list_head list;
    struct amdgpu_bo *bo;
    void *cpu_ptr;
    u64 gpu_addr;
};
```

**Members**

- `list`: list of dal allocations
- `bo`: GPU buffer object
- `cpu_ptr`: CPU virtual address of the GPU buffer object
- `gpu_addr`: GPU virtual address of the GPU buffer object

#### <a id="c-struct-hpd_rx_irq_offload_work_queue"></a>`struct hpd_rx_irq_offload_work_queue`

Work queue to handle hpd_rx_irq offload work

**Definition**

```c
struct hpd_rx_irq_offload_work_queue {
    struct workqueue_struct *wq;
    spinlock_t offload_lock;
    bool is_handling_link_loss;
    bool is_handling_mst_msg_rdy_event;
    struct amdgpu_dm_connector *aconnector;
};
```

**Members**

- `wq`: workqueue structure to queue offload work.
- `offload_lock`: To protect fields of offload work queue.
- `is_handling_link_loss`: Used to prevent inserting link loss event when
  we're handling link loss
- `is_handling_mst_msg_rdy_event`: Used to prevent inserting mst message
  ready event when we're already handling mst message ready event
- `aconnector`: The aconnector that this work queue is attached to

#### <a id="c-struct-hpd_rx_irq_offload_work"></a>`struct hpd_rx_irq_offload_work`

hpd_rx_irq offload work structure

**Definition**

```c
struct hpd_rx_irq_offload_work {
    struct work_struct work;
    union hpd_irq_data data;
    struct hpd_rx_irq_offload_work_queue *offload_wq;
    struct amdgpu_device *adev;
};
```

**Members**

- `work`: offload work
- `data`: reference irq data which is used while handling offload work
- `offload_wq`: offload work queue that this work is queued to
- `adev`: amdgpu_device pointer

#### <a id="c-struct-amdgpu_display_manager"></a>`struct amdgpu_display_manager`

Central amdgpu display manager device

**Definition**

```c
struct amdgpu_display_manager {
        struct dc *dc;
        struct dmub_srv *dmub_srv;
        struct dmub_notification *dmub_notify;
        dmub_notify_interrupt_callback_t dmub_callback[AMDGPU_DMUB_NOTIFICATION_MAX];
        bool dmub_thread_offload[AMDGPU_DMUB_NOTIFICATION_MAX];
        struct dmub_srv_fb_info *dmub_fb_info;
        const struct firmware *dmub_fw;
        struct amdgpu_bo *dmub_bo;
        u64 dmub_bo_gpu_addr;
        void *dmub_bo_cpu_addr;
        uint32_t dmcub_fw_version;
        uint32_t fw_inst_size;
        struct cgs_device *cgs_device;
        struct amdgpu_device *adev;
        struct drm_device *ddev;
        u16 display_indexes_num;
        struct drm_private_obj atomic_obj;
        struct mutex dc_lock;
        struct mutex audio_lock;
        struct drm_audio_component *audio_component;
        bool audio_registered;
        struct list_head irq_handler_list_low_tab[DAL_IRQ_SOURCES_NUMBER];
        struct list_head irq_handler_list_high_tab[DAL_IRQ_SOURCES_NUMBER];
        struct common_irq_params pflip_params[DC_IRQ_SOURCE_PFLIP_LAST - DC_IRQ_SOURCE_PFLIP_FIRST + 1];
        struct common_irq_params vblank_params[DC_IRQ_SOURCE_VBLANK6 - DC_IRQ_SOURCE_VBLANK1 + 1];
        struct common_irq_params vline0_params[DC_IRQ_SOURCE_DC6_VLINE0 - DC_IRQ_SOURCE_DC1_VLINE0 + 1];
        struct common_irq_params vupdate_params[DC_IRQ_SOURCE_VUPDATE6 - DC_IRQ_SOURCE_VUPDATE1 + 1];
        struct common_irq_params dmub_trace_params[1];
        struct common_irq_params dmub_outbox_params[1];
        spinlock_t irq_handler_list_table_lock;
        struct backlight_device *backlight_dev[AMDGPU_DM_MAX_NUM_EDP];
        const struct dc_link *backlight_link[AMDGPU_DM_MAX_NUM_EDP];
        uint8_t num_of_edps;
        struct amdgpu_dm_backlight_caps backlight_caps[AMDGPU_DM_MAX_NUM_EDP];
        struct mod_freesync *freesync_module;
        struct hdcp_workqueue *hdcp_workqueue;
        struct workqueue_struct *vblank_control_workqueue;
        struct idle_workqueue *idle_workqueue;
        struct drm_atomic_state *cached_state;
        struct dc_state *cached_dc_state;
        struct dm_compressor_info compressor;
        const struct firmware *fw_dmcu;
        uint32_t dmcu_fw_version;
        const struct gpu_info_soc_bounding_box_v1_0 *soc_bounding_box;
        uint32_t active_vblank_irq_count;
    #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY);
        struct secure_display_context secure_display_ctx;
    #endif;
        struct hpd_rx_irq_offload_work_queue *hpd_rx_offload_wq;
        struct amdgpu_encoder mst_encoders[AMDGPU_DM_MAX_CRTC];
        bool force_timing_sync;
        bool disable_hpd_irq;
        bool dmcub_trace_event_en;
        struct list_head da_list;
        struct completion dmub_aux_transfer_done;
        struct workqueue_struct *delayed_hpd_wq;
        u32 brightness[AMDGPU_DM_MAX_NUM_EDP];
        u32 actual_brightness[AMDGPU_DM_MAX_NUM_EDP];
        bool aux_hpd_discon_quirk;
        bool edp0_on_dp1_quirk;
        struct mutex dpia_aux_lock;
        void *bb_from_dmub;
        struct amdgpu_i2c_adapter *oem_i2c;
        struct fused_io_sync {
            struct completion replied;
            char reply_data[0x40];
        } fused_io[8];
};
```

**Members**

- `dc`: Display Core control structure
- `dmub_srv`: DMUB service, used for controlling the DMUB on hardware
  that supports it. The pointer to the dmub_srv will be
  NULL on hardware that does not support it.
- `dmub_notify`: Notification from DMUB.
- `dmub_callback`: Callback functions to handle notification from DMUB.
- `dmub_thread_offload`: Flag to indicate if callback is offload.
- `dmub_fb_info`: Framebuffer regions for the DMUB.
- `dmub_fw`: DMUB firmware, required on hardware that has DMUB support.
- `dmub_bo`: Buffer object for the DMUB.
- `dmub_bo_gpu_addr`: GPU virtual address for the DMUB buffer object.
- `dmub_bo_cpu_addr`: CPU address for the DMUB buffer object.
- `dmcub_fw_version`: DMCUB firmware version.
- `fw_inst_size`: Size of the firmware instruction buffer.
- `cgs_device`: The Common Graphics Services device. It provides an interface for
  accessing registers.
- `adev`: AMDGPU base driver structure
- `ddev`: DRM base driver structure
- `display_indexes_num`: Max number of display streams supported
- `atomic_obj`: In combination with `dm_atomic_state` it helps manage
  global atomic state that doesn't map cleanly into existing
  drm resources, like `dc_context`.
- `dc_lock`: Guards access to DC functions that can issue register write
  sequences.
- `audio_lock`: Guards access to audio instance changes.
- `audio_component`: Used to notify ELD changes to sound driver.
- `audio_registered`: True if the audio component has been registered
  successfully, false otherwise.
- `irq_handler_list_low_tab`: Low priority IRQ handler table.

  It is a n*m table consisting of n IRQ sources, and m handlers per IRQ
  source. Low priority IRQ handlers are deferred to a workqueue to be
  processed. Hence, they can sleep.

  Note that handlers are called in the same order as they were
  registered (FIFO).
- `irq_handler_list_high_tab`: High priority IRQ handler table.

  It is a n*m table, same as `irq_handler_list_low_tab`. However,
  handlers in this table are not deferred and are called immediately.
- `pflip_params`: Page flip IRQ parameters, passed to registered handlers when
  triggered.
- `vblank_params`: Vertical blanking IRQ parameters, passed to registered handlers when
  triggered.
- `vline0_params`: OTG vertical interrupt0 IRQ parameters, passed to registered
  handlers when triggered.
- `vupdate_params`: Vertical update IRQ parameters, passed to registered handlers when
  triggered.
- `dmub_trace_params`: DMUB trace event IRQ parameters, passed to registered handlers when
  triggered.
- `dmub_outbox_params`: DMUB Outbox parameters
- `irq_handler_list_table_lock`: Synchronizes access to IRQ tables
- `backlight_dev`: Backlight control device
- `backlight_link`: Link on which to control backlight
- `num_of_edps`: number of backlight eDPs
- `backlight_caps`: Capabilities of the backlight device
- `freesync_module`: Module handling freesync calculations
- `hdcp_workqueue`: AMDGPU content protection queue
- `vblank_control_workqueue`: Deferred work for vblank control events.
- `idle_workqueue`: Periodic work for idle events.
- `cached_state`: Caches device atomic state for suspend/resume
- `cached_dc_state`: Cached state of content streams
- `compressor`: Frame buffer compression buffer. See [`struct dm_compressor_info`](#c-struct-dm_compressor_info)
- `fw_dmcu`: Reference to DMCU firmware
- `dmcu_fw_version`: Version of the DMCU firmware
- `soc_bounding_box`: gpu_info FW provided soc bounding box struct or 0 if not
  available in FW
- `active_vblank_irq_count`: number of currently active vblank irqs
- `secure_display_ctx`: Store secure display relevant info. e.g. the ROI information
  , the work_struct to command dmub, etc.
- `hpd_rx_offload_wq`: Work queue to offload works of hpd_rx_irq
- `mst_encoders`: fake encoders used for DP MST.
- `force_timing_sync`: set via debugfs. When set, indicates that all connected
  displays will be forced to synchronize.
- `disable_hpd_irq`: disables all HPD and HPD RX interrupt handling in the
  driver when true
- `dmcub_trace_event_en`: enable dmcub trace events
- `da_list`: DAL fb memory allocation list, for communication with SMU.
- `dmub_aux_transfer_done`: struct completion used to indicate when DMUB
  transfers are done
- `delayed_hpd_wq`: work queue used to delay DMUB HPD work
- `brightness`: cached backlight values.
- `actual_brightness`: last successfully applied backlight values.
- `aux_hpd_discon_quirk`: quirk for hpd discon while aux is on-going.
  occurred on certain intel platform
- `edp0_on_dp1_quirk`: quirk for platforms that put edp0 on DP1.
- `dpia_aux_lock`: Guards access to DPIA AUX
- `bb_from_dmub`: Bounding box data read from dmub during early initialization for DCN4+
  Data is stored as a byte array that should be casted to the appropriate bb struct
- `oem_i2c`: OEM i2c bus
- `fused_io`: dmub fused io interface

#### <a id="c-struct-amdgpu_hdmi_vsdb_info"></a>`struct amdgpu_hdmi_vsdb_info`

Keep track of the VSDB info

**Definition**

```c
struct amdgpu_hdmi_vsdb_info {
    unsigned int amd_vsdb_version;
    bool freesync_supported;
    unsigned int min_refresh_rate_hz;
    unsigned int max_refresh_rate_hz;
    bool replay_mode;
};
```

**Members**

- `amd_vsdb_version`: Vendor Specific Data Block Version, should be
  used to determine which Vendor Specific InfoFrame (VSIF) to send.
- `freesync_supported`: FreeSync Supported.
- `min_refresh_rate_hz`: FreeSync Minimum Refresh Rate in Hz.
- `max_refresh_rate_hz`: FreeSync Maximum Refresh Rate in Hz
- `replay_mode`: Replay supported

**Description**

AMDGPU supports FreeSync over HDMI by using the VSDB section, and this
struct is useful to keep track of the display-specific information about
FreeSync.


<a id="rst-lifecycle"></a>

## Lifecycle


DM (and consequently DC) is registered in the amdgpu base driver as a IP
block. When CONFIG_DRM_AMD_DC is enabled, the DM device IP block is added to
the base driver's device list to be initialized and torn down accordingly.

The functions to do so are provided as hooks in [`struct amd_ip_funcs`](/kernel/hardware/gpu/amdgpu/driver-core.md#c-struct-amd_ip_funcs).



#### <a id="c-dm_hw_init"></a>`dm_hw_init()`

```c
int dm_hw_init(struct amdgpu_ip_block *ip_block)
```

Initialize DC device

**Parameters**

- `struct amdgpu_ip_block *ip_block`: Pointer to the amdgpu_ip_block for this hw instance.

**Description**

Initialize the [`struct amdgpu_display_manager`](#c-struct-amdgpu_display_manager) device. This involves calling
the initializers of each DM component, then populating the struct with them.

Although the function implies hardware initialization, both hardware and
software are initialized here. Splitting them out to their relevant init
hooks is a future TODO item.

Some notable things that are initialized here:

- Display Core, both software and hardware
- DC modules that we need (freesync and color management)
- DRM software states
- Interrupt sources and handlers
- Vblank support
- Debug FS entries, if enabled

#### <a id="c-dm_hw_fini"></a>`dm_hw_fini()`

```c
int dm_hw_fini(struct amdgpu_ip_block *ip_block)
```

Teardown DC device

**Parameters**

- `struct amdgpu_ip_block *ip_block`: Pointer to the amdgpu_ip_block for this hw instance.

**Description**

Teardown components within [`struct amdgpu_display_manager`](#c-struct-amdgpu_display_manager) that require
cleanup. This involves cleaning up the DRM device, DC, and any modules that
were loaded. Also flush IRQ workqueues and disable them.


<a id="rst-interrupts"></a>

## Interrupts


DM provides another layer of IRQ management on top of what the base driver
already provides. This is something that could be cleaned up, and is a
future TODO item.

The base driver provides IRQ source registration with DRM, handler
registration into the base driver's IRQ table, and a handler callback
[`amdgpu_irq_handler()`](/kernel/hardware/gpu/amdgpu/driver-core.md#c-amdgpu_irq_handler), with which DRM calls on interrupts. This generic
handler looks up the IRQ table, and calls the respective
`amdgpu_irq_src_funcs.process` hookups.

What DM provides on top are two IRQ tables specifically for top-half and
bottom-half IRQ handling, with the bottom-half implementing workqueues:

- [`amdgpu_display_manager.irq_handler_list_high_tab`](#c-struct-amdgpu_display_manager)
- [`amdgpu_display_manager.irq_handler_list_low_tab`](#c-struct-amdgpu_display_manager)

They override the base driver's IRQ table, and the effect can be seen
in the hooks that DM provides for `amdgpu_irq_src_funcs.process`. They
are all set to the DM generic handler [`amdgpu_dm_irq_handler()`](#c-amdgpu_dm_irq_handler), which looks up
DM's IRQ tables. However, in order for base driver to recognize this hook, DM
still needs to register the IRQ with the base driver. See
`dce110_register_irq_handlers()` and `dcn10_register_irq_handlers()`.

To expose DC's hardware interrupt toggle to the base driver, DM implements
`amdgpu_irq_src_funcs.set` hooks. Base driver calls it through
[`amdgpu_irq_update()`](/kernel/hardware/gpu/amdgpu/driver-core.md#c-amdgpu_irq_update) to enable or disable the interrupt.



#### <a id="c-struct-amdgpu_dm_irq_handler_data"></a>`struct amdgpu_dm_irq_handler_data`

Data for DM interrupt handlers.

**Definition**

```c
struct amdgpu_dm_irq_handler_data {
    struct list_head list;
    interrupt_handler handler;
    void *handler_arg;
    struct amdgpu_display_manager *dm;
    enum dc_irq_source irq_source;
    struct work_struct work;
};
```

**Members**

- `list`: Linked list entry referencing the next/previous handler
- `handler`: Handler function
- `handler_arg`: Argument passed to the handler when triggered
- `dm`: DM which this handler belongs to
- `irq_source`: DC interrupt source that this handler is registered for
- `work`: work struct

#### <a id="c-dm_irq_work_func"></a>`dm_irq_work_func()`

```c
void dm_irq_work_func(struct work_struct *work)
```

Handle an IRQ outside of the interrupt handler proper.

**Parameters**

- `struct work_struct *work`: work struct

#### <a id="c-unregister_all_irq_handlers"></a>`unregister_all_irq_handlers()`

```c
void unregister_all_irq_handlers(struct amdgpu_device *adev)
```

Cleans up handlers from the DM IRQ table

**Parameters**

- `struct amdgpu_device *adev`: The base driver device containing the DM device

**Description**

Go through low and high context IRQ tables and deallocate handlers.

#### <a id="c-amdgpu_dm_irq_register_interrupt"></a>`amdgpu_dm_irq_register_interrupt()`

```c
void * amdgpu_dm_irq_register_interrupt(struct amdgpu_device *adev, struct dc_interrupt_params *int_params, void (*ih)(void *), void *handler_args)
```

Register a handler within DM.

**Parameters**

- `struct amdgpu_device *adev`: The base driver device containing the DM device.
- `struct dc_interrupt_params *int_params`: Interrupt parameters containing the source, and handler context
- `void (*ih)(void *)`: Function pointer to the interrupt handler to register
- `void *handler_args`: Arguments passed to the handler when the interrupt occurs

**Description**

Register an interrupt handler for the given IRQ source, under the given
context. The context can either be high or low. High context handlers are
executed directly within ISR context, while low context is executed within a
workqueue, thereby allowing operations that sleep.

Registered handlers are called in a FIFO manner, i.e. the most recently
registered handler will be called first.

**Return**

Handler data [`struct amdgpu_dm_irq_handler_data`](#c-struct-amdgpu_dm_irq_handler_data) containing the IRQ
source, handler function, and args

#### <a id="c-amdgpu_dm_irq_unregister_interrupt"></a>`amdgpu_dm_irq_unregister_interrupt()`

```c
void amdgpu_dm_irq_unregister_interrupt(struct amdgpu_device *adev, enum dc_irq_source irq_source, void *ih)
```

Remove a handler from the DM IRQ table

**Parameters**

- `struct amdgpu_device *adev`: The base driver device containing the DM device
- `enum dc_irq_source irq_source`: IRQ source to remove the given handler from
- `void *ih`: Function pointer to the interrupt handler to unregister

**Description**

Go through both low and high context IRQ tables, and find the given handler
for the given irq source. If found, remove it. Otherwise, do nothing.

#### <a id="c-amdgpu_dm_irq_init"></a>`amdgpu_dm_irq_init()`

```c
int amdgpu_dm_irq_init(struct amdgpu_device *adev)
```

Initialize DM IRQ management

**Parameters**

- `struct amdgpu_device *adev`: The base driver device containing the DM device

**Description**

Initialize DM's high and low context IRQ tables.

The N by M table contains N IRQ sources, with M
[`struct amdgpu_dm_irq_handler_data`](#c-struct-amdgpu_dm_irq_handler_data) hooked together in a linked list. The
list_heads are initialized here. When an interrupt n is triggered, all m
handlers are called in sequence, FIFO according to registration order.

The low context table requires special steps to initialize, since handlers
will be deferred to a workqueue. See `struct irq_list_head`.

#### <a id="c-amdgpu_dm_irq_fini"></a>`amdgpu_dm_irq_fini()`

```c
void amdgpu_dm_irq_fini(struct amdgpu_device *adev)
```

Tear down DM IRQ management

**Parameters**

- `struct amdgpu_device *adev`: The base driver device containing the DM device

**Description**

Flush all work within the low context IRQ table.

#### <a id="c-amdgpu_dm_irq_handler"></a>`amdgpu_dm_irq_handler()`

```c
int amdgpu_dm_irq_handler(struct amdgpu_device *adev, struct amdgpu_irq_src *source, struct amdgpu_iv_entry *entry)
```

Generic DM IRQ handler

**Parameters**

- `struct amdgpu_device *adev`: amdgpu base driver device containing the DM device
- `struct amdgpu_irq_src *source`: Unused
- `struct amdgpu_iv_entry *entry`: Data about the triggered interrupt

**Description**

Calls all registered high irq work immediately, and schedules work for low
irq. The DM IRQ table is used to find the corresponding handlers.

#### <a id="c-amdgpu_dm_hpd_init"></a>`amdgpu_dm_hpd_init()`

```c
void amdgpu_dm_hpd_init(struct amdgpu_device *adev)
```

hpd setup callback.

**Parameters**

- `struct amdgpu_device *adev`: amdgpu_device pointer

**Description**

Setup the hpd pins used by the card (evergreen+).
Enable the pin, set the polarity, and enable the hpd interrupts.

#### <a id="c-amdgpu_dm_hpd_fini"></a>`amdgpu_dm_hpd_fini()`

```c
void amdgpu_dm_hpd_fini(struct amdgpu_device *adev)
```

hpd tear down callback.

**Parameters**

- `struct amdgpu_device *adev`: amdgpu_device pointer

**Description**

Tear down the hpd pins used by the card (evergreen+).
Disable the hpd interrupts.



#### <a id="c-dm_pflip_high_irq"></a>`dm_pflip_high_irq()`

```c
void dm_pflip_high_irq(void *interrupt_params)
```

Handle pageflip interrupt

**Parameters**

- `void *interrupt_params`: ignored

**Description**

Handles the pageflip interrupt by notifying all interested parties
that the pageflip has been completed.

#### <a id="c-dm_crtc_high_irq"></a>`dm_crtc_high_irq()`

```c
void dm_crtc_high_irq(void *interrupt_params)
```

Handles CRTC interrupt

**Parameters**

- `void *interrupt_params`: used for determining the CRTC instance

**Description**

Handles the CRTC/VSYNC interrupt by notfying DRM's VBLANK
event handler.


<a id="rst-atomic-implementation"></a>

## Atomic Implementation


*WIP*



#### <a id="c-amdgpu_dm_atomic_commit_tail"></a>`amdgpu_dm_atomic_commit_tail()`

```c
void amdgpu_dm_atomic_commit_tail(struct drm_atomic_state *state)
```

AMDgpu DM's commit tail implementation.

**Parameters**

- `struct drm_atomic_state *state`: The atomic state to commit

**Description**

This will tell DC to commit the constructed DC state from atomic_check,
programming the hardware. Any failures here implies a hardware failure, since
atomic check should have filtered anything non-kosher.

#### <a id="c-amdgpu_dm_atomic_check"></a>`amdgpu_dm_atomic_check()`

```c
int amdgpu_dm_atomic_check(struct drm_device *dev, struct drm_atomic_state *state)
```

Atomic check implementation for AMDgpu DM.

**Parameters**

- `struct drm_device *dev`: The DRM device
- `struct drm_atomic_state *state`: The atomic state to commit

**Description**

Validate that the given atomic state is programmable by DC into hardware.
This involves constructing a `struct dc_state` reflecting the new hardware
state we wish to commit, then querying DC to see if it is programmable. It's
important not to modify the existing DC state. Otherwise, atomic_check
may unexpectedly commit hardware changes.

When validating the DC state, it's important that the right locks are
acquired. For full updates case which removes/adds/updates streams on one
CRTC while flipping on another CRTC, acquiring global lock will guarantee
that any such full update commit will wait for completion of any outstanding
flip using DRMs synchronization events.

Note that DM adds the affected connectors for all CRTCs in state, when that
might not seem necessary. This is because DC stream creation requires the
DC sink, which is tied to the DRM connector state. Cleaning this up should
be possible but non-trivial - a possible TODO item.

**Return**

-Error code if validation failed.


<a id="rst-color-management-properties"></a>

## Color Management Properties


We have three types of color management in the AMD display driver.
1. the legacy [`drm_crtc`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_crtc) DEGAMMA, CTM, and GAMMA properties
2. AMD driver private color management on [`drm_plane`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_plane) and [`drm_crtc`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_crtc)
3. AMD plane color pipeline

The CRTC properties are the original color management. When they were
implemented per-plane color management was not a thing yet. Because
of that we could get away with plumbing the DEGAMMA and CTM
properties to pre-blending HW functions. This is incompatible with
per-plane color management, such as via the AMD private properties or
the new drm_plane color pipeline. The only compatible CRTC property
with per-plane color management is the GAMMA property as it is
applied post-blending.

The AMD driver private color management properties are only exposed
when the kernel is built explicitly with -DAMD_PRIVATE_COLOR. They
are temporary building blocks on the path to full-fledged [`drm_plane`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_plane)
and [`drm_crtc`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_crtc) color pipelines and lay the driver's groundwork for the
color pipelines.

The AMD plane color pipeline describes AMD's `drm_colorops` via the
[`drm_plane`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_plane)'s COLOR_PIPELINE property.

**drm_crtc Properties**

The DC interface to HW gives us the following color management blocks
per pipe (surface):

- Input gamma LUT (de-normalized)
- Input CSC (normalized)
- Surface degamma LUT (normalized)
- Surface CSC (normalized)
- Surface regamma LUT (normalized)
- Output CSC (normalized)

But these aren't a direct mapping to DRM color properties. The
current DRM interface exposes CRTC degamma, CRTC CTM and CRTC regamma
while our hardware is essentially giving:

Plane CTM -> Plane degamma -> Plane CTM -> Plane regamma -> Plane CTM

The input gamma LUT block isn't really applicable here since it
operates on the actual input data itself rather than the HW fp
representation. The input and output CSC blocks are technically
available to use as part of the DC interface but are typically used
internally by DC for conversions between color spaces. These could be
blended together with user adjustments in the future but for now
these should remain untouched.

The pipe blending also happens after these blocks so we don't
actually support any CRTC props with correct blending with multiple
planes - but we can still support CRTC color management properties in
DM in most single plane cases correctly with clever management of the
DC interface in DM.

As per DRM documentation, blocks should be in hardware bypass when
their respective property is set to NULL. A linear DGM/RGM LUT should
also considered as putting the respective block into bypass mode.

This means that the following configuration is assumed to be the
default:

Plane DGM Bypass -> Plane CTM Bypass -> Plane RGM Bypass -> ... CRTC
DGM Bypass -> CRTC CTM Bypass -> CRTC RGM Bypass

**AMD Private Color Management on drm_plane**

The AMD private color management properties on a [`drm_plane`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_plane) are:

- AMD_PLANE_DEGAMMA_LUT
- AMD_PLANE_DEGAMMA_LUT_SIZE
- AMD_PLANE_DEGAMMA_TF
- AMD_PLANE_HDR_MULT
- AMD_PLANE_CTM
- AMD_PLANE_SHAPER_LUT
- AMD_PLANE_SHAPER_LUT_SIZE
- AMD_PLANE_SHAPER_TF
- AMD_PLANE_LUT3D
- AMD_PLANE_LUT3D_SIZE
- AMD_PLANE_BLEND_LUT
- AMD_PLANE_BLEND_LUT_SIZE
- AMD_PLANE_BLEND_TF

The AMD private color management property on a [`drm_crtc`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_crtc) is:

- AMD_CRTC_REGAMMA_TF

Use of these properties is discouraged.

**AMD plane color pipeline**

The AMD [`drm_plane`](/kernel/hardware/gpu/drm-kms.md#c-struct-drm_plane) color pipeline is advertised for DCN generations
3.0 and newer. It exposes these elements in this order:

1. 1D curve colorop
2. Multiplier
3. 3x4 CTM
4. 1D curve colorop
5. 1D LUT
6. 3D LUT
7. 1D curve colorop
8. 1D LUT

The multiplier (#2) is a simple multiplier that is applied to all
channels.

The 3x4 CTM (#3) is a simple 3x4 matrix.

\#1, and #7 are non-linear to linear curves. #4 is a linear to
non-linear curve. They support sRGB, PQ, and BT.709/BT.2020 EOTFs or
their inverse.

The 1D LUTs (#5 and #8) are plain 4096 entry LUTs.

The 3DLUT (#6) is a tetrahedrally interpolated 17 cube LUT.



#### <a id="c-amdgpu_dm_init_color_mod"></a>`amdgpu_dm_init_color_mod()`

```c
void amdgpu_dm_init_color_mod(void)
```

Initialize the color module.

**Parameters**

- `void`: no arguments

**Description**

We're not using the full color module, only certain components.
Only call setup functions for components that we need.

#### <a id="c-__extract_blob_lut"></a>`__extract_blob_lut()`

```c
const struct drm_color_lut * __extract_blob_lut(const struct drm_property_blob *blob, uint32_t *size)
```

Extracts the DRM lut and lut size from a blob.

**Parameters**

- `const struct drm_property_blob *blob`: DRM color mgmt property blob
- `uint32_t *size`: lut size

**Return**

DRM LUT or NULL

#### <a id="c-__extract_blob_lut32"></a>`__extract_blob_lut32()`

```c
const struct drm_color_lut32 * __extract_blob_lut32(const struct drm_property_blob *blob, uint32_t *size)
```

Extracts the DRM lut and lut size from a blob.

**Parameters**

- `const struct drm_property_blob *blob`: DRM color mgmt property blob
- `uint32_t *size`: lut size

**Return**

DRM LUT or NULL

#### <a id="c-__is_lut_linear"></a>`__is_lut_linear()`

```c
bool __is_lut_linear(const struct drm_color_lut *lut, uint32_t size)
```

check if the given lut is a linear mapping of values

**Parameters**

- `const struct drm_color_lut *lut`: given lut to check values
- `uint32_t size`: lut size

**Description**

It is considered linear if the lut represents:
f(a) = (0xFF00/MAX_COLOR_LUT_ENTRIES-1)a; for integer a in \[0,
MAX_COLOR_LUT_ENTRIES)

**Return**

True if the given lut is a linear mapping of values, i.e. it acts like a
bypass LUT. Otherwise, false.

#### <a id="c-__drm_lut_to_dc_gamma"></a>`__drm_lut_to_dc_gamma()`

```c
void __drm_lut_to_dc_gamma(const struct drm_color_lut *lut, struct dc_gamma *gamma, bool is_legacy)
```

convert the drm_color_lut to dc_gamma.

**Parameters**

- `const struct drm_color_lut *lut`: DRM lookup table for color conversion
- `struct dc_gamma *gamma`: DC gamma to set entries
- `bool is_legacy`: legacy or atomic gamma

**Description**

The conversion depends on the size of the lut - whether or not it's legacy.

#### <a id="c-__drm_lut32_to_dc_gamma"></a>`__drm_lut32_to_dc_gamma()`

```c
void __drm_lut32_to_dc_gamma(const struct drm_color_lut32 *lut, struct dc_gamma *gamma)
```

convert the drm_color_lut to dc_gamma.

**Parameters**

- `const struct drm_color_lut32 *lut`: DRM lookup table for color conversion
- `struct dc_gamma *gamma`: DC gamma to set entries

**Description**

The conversion depends on the size of the lut - whether or not it's legacy.

#### <a id="c-__drm_ctm_to_dc_matrix"></a>`__drm_ctm_to_dc_matrix()`

```c
void __drm_ctm_to_dc_matrix(const struct drm_color_ctm *ctm, struct fixed31_32 *matrix)
```

converts a DRM CTM to a DC CSC float matrix

**Parameters**

- `const struct drm_color_ctm *ctm`: DRM color transformation matrix
- `struct fixed31_32 *matrix`: DC CSC float matrix

**Description**

The matrix needs to be a 3x4 (12 entry) matrix.

#### <a id="c-__drm_ctm_3x4_to_dc_matrix"></a>`__drm_ctm_3x4_to_dc_matrix()`

```c
void __drm_ctm_3x4_to_dc_matrix(const struct drm_color_ctm_3x4 *ctm, struct fixed31_32 *matrix)
```

converts a DRM CTM 3x4 to a DC CSC float matrix

**Parameters**

- `const struct drm_color_ctm_3x4 *ctm`: DRM color transformation matrix with 3x4 dimensions
- `struct fixed31_32 *matrix`: DC CSC float matrix

**Description**

The matrix needs to be a 3x4 (12 entry) matrix.

#### <a id="c-__set_legacy_tf"></a>`__set_legacy_tf()`

```c
int __set_legacy_tf(struct dc_transfer_func *func, const struct drm_color_lut *lut, uint32_t lut_size, bool has_rom)
```

Calculates the legacy transfer function

**Parameters**

- `struct dc_transfer_func *func`: transfer function
- `const struct drm_color_lut *lut`: lookup table that defines the color space
- `uint32_t lut_size`: size of respective lut
- `bool has_rom`: if ROM can be used for hardcoded curve

**Description**

Only for sRGB input space

**Return**

0 in case of success, -ENOMEM if fails

#### <a id="c-__set_output_tf"></a>`__set_output_tf()`

```c
int __set_output_tf(struct dc_transfer_func *func, const struct drm_color_lut *lut, uint32_t lut_size, bool has_rom)
```

calculates the output transfer function based on expected input space.

**Parameters**

- `struct dc_transfer_func *func`: transfer function
- `const struct drm_color_lut *lut`: lookup table that defines the color space
- `uint32_t lut_size`: size of respective lut
- `bool has_rom`: if ROM can be used for hardcoded curve

**Return**

0 in case of success. -ENOMEM if fails.

#### <a id="c-__set_output_tf_32"></a>`__set_output_tf_32()`

```c
int __set_output_tf_32(struct dc_transfer_func *func, const struct drm_color_lut32 *lut, uint32_t lut_size, bool has_rom)
```

calculates the output transfer function based on expected input space.

**Parameters**

- `struct dc_transfer_func *func`: transfer function
- `const struct drm_color_lut32 *lut`: lookup table that defines the color space
- `uint32_t lut_size`: size of respective lut
- `bool has_rom`: if ROM can be used for hardcoded curve

**Return**

0 in case of success. -ENOMEM if fails.

#### <a id="c-__set_input_tf"></a>`__set_input_tf()`

```c
int __set_input_tf(struct dc_color_caps *caps, struct dc_transfer_func *func, const struct drm_color_lut *lut, uint32_t lut_size)
```

calculates the input transfer function based on expected input space.

**Parameters**

- `struct dc_color_caps *caps`: dc color capabilities
- `struct dc_transfer_func *func`: transfer function
- `const struct drm_color_lut *lut`: lookup table that defines the color space
- `uint32_t lut_size`: size of respective lut.

**Return**

0 in case of success. -ENOMEM if fails.

#### <a id="c-__set_input_tf_32"></a>`__set_input_tf_32()`

```c
int __set_input_tf_32(struct dc_color_caps *caps, struct dc_transfer_func *func, const struct drm_color_lut32 *lut, uint32_t lut_size)
```

calculates the input transfer function based on expected input space.

**Parameters**

- `struct dc_color_caps *caps`: dc color capabilities
- `struct dc_transfer_func *func`: transfer function
- `const struct drm_color_lut32 *lut`: lookup table that defines the color space
- `uint32_t lut_size`: size of respective lut.

**Return**

0 in case of success. -ENOMEM if fails.

#### <a id="c-amdgpu_dm_verify_lut3d_size"></a>`amdgpu_dm_verify_lut3d_size()`

```c
int amdgpu_dm_verify_lut3d_size(struct amdgpu_device *adev, struct drm_plane_state *plane_state)
```

verifies if 3D LUT is supported and if user shaper and 3D LUTs match the hw supported size

**Parameters**

- `struct amdgpu_device *adev`: amdgpu device
- `struct drm_plane_state *plane_state`: the DRM plane state

**Description**

Verifies if pre-blending (DPP) 3D LUT is supported by the HW (DCN 2.0 or
newer) and if the user shaper and 3D LUTs match the supported size.

**Return**

0 on success. -EINVAL if lut size are invalid.

#### <a id="c-amdgpu_dm_verify_lut_sizes"></a>`amdgpu_dm_verify_lut_sizes()`

```c
int amdgpu_dm_verify_lut_sizes(const struct drm_crtc_state *crtc_state)
```

verifies if DRM luts match the hw supported sizes

**Parameters**

- `const struct drm_crtc_state *crtc_state`: the DRM CRTC state

**Description**

Verifies that the Degamma and Gamma LUTs attached to the `crtc_state`
are of the expected size.

**Return**

0 on success. -EINVAL if any lut sizes are invalid.

#### <a id="c-amdgpu_dm_check_crtc_color_mgmt"></a>`amdgpu_dm_check_crtc_color_mgmt()`

```c
int amdgpu_dm_check_crtc_color_mgmt(struct dm_crtc_state *crtc, bool check_only)
```

Check if DRM color props are programmable by DC.

**Parameters**

- `struct dm_crtc_state *crtc`: amdgpu_dm crtc state
- `bool check_only`: only check color state without update dc stream

**Description**

This function just verifies CRTC LUT sizes, if there is enough space for
output transfer function and if its parameters can be calculated by AMD
color module. It also adjusts some settings for programming CRTC degamma at
plane stage, using plane DGM block.

The RGM block is typically more fully featured and accurate across
all ASICs - DCE can't support a custom non-linear CRTC DGM.

For supporting both plane level color management and CRTC level color
management at once we have to either restrict the usage of some CRTC
properties or blend adjustments together.

**Return**

0 on success. Error code if validation fails.

#### <a id="c-amdgpu_dm_update_crtc_color_mgmt"></a>`amdgpu_dm_update_crtc_color_mgmt()`

```c
int amdgpu_dm_update_crtc_color_mgmt(struct dm_crtc_state *crtc)
```

Maps DRM color management to DC stream.

**Parameters**

- `struct dm_crtc_state *crtc`: amdgpu_dm crtc state

**Description**

With no plane level color management properties we're free to use any
of the HW blocks as long as the CRTC CTM always comes before the
CRTC RGM and after the CRTC DGM.

- The CRTC RGM block will be placed in the RGM LUT block if it is non-linear.
- The CRTC DGM block will be placed in the DGM LUT block if it is non-linear.
- The CRTC CTM will be placed in the gamut remap block if it is non-linear.

The RGM block is typically more fully featured and accurate across
all ASICs - DCE can't support a custom non-linear CRTC DGM.

For supporting both plane level color management and CRTC level color
management at once we have to either restrict the usage of CRTC properties
or blend adjustments together.

**Return**

0 on success. Error code if setup fails.

#### <a id="c-amdgpu_dm_update_plane_color_mgmt"></a>`amdgpu_dm_update_plane_color_mgmt()`

```c
int amdgpu_dm_update_plane_color_mgmt(struct dm_crtc_state *crtc, struct drm_plane_state *plane_state, struct dc_plane_state *dc_plane_state)
```

Maps DRM color management to DC plane.

**Parameters**

- `struct dm_crtc_state *crtc`: amdgpu_dm crtc state
- `struct drm_plane_state *plane_state`: DRM plane state
- `struct dc_plane_state *dc_plane_state`: target DC surface

**Description**

Update the underlying dc_stream_state's input transfer function (ITF) in
preparation for hardware commit. The transfer function used depends on
the preparation done on the stream for color management.

**Return**

0 on success. -ENOMEM if mem allocation fails.


<a id="rst-dc-color-capabilities-between-dcn-generations"></a>

### DC Color Capabilities between DCN generations

DRM/KMS framework defines three CRTC color correction properties: degamma, color transformation matrix (CTM) and gamma, and two properties for degamma and gamma LUT sizes. AMD DC programs some of the color correction features pre-blending but DRM/KMS has not per-plane color correction properties.

In general, the DRM CRTC color properties are programmed to DC, as follows: CRTC gamma after blending, and CRTC degamma pre-blending. Although CTM is programmed after blending, it is mapped to DPP hw blocks (pre-blending). Other color caps available in the hw is not currently exposed by DRM interface and are bypassed.


**Color management caps (DPP and MPC)**

Modules/color calculates various color operations which are translated to
abstracted HW. DCE 5-12 had almost no important changes, but starting with
DCN1, every new generation comes with fairly major differences in color
pipeline. Therefore, we abstract color pipe capabilities so modules/DM can
decide mapping to HW block based on logical capabilities.



#### <a id="c-MAX_SURFACES"></a>`MAX_SURFACES`

```c
MAX_SURFACES
```

representative of the upper bound of surfaces that can be piped to a single CRTC

#### <a id="c-MAX_PLANES"></a>`MAX_PLANES`

```c
MAX_PLANES
```

representative of the upper bound of planes that are supported by the HW

#### <a id="c-struct-rom_curve_caps"></a>`struct rom_curve_caps`

predefined transfer function caps for degamma and regamma

**Definition**

```c
struct rom_curve_caps {
    uint16_t srgb : 1;
    uint16_t bt2020 : 1;
    uint16_t gamma2_2 : 1;
    uint16_t pq : 1;
    uint16_t hlg : 1;
};
```

**Members**

- `srgb`: RGB color space transfer func
- `bt2020`: BT.2020 transfer func
- `gamma2_2`: standard gamma
- `pq`: perceptual quantizer transfer function
- `hlg`: hybrid log–gamma transfer function

#### <a id="c-struct-dpp_color_caps"></a>`struct dpp_color_caps`

color pipeline capabilities for display pipe and plane blocks

**Definition**

```c
struct dpp_color_caps {
    uint16_t dcn_arch : 1;
    uint16_t input_lut_shared : 1;
    uint16_t icsc : 1;
    uint16_t dgam_ram : 1;
    uint16_t post_csc : 1;
    uint16_t gamma_corr : 1;
    uint16_t hw_3d_lut : 1;
    uint16_t ogam_ram : 1;
    uint16_t ocsc : 1;
    uint16_t dgam_rom_for_yuv : 1;
    struct rom_curve_caps dgam_rom_caps;
    struct rom_curve_caps ogam_rom_caps;
};
```

**Members**

- `dcn_arch`: all DCE generations treated the same
- `input_lut_shared`: shared with DGAM. Input LUT is different than most LUTs,
  just plain 256-entry lookup
- `icsc`: input color space conversion
- `dgam_ram`: programmable degamma LUT
- `post_csc`: post color space conversion, before gamut remap
- `gamma_corr`: degamma correction
- `hw_3d_lut`: 3D LUT support. It implies a shaper LUT before. It may be shared
  with MPC by setting mpc:shared_3d_lut flag
- `ogam_ram`: programmable out/blend gamma LUT
- `ocsc`: output color space conversion
- `dgam_rom_for_yuv`: pre-defined degamma LUT for YUV planes
- `dgam_rom_caps`: pre-definied curve caps for degamma 1D LUT
- `ogam_rom_caps`: pre-definied curve caps for regamma 1D LUT

**Note**

hdr_mult and gamut remap (CTM) are always available in DPP (in that order)

#### <a id="c-struct-mpc_color_caps"></a>`struct mpc_color_caps`

color pipeline capabilities for multiple pipe and plane combined blocks

**Definition**

```c
struct mpc_color_caps {
    uint16_t gamut_remap : 1;
    uint16_t ogam_ram : 1;
    uint16_t ocsc : 1;
    uint16_t num_3dluts : 3;
    uint16_t num_rmcm_3dluts : 3;
    uint16_t shared_3d_lut:1;
    struct rom_curve_caps ogam_rom_caps;
    struct lut3d_caps mcm_3d_lut_caps;
    struct lut3d_caps rmcm_3d_lut_caps;
    bool preblend;
};
```

**Members**

- `gamut_remap`: color transformation matrix
- `ogam_ram`: programmable out gamma LUT
- `ocsc`: output color space conversion matrix
- `num_3dluts`: MPC 3D LUT; always assumes a preceding shaper LUT
- `num_rmcm_3dluts`: number of RMCM 3D LUTS; always assumes a preceding shaper LUT
- `shared_3d_lut`: shared 3D LUT flag. Can be either DPP or MPC, but single
  instance
- `ogam_rom_caps`: pre-definied curve caps for regamma 1D LUT
- `mcm_3d_lut_caps`: HW support cap for MCM LUT memory
- `rmcm_3d_lut_caps`: HW support cap for RMCM LUT memory
- `preblend`: whether color manager supports preblend with MPC

#### <a id="c-struct-dc_color_caps"></a>`struct dc_color_caps`

color pipes capabilities for DPP and MPC hw blocks

**Definition**

```c
struct dc_color_caps {
    struct dpp_color_caps dpp;
    struct mpc_color_caps mpc;
};
```

**Members**

- `dpp`: color pipes caps for DPP
- `mpc`: color pipes caps for MPC

#### <a id="c-enum-pipe_split_policy"></a>`enum pipe_split_policy`

Pipe split strategy supported by DCN

**Constants**

- `MPC_SPLIT_DYNAMIC`: DC will automatically decide how to split the
  pipe in order to bring the best trade-off between performance and
  power consumption. This is the recommended option.
- `MPC_SPLIT_AVOID`: Avoid pipe split, which means that DC will not
  try any sort of split optimization.
- `MPC_SPLIT_AVOID_MULT_DISP`: With this option, DC will only try to
  optimize the pipe utilization when using a single display; if the
  user connects to a second display, DC will avoid pipe split.

**Description**

This enum is used to define the pipe split policy supported by DCN. By
default, DC favors MPC_SPLIT_DYNAMIC.

#### <a id="c-struct-dc_validation_set"></a>`struct dc_validation_set`

Struct to store surface/stream associations for validation

**Definition**

```c
struct dc_validation_set {
    struct dc_stream_state *stream;
    struct dc_plane_state *plane_states[MAX_SURFACES];
    uint8_t plane_count;
};
```

**Members**

- `stream`: Stream state properties
- `plane_states`: Surface state
- `plane_count`: Total of active planes

#### <a id="c-dc_get_underflow_debug_data_for_otg"></a>`dc_get_underflow_debug_data_for_otg()`

```c
void dc_get_underflow_debug_data_for_otg(struct dc *dc, int primary_otg_inst, struct dc_underflow_debug_data *out_data)
```

Retrieve underflow debug data.

**Parameters**

- `struct dc *dc`: Pointer to the display core context.
- `int primary_otg_inst`: Instance index of the primary OTG that underflowed.
- `struct dc_underflow_debug_data *out_data`: Pointer to a dc_underflow_debug_data struct to be filled with debug information.

**Description**

This function collects and logs underflow-related HW states when underflow happens,
including OTG underflow status, current read positions, frame count, and per-HUBP debug data.
The results are stored in the provided out_data structure for further analysis or logging.

#### <a id="c-dc_capture_register_software_state"></a>`dc_capture_register_software_state()`

```c
bool dc_capture_register_software_state(struct dc *dc, struct dc_register_software_state *state)
```

Capture software state for register programming

**Parameters**

- `struct dc *dc`: DC context containing current display configuration
- `struct dc_register_software_state *state`: Pointer to dc_register_software_state structure to populate

**Description**

Extracts all software state variables that are used to program hardware register
fields across the display driver pipeline. This provides a complete snapshot
of the software configuration that drives hardware register programming.

The function traverses the DC context and extracts values from:
- Stream configurations (timing, format, DSC settings)
- Plane states (surface format, rotation, scaling, cursor)
- Pipe contexts (resource allocation, blending, viewport)
- Clock manager (display clocks, DPP clocks, pixel clocks)
- Resource context (DET buffer allocation, ODM configuration)

This is essential for underflow debugging as it captures the exact software
state that determines how registers are programmed, allowing analysis of
whether underflow is caused by incorrect register programming or timing issues.

**Return**

true if state was successfully captured, false on error

#### <a id="c-dc_get_qos_info"></a>`dc_get_qos_info()`

```c
bool dc_get_qos_info(struct dc *dc, struct dc_qos_info *info)
```

Retrieve Quality of Service (QoS) information from display core

**Parameters**

- `struct dc *dc`: DC context containing current display configuration
- `struct dc_qos_info *info`: Pointer to dc_qos_info structure to populate with QoS metrics

**Description**

This function retrieves QoS metrics from the display core that can be used by
benchmark tools to analyze display system performance. The function may take
several milliseconds to execute due to hardware measurement requirements.

QoS information includes:
- Bandwidth bounds (lower limits in Mbps)
- Latency bounds (upper limits in nanoseconds)
- Hardware-measured bandwidth metrics (peak/average in Mbps)
- Hardware-measured latency metrics (maximum/average in nanoseconds)

The function will populate the provided dc_qos_info structure with current
QoS measurements. If hardware measurement functions are not available for
the current DCN version, the function returns false with zero'd info structure.

**Return**

true if QoS information was successfully retrieved, false if measurement
functions are unavailable or hardware measurements cannot be performed


The color pipeline has undergone major changes between DCN hardware generations. What's possible to do before and after blending depends on hardware capabilities, as illustrated below by the DCN 2.0 and DCN 3.0 families schemas.

**DCN 2.0 family color caps and mapping**

![](/kernel/hardware/gpu/amdgpu-display/asset-84c92f54781d-dcn2-cm-drm-current.svg)

**DCN 3.0 family color caps and mapping**

![](/kernel/hardware/gpu/amdgpu-display/asset-79f499949536-dcn3-cm-drm-current.svg)

<a id="rst-blend-mode-properties"></a>

## Blend Mode Properties

Pixel blend mode is a DRM plane composition property of `drm_plane` used to describes how pixels from a foreground plane (fg) are composited with the background plane (bg). Here, we present main concepts of DRM blend mode to help to understand how this property is mapped to AMD DC interface. See more about this DRM property and the alpha blending equations in [DRM Plane Composition Properties](<https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/Documentation/gpu/drm-kms.rst?id=9021cc14f7d98b4a1d2c932f52c5343d4d0f6b92>).

Basically, a blend mode sets the alpha blending equation for plane composition that fits the mode in which the alpha channel affects the state of pixel color values and, therefore, the resulted pixel color. For example, consider the following elements of the alpha blending equation:

- *fg.rgb*: Each of the RGB component values from the foreground's pixel.

- *fg.alpha*: Alpha component value from the foreground's pixel.

- *bg.rgb*: Each of the RGB component values from the background.

- *plane_alpha*: Plane alpha value set by the **plane "alpha" property**, see more in [DRM Plane Composition Properties](<https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/Documentation/gpu/drm-kms.rst?id=9021cc14f7d98b4a1d2c932f52c5343d4d0f6b92>).

in the basic alpha blending equation:



```text
out.rgb = alpha * fg.rgb + (1 - alpha) * bg.rgb
```

the alpha channel value of each pixel in a plane is ignored and only the plane alpha affects the resulted pixel color values.

DRM has three blend mode to define the blend formula in the plane composition:

- **None**: Blend formula that ignores the pixel alpha.

- **Pre-multiplied**: Blend formula that assumes the pixel color values in a plane was already pre-multiplied by its own alpha channel before storage.

- **Coverage**: Blend formula that assumes the pixel color values were not pre-multiplied with the alpha channel values.

and pre-multiplied is the default pixel blend mode, that means, when no blend mode property is created or defined, DRM considers the plane's pixels has pre-multiplied color values. On IGT GPU tools, the kms_plane_alpha_blend test provides a set of subtests to verify plane alpha and blend mode properties.

The DRM blend mode and its elements are then mapped by AMDGPU display manager (DM) to program the blending configuration of the Multiple Pipe/Plane Combined (MPC), as follows:




Therefore, the blending configuration for a single MPCC instance on the MPC tree is defined by `mpcc_blnd_cfg`, where `pre_multiplied_alpha` is the alpha pre-multiplied mode flag used to set `MPCC_ALPHA_MULTIPLIED_MODE`. It controls whether alpha is multiplied (true/false), being only true for DRM pre-multiplied blend mode. `mpcc_alpha_blend_mode` defines the alpha blend mode regarding pixel alpha and plane alpha values. It sets one of the three modes for `MPCC_ALPHA_BLND_MODE`, as described below.




DM then maps the elements of `enum mpcc_alpha_blend_mode` to those in the DRM blend formula, as follows:

- *MPC pixel alpha* matches *DRM fg.alpha* as the alpha component value from the plane's pixel

- *MPC global alpha* matches *DRM plane_alpha* when the pixel alpha should be ignored and, therefore, pixel values are not pre-multiplied

- *MPC global gain* assumes *MPC global alpha* value when both *DRM fg.alpha* and *DRM plane_alpha* participate in the blend equation

In short, *fg.alpha* is ignored by selecting `MPCC_ALPHA_BLEND_MODE_GLOBAL_ALPHA`. On the other hand, (plane_alpha \* fg.alpha) component becomes available by selecting `MPCC_ALPHA_BLEND_MODE_PER_PIXEL_ALPHA_COMBINED_GLOBAL_GAIN`. And the `MPCC_ALPHA_MULTIPLIED_MODE` defines if the pixel color values are pre-multiplied by alpha or not.

<a id="rst-blend-configuration-flow"></a>

### Blend configuration flow

The alpha blending equation is configured from DRM to DC interface by the following path:

1. When updating a `drm_plane_state <drm_plane_state>`, DM calls `amdgpu_dm_plane_fill_blending_from_plane_state()` that maps `drm_plane_state <drm_plane_state>` attributes to `dc_plane_info <dc_plane_info>` struct to be handled in the OS-agnostic component (DC).

2. On DC interface, `struct mpcc_blnd_cfg <mpcc_blnd_cfg>` programs the MPCC blend configuration considering the `dc_plane_info <dc_plane_info>` input from DPP.

---

# Multiplane Overlay (MPO)

_Peios Kernel / Hardware and drivers / Graphics / amdgpu / display_

> Multiplane Overlay (MPO) allows for multiple framebuffers to be composited via fixed-function hardware in the display controller rather than using graphics or compute shaders for composition. This can yield some power savings if it means…

<a id="rst-multiplane-overlay-mpo"></a>

> [!NOTE]
>
> You will get more from this page if you have already read the '[Documentation/gpu/amdgpu/display/dcn-overview.rst](/kernel/hardware/gpu/amdgpu-display/dcn-overview.md)'.

Multiplane Overlay (MPO) allows for multiple framebuffers to be composited via fixed-function hardware in the display controller rather than using graphics or compute shaders for composition. This can yield some power savings if it means the graphics/compute pipelines can be put into low-power states. In summary, MPO can bring the following benefits:

- Decreased GPU and CPU workload - no composition shaders needed, no extra buffer copy needed, GPU can remain idle.

- Plane independent page flips - No need to be tied to global compositor page-flip present rate, reduced latency, independent timing.

> [!NOTE]
>
> Keep in mind that MPO is all about power-saving; if you want to learn more about power-save in the display context, check the link: [Power](<https://gitlab.freedesktop.org/pq/color-and-hdr/-/blob/main/doc/power.rst>).

Multiplane Overlay is only available using the DRM atomic model. The atomic model only uses a single userspace IOCTL for configuring the display hardware (modesetting, page-flipping, etc) - drmModeAtomicCommit. To query hardware resources and limitations userspace also calls into drmModeGetResources which reports back the number of planes, CRTCs, and connectors. There are three types of DRM planes that the driver can register and work with:

- `DRM_PLANE_TYPE_PRIMARY`: Primary planes represent a "main" plane for a CRTC, primary planes are the planes operated upon by CRTC modesetting and flipping operations.

- `DRM_PLANE_TYPE_CURSOR`: Cursor planes represent a "cursor" plane for a CRTC. Cursor planes are the planes operated upon by the cursor IOCTLs

- `DRM_PLANE_TYPE_OVERLAY`: Overlay planes represent all non-primary, non-cursor planes. Some drivers refer to these types of planes as "sprites" internally.

To illustrate how it works, let's take a look at a device that exposes the following planes to userspace:

- 4 Primary planes (1 per CRTC).

- 4 Cursor planes (1 per CRTC).

- 1 Overlay plane (shared among CRTCs).

> [!NOTE]
>
> Keep in mind that different ASICs might expose other numbers of planes.

For this hardware example, we have 4 pipes (if you don't know what AMD pipe means, look at '[Documentation/gpu/amdgpu/display/dcn-overview.rst](/kernel/hardware/gpu/amdgpu-display/dcn-overview.md)', section "AMD Hardware Pipeline"). Typically most AMD devices operate in a pipe-split configuration for optimal single display output (e.g., 2 pipes per plane).

A typical MPO configuration from userspace - 1 primary + 1 overlay on a single display - will see 4 pipes in use, 2 per plane.

At least 1 pipe must be used per plane (primary and overlay), so for this hypothetical hardware that we are using as an example, we have an absolute limit of 4 planes across all CRTCs. Atomic commits will be rejected for display configurations using more than 4 planes. Again, it is important to stress that every DCN has different restrictions; here, we are just trying to provide the concept idea.

<a id="rst-plane-restrictions"></a>

## Plane Restrictions

AMDGPU imposes restrictions on the use of DRM planes in the driver.

Atomic commits will be rejected for commits which do not follow these restrictions:

- Overlay planes must be in ARGB8888 or XRGB8888 format

- Planes cannot be placed outside of the CRTC destination rectangle

- Planes cannot be downscaled more than 1/4x of their original size

- Planes cannot be upscaled more than 16x of their original size

Not every property is available on every plane:

- Only primary planes have color-space and non-RGB format support

- Only overlay planes have alpha blending support

<a id="rst-cursor-restrictions"></a>

## Cursor Restrictions

Before we start to describe some restrictions around cursor and MPO, see the below image:

![](/kernel/hardware/gpu/amdgpu-display/asset-e6aae9c8e242-mpo-cursor.svg)

The image on the left side represents how DRM expects the cursor and planes to be blended. However, AMD hardware handles cursors differently, as you can see on the right side; basically, our cursor cannot be drawn outside its associated plane as it is being treated as part of the plane. Another consequence of that is that cursors inherit the color and scale from the plane.

As a result of the above behavior, do not use legacy API to set up the cursor plane when working with MPO; otherwise, you might encounter unexpected behavior.

In short, AMD HW has no dedicated cursor planes. A cursor is attached to another plane and therefore inherits any scaling or color processing from its parent plane.

<a id="rst-use-cases"></a>

## Use Cases

<a id="rst-picture-in-picture-pip-playback-underlay-strategy"></a>

### Picture-in-Picture (PIP) playback - Underlay strategy

Video playback should be done using the "primary plane as underlay" MPO strategy. This is a 2 planes configuration:

- 1 YUV DRM Primary Plane (e.g. NV12 Video)

- 1 RGBA DRM Overlay Plane (e.g. ARGB8888 desktop). The compositor should prepare the framebuffers for the planes as follows: - The overlay plane contains general desktop UI, video player controls, and video subtitles - Primary plane contains one or more videos

> [!NOTE]
>
> Keep in mind that we could extend this configuration to more planes, but that is currently not supported by our driver yet (maybe if we have a userspace request in the future, we can change that).

See below a single-video example:

![](/kernel/hardware/gpu/amdgpu-display/asset-48f0eff44d42-single-display-mpo.svg)

> [!NOTE]
>
> We could extend this behavior to more planes, but that is currently not supported by our driver.

The video buffer should be used directly for the primary plane. The video can be scaled and positioned for the desktop using the properties: CRTC_X, CRTC_Y, CRTC_W, and CRTC_H. The primary plane should also have the color encoding and color range properties set based on the source content:

- `COLOR_RANGE`, `COLOR_ENCODING`

The overlay plane should be the native size of the CRTC. The compositor must draw a transparent cutout for where the video should be placed on the desktop (i.e., set the alpha to zero). The primary plane video will be visible through the underlay. The overlay plane's buffer may remain static while the primary plane's framebuffer is used for standard double-buffered playback.

The compositor should create a YUV buffer matching the native size of the CRTC. Each video buffer should be composited onto this YUV buffer for direct YUV scanout. The primary plane should have the color encoding and color range properties set based on the source content: `COLOR_RANGE`, `COLOR_ENCODING`. However, be mindful that the source color space and encoding match for each video since it affect the entire plane.

The overlay plane should be the native size of the CRTC. The compositor must draw a transparent cutout for where each video should be placed on the desktop (i.e., set the alpha to zero). The primary plane videos will be visible through the underlay. The overlay plane's buffer may remain static while compositing operations for video playback will be done on the video buffer.

This kernel interface is validated using IGT GPU Tools. The following tests can be run to validate positioning, blending, scaling under a variety of sequences and interactions with operations such as DPMS and S3:

- `kms_plane@plane-panning-bottom-right-pipe-*-planes`

- `kms_plane@plane-panning-bottom-right-suspend-pipe-*-`

- `kms_plane@plane-panning-top-left-pipe-*-`

- `kms_plane@plane-position-covered-pipe-*-`

- `kms_plane@plane-position-hole-dpms-pipe-*-`

- `kms_plane@plane-position-hole-pipe-*-`

- `kms_plane_multiple@atomic-pipe-*-tiling-`

- `kms_plane_scaling@pipe-*-plane-scaling`

- `kms_plane_alpha_blend@pipe-*-alpha-basic`

- `kms_plane_alpha_blend@pipe-*-alpha-transparant-fb`

- `kms_plane_alpha_blend@pipe-*-alpha-opaque-fb`

- `kms_plane_alpha_blend@pipe-*-constant-alpha-min`

- `kms_plane_alpha_blend@pipe-*-constant-alpha-mid`

- `kms_plane_alpha_blend@pipe-*-constant-alpha-max`

<a id="rst-multiple-display-mpo"></a>

### Multiple Display MPO

AMDGPU supports display MPO when using multiple displays; however, this feature behavior heavily relies on the compositor implementation. Keep in mind that userspace can define different policies. For example, some OSes can use MPO to protect the plane that handles the video playback; notice that we don't have many limitations for a single display. Nonetheless, this manipulation can have many more restrictions for a multi-display scenario. The below example shows a video playback in the middle of two displays, and it is up to the compositor to define a policy on how to handle it:

![](/kernel/hardware/gpu/amdgpu-display/asset-3725af5691c3-multi-display-hdcp-mpo.svg)

Let's discuss some of the hardware limitations we have when dealing with multi-display with MPO.

<a id="rst-limitations"></a>

#### Limitations

For simplicity's sake, for discussing the hardware limitation, this documentation supposes an example where we have two displays and video playback that will be moved around different displays.

- **Hardware limitations**

From the DCN overview page, each display requires at least one pipe and each MPO plane needs another pipe. As a result, when the video is in the middle of the two displays, we need to use 2 pipes. See the example below where we avoid pipe split:

- 1 display (1 pipe) + MPO (1 pipe), we will use two pipes

- 2 displays (2 pipes) + MPO (1-2 pipes); we will use 4 pipes. MPO in the middle of both displays needs 2 pipes.

- 3 Displays (3 pipes) + MPO (1-2 pipes), we need 5 pipes.

If we use MPO with multiple displays, the userspace has to decide to enable multiple MPO by the price of limiting the number of external displays supported or disable it in favor of multiple displays; it is a policy decision. For example:

- When ASIC has 3 pipes, AMD hardware can NOT support 2 displays with MPO

- When ASIC has 4 pipes, AMD hardware can NOT support 3 displays with MPO

Let's briefly explore how userspace can handle these two display configurations on an ASIC that only supports three pipes. We can have:

![](/kernel/hardware/gpu/amdgpu-display/asset-1cc23e0bbe71-multi-display-hdcp-mpo-less-pipe-ex.svg)

- Total pipes are 3

- User lights up 2 displays (2 out of 3 pipes are used)

- User launches video (1 pipe used for MPO)

- Now, if the user moves the video in the middle of 2 displays, one part of the video won't be MPO since we have used 3/3 pipes.

- **Scaling limitation**

MPO cannot handle scaling less than 0.25 and more than x16. For example:

If 4k video (3840x2160) is playing in windowed mode, the physical size of the window cannot be smaller than (960x540).

> [!NOTE]
>
> These scaling limitations might vary from ASIC to ASIC.

- **Size Limitation**

The minimum MPO size is 12px.

---

# DC Programming Model

_Peios Kernel / Hardware and drivers / Graphics / amdgpu / display_

> In the Display Core Next (DCN) <dcn_overview> and DCN Block <dcn_blocks> pages, you learned about the hardware components and how they interact with each other. On this page, the focus is shifted to the display code architecture. Hence, it…

<a id="rst-dc-programming-model"></a>

In the [Display Core Next (DCN)](</kernel/hardware/gpu/amdgpu-display/dcn-overview.md#rst-dcn-overview>) and [DCN Block](</kernel/hardware/gpu/amdgpu-display/dcn-blocks.md#rst-dcn-blocks>) pages, you learned about the hardware components and how they interact with each other. On this page, the focus is shifted to the display code architecture. Hence, it is reasonable to remind the reader that the code in DC is shared with other OSes; for this reason, DC provides a set of abstractions and operations to connect different APIs with the hardware configuration. See DC as a service available for a Display Manager (amdgpu_dm) to access and configure DCN/DCE hardware (DCE is also part of DC, but for simplicity's sake, this documentation only examines DCN).

> [!NOTE]
>
> For this page, we will use the term GPU to refers to dGPU and APU.

<a id="rst-overview"></a>

## Overview

From the display hardware perspective, it is plausible to expect that if a problem is well-defined, it will probably be implemented at the hardware level. On the other hand, when there are multiple ways of achieving something without a very well-defined scope, the solution is usually implemented as a policy at the DC level. In other words, some policies are defined in the DC core (resource management, power optimization, image quality, etc.), and the others implemented in hardware are enabled via DC configuration.

In terms of hardware management, DCN has multiple instances of the same block (e.g., HUBP, DPP, MPC, etc), and during the driver execution, it might be necessary to use some of these instances. The core has policies in place for handling those instances. Regarding resource management, the DC objective is quite simple: minimize the hardware shuffle when the driver performs some actions. When the state changes from A to B, the transition is considered easier to maneuver if the hardware resource is still used for the same set of driver objects. Usually, adding and removing a resource to a `pipe_ctx` (more details below) is not a problem; however, moving a resource from one `pipe_ctx` to another should be avoided.

Another area of influence for DC is power optimization, which has a myriad of arrangement possibilities. In some way, just displaying an image via DCN should be relatively straightforward; however, showing it with the best power footprint is more desirable, but it has many associated challenges. Unfortunately, there is no straight-forward analytic way to determine if a configuration is the best one for the context due to the enormous variety of variables related to this problem (e.g., many different DCN/DCE hardware versions, different displays configurations, etc.) for this reason DC implements a dedicated library for trying some configuration and verify if it is possible to support it or not. This type of policy is extremely complex to create and maintain, and amdgpu driver relies on Display Mode Library (DML) to generate the best decisions.

In summary, DC must deal with the complexity of handling multiple scenarios and determine policies to manage them. All of the above information is conveyed to give the reader some idea about the complexity of driving a display from the driver's perspective. This page hopes to allow the reader to better navigate over the amdgpu display code.

<a id="rst-display-driver-architecture-overview"></a>

## Display Driver Architecture Overview

The diagram below provides an overview of the display driver architecture; notice it illustrates the software layers adopted by DC:

![](/kernel/hardware/gpu/amdgpu-display/asset-a94e0af99ed8-dc-components.svg)

The first layer of the diagram is the high-level DC API represented by the `dc.h` file; below it are two big blocks represented by Core and Link. Next is the hardware configuration block; the main file describing it is the\`hw_sequencer.h\`, where the implementation of the callbacks can be found in the hardware sequencer folder. Almost at the end, you can see the block level API (`dc/inc/hw`), which represents each DCN low-level block, such as HUBP, DPP, MPC, OPTC, etc. Notice on the left side of the diagram that we have a different set of layers representing the interaction with the DMUB microcontroller.

<a id="rst-basic-objects"></a>

### Basic Objects

The below diagram outlines the basic display objects. In particular, pay attention to the names in the boxes since they represent a data structure in the driver:

![](/kernel/hardware/gpu/amdgpu-display/asset-083b52be089e-dc-arch-overview.svg)

Let's start with the central block in the image, `dc`. The `dc` struct is initialized per GPU; for example, one GPU has one `dc` instance, two GPUs have two `dc` instances, and so forth. In other words we have one 'dc' per 'amdgpu' instance. In some ways, this object behaves like the `Singleton` pattern.

After the `dc` block in the diagram, you can see the `dc_link` component, which is a low-level abstraction for the connector. One interesting aspect of the image is that connectors are not part of the DCN block; they are defined by the platform/board and not by the SoC. The `dc_link` struct is the high-level data container with information such as connected sinks, connection status, signal types, etc. After `dc_link`, there is the `dc_sink`, which is the object that represents the connected display.

> [!NOTE]
>
> For historical reasons, we used the name `dc_link`, which gives the wrong impression that this abstraction only deals with physical connections that the developer can easily manipulate. However, this also covers connections like eDP or cases where the output is connected to other devices.

There are two structs that are not represented in the diagram since they were elaborated in the DCN overview page  (check the DCN block diagram [Display Core Next (DCN)](</kernel/hardware/gpu/amdgpu-display/dcn-overview.md#rst-dcn-overview>)); still, it is worth bringing back for this overview which is `dc_stream` and `dc_state`. The `dc_stream` stores many properties associated with the data transmission, but most importantly, it represents the data flow from the connector to the display. Next we have `dc_state`, which represents the logic state within the hardware at the moment; `dc_state` is composed of `dc_stream` and `dc_plane`. The `dc_stream` is the DC version of `drm_crtc` and represents the post-blending pipeline.

Speaking of the `dc_plane` data structure (first part of the diagram), you can think about it as an abstraction similar to `drm_plane` that represents the pre-blending portion of the pipeline. This image was probably processed by GFX and is ready to be composited under a `dc_stream`. Normally, the driver may have one or more `dc_plane` connected to the same `dc_stream`, which defines a composition at the DC level.

<a id="rst-basic-operations"></a>

### Basic Operations

Now that we have covered the basic objects, it is time to examine some of the basic hardware/software operations. Let's start with the `dc_create()` function, which directly works with the `dc` data struct; this function behaves like a constructor responsible for the basic software initialization and preparing for enabling other parts of the API. It is important to highlight that this operation does not touch any hardware configuration; it is only a software initialization.

Next, we have the `dc_hardware_init()`, which also relies on the `dc` data struct. Its main function is to put the hardware in a valid state. It is worth highlighting that the hardware might initialize in an unknown state, and it is a requirement to put it in a valid state; this function has multiple callbacks for the hardware-specific initialization, whereas `dc_hardware_init` does the hardware initialization and is the first point where we touch hardware.

The `dc_get_link_at_index` is an operation that depends on the `dc_link` data structure. This function retrieves and enumerates all the `dc_links` available on the device; this is required since this information is not part of the SoC definition but depends on the board configuration. As soon as the `dc_link` is initialized, it is useful to figure out if any of them are already connected to the display by using the `dc_link_detect()` function. After the driver figures out if any display is connected to the device, the challenging phase starts: configuring the monitor to show something. Nonetheless, dealing with the ideal configuration is not a DC task since this is the Display Manager (`amdgpu_dm`) responsibility which in turn is responsible for dealing with the atomic commits. The only interface DC provides to the configuration phase is the function `dc_validate_with_context` that receives the configuration information and, based on that, validates whether the hardware can support it or not. It is important to add that even if the display supports some specific configuration, it does not mean the DCN hardware can support it.

After the DM and DC agree upon the configuration, the stream configuration phase starts. This task activates one or more `dc_stream` at this phase, and in the best-case scenario, you might be able to turn the display on with a black screen (it does not show anything yet since it does not have any plane associated with it). The final step would be to call the `dc_update_planes_and_stream,` which will add or remove planes.

---

# Single-display MPO with multiple videos

_Peios Kernel / Hardware and drivers / Graphics / amdgpu / display_

> Retained AMD display diagram showing multiple video planes on one display.

![Single-display MPO with multiple videos](/kernel/hardware/gpu/amdgpu-display/asset-single-display-mpo-multi-video.svg)

---

# drm/amdgpu - Graphics and Compute (GC)

_Peios Kernel / Hardware and drivers / Graphics / amdgpu / gc_

> The relationship between the CPU and GPU can be described as the producer-consumer problem, where the CPU fills out a buffer with operations (producer) to be executed by the GPU (consumer). The requested operations in the buffer are called…

<a id="rst-drm-amdgpu-graphics-and-compute-gc"></a>
<a id="rst-amdgpu-gc"></a>

The relationship between the CPU and GPU can be described as the producer-consumer problem, where the CPU fills out a buffer with operations (producer) to be executed by the GPU (consumer). The requested operations in the buffer are called **Command Packets**, which can be summarized as a compressed way of transmitting command information to the graphics controller.

The component that acts as the front end between the CPU and the GPU is called **Command Processor (CP)**. This component is responsible for providing greater flexibility to the **Graphics and Compute (GC)** since CP makes it possible to program various aspects of the GPU pipeline. CP also coordinates the communication between the CPU and GPU via a mechanism named **Ring Buffers**, where the CPU appends information to the buffer while the GPU removes operations. CP is also responsible for handling **Indirect Buffers (IB)**.

For reference, internally the CP consists of several sub-blocks (CPC - CP compute, CPG - CP graphics, and CPF - CP fetcher). Some of these acronyms appear in register names, but this is more of an implementation detail and not something that directly impacts driver programming or debugging.

<a id="rst-graphics-gfx-and-compute-microcontrollers"></a>

## Graphics (GFX) and Compute Microcontrollers

GC is a large block, and as a result, it has multiple firmware associated with it. Some of them are:

- **CP (Command Processor)**

  The name for the hardware block that encompasses the front end of the GFX/Compute pipeline. Consists mainly of a bunch of microcontrollers (PFP, ME, CE, MEC). The firmware that runs on these microcontrollers provides the driver interface to interact with the GFX/Compute engine.

  - **MEC (MicroEngine Compute)**

    This is the microcontroller that controls the compute queues on the GFX/compute engine.

  - **MES (MicroEngine Scheduler)**

    This is the engine for managing queues. For more details check [MicroEngine Scheduler (MES)](</kernel/hardware/gpu/amdgpu-gc/mes.md#rst-amdgpu-mes>).

- **RLC (RunList Controller)**

  This is another microcontroller in the GFX/Compute engine. It handles power management related functionality within the GFX/Compute engine. The name is a vestige of old hardware where it was originally added and doesn't really have much relation to what the engine does now.

- [MicroEngine Scheduler (MES)](</kernel/hardware/gpu/amdgpu-gc/mes.md>)

---

# MicroEngine Scheduler (MES)

_Peios Kernel / Hardware and drivers / Graphics / amdgpu / gc_

> Every GFX has a pipe component with one or more hardware queues. Pipes can switch between queues depending on certain conditions, and one of the components that can request a queue switch to a pipe is the MicroEngine Scheduler (MES).…

<a id="rst-microengine-scheduler-mes"></a>
<a id="rst-amdgpu-mes"></a>

> [!NOTE]
>
> Queue and ring buffer are used as a synonymous.

> [!NOTE]
>
> This section assumes that you are familiar with the concept of Pipes, Queues, and GC. If not, check [GFX, Compute, and SDMA Overall Behavior](</kernel/hardware/gpu/amdgpu/driver-core.md#rst-pipes-and-queues-description>) and [drm/amdgpu - Graphics and Compute (GC)](</kernel/hardware/gpu/amdgpu-gc/index.md#rst-amdgpu-gc>).

Every GFX has a pipe component with one or more hardware queues. Pipes can switch between queues depending on certain conditions, and one of the components that can request a queue switch to a pipe is the MicroEngine Scheduler (MES). Whenever the driver is initialized, it creates one MQD per hardware queue, and then the MQDs are handed to the MES firmware for mapping to:

1. Kernel Queues (legacy): This queue is statically mapped to HQDs and never preempted. Even though this is a legacy feature, it is the current default, and most existing hardware supports it. When an application submits work to the kernel driver, it submits all of the application command buffers to the kernel queues. The CS IOCTL takes the command buffer from the applications and schedules them on the kernel queue.

2. User Queues: These queues are dynamically mapped to the HQDs. Regarding the utilization of User Queues, the userspace application will create its user queues and submit work directly to its user queues with no need to IOCTL for each submission and no need to share a single kernel queue.

In terms of User Queues, MES can dynamically map them to the HQD. If there are more MQDs than HQDs, the MES firmware will preempt other user queues to make sure each queues get a time slice; in other words, MES is a microcontroller that handles the mapping and unmapping of MQDs into HQDs, as well as the priorities and oversubscription of MQDs.

---

# drm/bridge/dw-hdmi Synopsys DesignWare HDMI Controller

_Peios Kernel / Hardware and drivers / Graphics / bridge_

> This section covers everything related to the Synopsys DesignWare HDMI Controller implemented as a DRM bridge.

<a id="rst-drm-bridge-dw-hdmi-synopsys-designware-hdmi-controller"></a>

<a id="rst-synopsys-designware-hdmi-controller"></a>

## Synopsys DesignWare HDMI Controller

This section covers everything related to the Synopsys DesignWare HDMI Controller implemented as a DRM bridge.

<a id="rst-supported-input-formats-and-encodings"></a>

## Supported Input Formats and Encodings


Depending on the Hardware configuration of the Controller IP, it supports
a subset of the following input formats and encodings on its internal
48bit bus.

```text
+----------------------+----------------------------------+------------------------------+
| Format Name          | Format Code                      | Encodings                    |
+----------------------+----------------------------------+------------------------------+
| RGB 4:4:4 8bit       | ``MEDIA_BUS_FMT_RGB888_1X24``    | ``V4L2_YCBCR_ENC_DEFAULT``   |
+----------------------+----------------------------------+------------------------------+
| RGB 4:4:4 10bits     | ``MEDIA_BUS_FMT_RGB101010_1X30`` | ``V4L2_YCBCR_ENC_DEFAULT``   |
+----------------------+----------------------------------+------------------------------+
| RGB 4:4:4 12bits     | ``MEDIA_BUS_FMT_RGB121212_1X36`` | ``V4L2_YCBCR_ENC_DEFAULT``   |
+----------------------+----------------------------------+------------------------------+
| RGB 4:4:4 16bits     | ``MEDIA_BUS_FMT_RGB161616_1X48`` | ``V4L2_YCBCR_ENC_DEFAULT``   |
+----------------------+----------------------------------+------------------------------+
| YCbCr 4:4:4 8bit     | ``MEDIA_BUS_FMT_YUV8_1X24``      | ``V4L2_YCBCR_ENC_601``       |
|                      |                                  | or ``V4L2_YCBCR_ENC_709``    |
|                      |                                  | or ``V4L2_YCBCR_ENC_XV601``  |
|                      |                                  | or ``V4L2_YCBCR_ENC_XV709``  |
+----------------------+----------------------------------+------------------------------+
| YCbCr 4:4:4 10bits   | ``MEDIA_BUS_FMT_YUV10_1X30``     | ``V4L2_YCBCR_ENC_601``       |
|                      |                                  | or ``V4L2_YCBCR_ENC_709``    |
|                      |                                  | or ``V4L2_YCBCR_ENC_XV601``  |
|                      |                                  | or ``V4L2_YCBCR_ENC_XV709``  |
+----------------------+----------------------------------+------------------------------+
| YCbCr 4:4:4 12bits   | ``MEDIA_BUS_FMT_YUV12_1X36``     | ``V4L2_YCBCR_ENC_601``       |
|                      |                                  | or ``V4L2_YCBCR_ENC_709``    |
|                      |                                  | or ``V4L2_YCBCR_ENC_XV601``  |
|                      |                                  | or ``V4L2_YCBCR_ENC_XV709``  |
+----------------------+----------------------------------+------------------------------+
| YCbCr 4:4:4 16bits   | ``MEDIA_BUS_FMT_YUV16_1X48``     | ``V4L2_YCBCR_ENC_601``       |
|                      |                                  | or ``V4L2_YCBCR_ENC_709``    |
|                      |                                  | or ``V4L2_YCBCR_ENC_XV601``  |
|                      |                                  | or ``V4L2_YCBCR_ENC_XV709``  |
+----------------------+----------------------------------+------------------------------+
| YCbCr 4:2:2 8bit     | ``MEDIA_BUS_FMT_UYVY8_1X16``     | ``V4L2_YCBCR_ENC_601``       |
|                      |                                  | or ``V4L2_YCBCR_ENC_709``    |
+----------------------+----------------------------------+------------------------------+
| YCbCr 4:2:2 10bits   | ``MEDIA_BUS_FMT_UYVY10_1X20``    | ``V4L2_YCBCR_ENC_601``       |
|                      |                                  | or ``V4L2_YCBCR_ENC_709``    |
+----------------------+----------------------------------+------------------------------+
| YCbCr 4:2:2 12bits   | ``MEDIA_BUS_FMT_UYVY12_1X24``    | ``V4L2_YCBCR_ENC_601``       |
|                      |                                  | or ``V4L2_YCBCR_ENC_709``    |
+----------------------+----------------------------------+------------------------------+
| YCbCr 4:2:0 8bit     | ``MEDIA_BUS_FMT_UYYVYY8_0_5X24`` | ``V4L2_YCBCR_ENC_601``       |
|                      |                                  | or ``V4L2_YCBCR_ENC_709``    |
+----------------------+----------------------------------+------------------------------+
| YCbCr 4:2:0 10bits   | ``MEDIA_BUS_FMT_UYYVYY10_0_5X30``| ``V4L2_YCBCR_ENC_601``       |
|                      |                                  | or ``V4L2_YCBCR_ENC_709``    |
+----------------------+----------------------------------+------------------------------+
| YCbCr 4:2:0 12bits   | ``MEDIA_BUS_FMT_UYYVYY12_0_5X36``| ``V4L2_YCBCR_ENC_601``       |
|                      |                                  | or ``V4L2_YCBCR_ENC_709``    |
+----------------------+----------------------------------+------------------------------+
| YCbCr 4:2:0 16bits   | ``MEDIA_BUS_FMT_UYYVYY16_0_5X48``| ``V4L2_YCBCR_ENC_601``       |
|                      |                                  | or ``V4L2_YCBCR_ENC_709``    |
+----------------------+----------------------------------+------------------------------+
```

---

# drm/imagination PowerVR Graphics Driver

_Peios Kernel / Hardware and drivers / Graphics / imagination_

> Reference for drm/imagination PowerVR Graphics Driver.

<a id="rst-drm-imagination-powervr-graphics-driver"></a>


This driver supports the following PowerVR/IMG graphics cores from Imagination Technologies:

* AXE-1-16M (found in Texas Instruments AM62)
* BXS-4-64 MC1 (found in Texas Instruments J721S2/AM68)


<a id="rst-contents"></a>

## Contents

- [UAPI](</kernel/hardware/gpu/imagination/uapi.md>)

---

# UAPI

_Peios Kernel / Hardware and drivers / Graphics / imagination_

> The sources associated with this section can be found in pvr_drm.h.

<a id="rst-uapi"></a>

The sources associated with this section can be found in `pvr_drm.h`.


The PowerVR IOCTL argument structs have a few limitations in place, in
addition to the standard kernel restrictions:

- All members must be type-aligned.
- The overall struct must be padded to 64-bit alignment.
- Explicit padding is almost always required. This takes the form of
  `_padding_[x]` members of sufficient size to pad to the next power-of-two
  alignment, where \[x\] is the offset into the struct in hexadecimal. Arrays
  are never used for alignment. Padding fields must be zeroed; this is
  always checked.
- Unions may only appear as the last member of a struct.
- Individual union members may grow in the future. The space between the
  end of a union member and the end of its containing union is considered
  "implicit padding" and must be zeroed. This is always checked.

In addition to the IOCTL argument structs, the PowerVR UAPI makes use of
DEV_QUERY argument structs. These are used to fetch information about the
device and runtime. These structs are subject to the same rules set out
above.


<a id="rst-object-arrays"></a>

## OBJECT ARRAYS


#### <a id="c-struct-drm_pvr_obj_array"></a>`struct drm_pvr_obj_array`

Container used to pass arrays of objects

**Definition**

```c
struct drm_pvr_obj_array {
    __u32 stride;
    __u32 count;
    __u64 array;
};
```

**Members**

- `stride`: Stride of object struct. Used for versioning.
- `count`: Number of objects in the array.
- `array`: User pointer to an array of objects.

**Description**

It is not unusual to have to extend objects to pass new parameters, and the DRM
ioctl infrastructure is supporting that by padding ioctl arguments with zeros
when the data passed by userspace is smaller than the struct defined in the
drm_ioctl_desc, thus keeping things backward compatible. This type is just
applying the same concepts to indirect objects passed through arrays referenced
from the main ioctl arguments structure: the stride basically defines the size
of the object passed by userspace, which allows the kernel driver to pad with
zeros when it's smaller than the size of the object it expects.

Use `DRM_PVR_OBJ_ARRAY()` to fill object array fields, unless you
have a very good reason not to.



#### <a id="c-DRM_PVR_OBJ_ARRAY"></a>`DRM_PVR_OBJ_ARRAY()`

```c
DRM_PVR_OBJ_ARRAY(cnt, ptr)
```

Helper macro for filling [`struct drm_pvr_obj_array`](#c-struct-drm_pvr_obj_array).

**Parameters**

- `cnt`: Number of elements pointed to py **ptr**.
- `ptr`: Pointer to start of a C array.

**Return**

Literal of type [`struct drm_pvr_obj_array`](#c-struct-drm_pvr_obj_array).


<a id="rst-ioctls"></a>

## IOCTLS





#### <a id="c-PVR_IOCTL"></a>`PVR_IOCTL()`

```c
PVR_IOCTL(_ioctl, _mode, _data)
```

Build a PowerVR IOCTL number

**Parameters**

- `_ioctl`: An incrementing id for this IOCTL. Added to `DRM_COMMAND_BASE`.
- `_mode`: Must be one of `DRM_IOR`, `DRM_IOW` or `DRM_IOWR`.
- `_data`: The type of the args struct passed by this IOCTL.

**Description**

The struct referred to by **_data** must have a `drm_pvr_ioctl_` prefix and an
`_args suffix`. They are therefore omitted from **_data**.

This should only be used to build the constants described below; it should
never be used to call an IOCTL directly.

**Return**

An IOCTL number to be passed to `ioctl()` from userspace.


<a id="rst-dev-query"></a>

### DEV_QUERY





#### <a id="c-enum-drm_pvr_dev_query"></a>`enum drm_pvr_dev_query`

For use with [`drm_pvr_ioctl_dev_query_args.type`](#c-struct-drm_pvr_ioctl_dev_query_args) to indicate the type of the receiving container.

**Constants**

- `DRM_PVR_DEV_QUERY_GPU_INFO_GET`: The dev query args contain a pointer
  to [`struct drm_pvr_dev_query_gpu_info`](#c-struct-drm_pvr_dev_query_gpu_info).
- `DRM_PVR_DEV_QUERY_RUNTIME_INFO_GET`: The dev query args contain a
  pointer to [`struct drm_pvr_dev_query_runtime_info`](#c-struct-drm_pvr_dev_query_runtime_info).
- `DRM_PVR_DEV_QUERY_QUIRKS_GET`: The dev query args contain a pointer
  to [`struct drm_pvr_dev_query_quirks`](#c-struct-drm_pvr_dev_query_quirks).
- `DRM_PVR_DEV_QUERY_ENHANCEMENTS_GET`: The dev query args contain a
  pointer to [`struct drm_pvr_dev_query_enhancements`](#c-struct-drm_pvr_dev_query_enhancements).
- `DRM_PVR_DEV_QUERY_HEAP_INFO_GET`: The dev query args contain a
  pointer to [`struct drm_pvr_dev_query_heap_info`](#c-struct-drm_pvr_dev_query_heap_info).
- `DRM_PVR_DEV_QUERY_STATIC_DATA_AREAS_GET`: The dev query args contain
  a pointer to [`struct drm_pvr_dev_query_static_data_areas`](#c-struct-drm_pvr_dev_query_static_data_areas).

**Description**

Append only. Do not reorder.



#### <a id="c-struct-drm_pvr_ioctl_dev_query_args"></a>`struct drm_pvr_ioctl_dev_query_args`

Arguments for `DRM_IOCTL_PVR_DEV_QUERY`.

**Definition**

```c
struct drm_pvr_ioctl_dev_query_args {
    __u32 type;
    __u32 size;
    __u64 pointer;
};
```

**Members**

- `type`: Type of query and output struct. See [`enum drm_pvr_dev_query`](#c-enum-drm_pvr_dev_query).
- `size`: Size of the receiving struct, see **type**.

  After a successful call this will be updated to the written byte
  length.
  Can also be used to get the minimum byte length (see **pointer**).
  This allows additional fields to be appended to the structs in
  future.
- `pointer`: Pointer to struct **type**.

  Must be large enough to contain **size** bytes.
  If pointer is NULL, the expected size will be returned in the **size**
  field, but no other data will be written.



#### <a id="c-struct-drm_pvr_dev_query_gpu_info"></a>`struct drm_pvr_dev_query_gpu_info`

Container used to fetch information about the graphics processor.

**Definition**

```c
struct drm_pvr_dev_query_gpu_info {
    __u64 gpu_id;
    __u32 num_phantoms;
    __u32 _padding_c;
};
```

**Members**

- `gpu_id`: GPU identifier.

  For all currently supported GPUs this is the BVNC encoded as a 64-bit
  value as follows:

  ```text
  +--------+--------+--------+-------+
  | 63..48 | 47..32 | 31..16 | 15..0 |
  +========+========+========+=======+
  | B      | V      | N      | C     |
  +--------+--------+--------+-------+
  ```
- `num_phantoms`: Number of Phantoms present.
- `_padding_c`: Reserved. This field must be zeroed.

**Description**

When fetching this type [`struct drm_pvr_ioctl_dev_query_args`](#c-struct-drm_pvr_ioctl_dev_query_args).type must be set
to `DRM_PVR_DEV_QUERY_GPU_INFO_GET`.

#### <a id="c-struct-drm_pvr_dev_query_runtime_info"></a>`struct drm_pvr_dev_query_runtime_info`

Container used to fetch information about the graphics runtime.

**Definition**

```c
struct drm_pvr_dev_query_runtime_info {
    __u64 free_list_min_pages;
    __u64 free_list_max_pages;
    __u32 common_store_alloc_region_size;
    __u32 common_store_partition_space_size;
    __u32 max_coeffs;
    __u32 cdm_max_local_mem_size_regs;
};
```

**Members**

- `free_list_min_pages`: Minimum allowed free list size,
  in PM physical pages.
- `free_list_max_pages`: Maximum allowed free list size,
  in PM physical pages.
- `common_store_alloc_region_size`: Size of the Allocation
  Region within the Common Store used for coefficient and shared
  registers, in dwords.
- `common_store_partition_space_size`: Size of the
  Partition Space within the Common Store for output buffers, in
  dwords.
- `max_coeffs`: Maximum coefficients, in dwords.
- `cdm_max_local_mem_size_regs`: Maximum amount of local
  memory available to a compute kernel, in dwords.

**Description**

When fetching this type [`struct drm_pvr_ioctl_dev_query_args`](#c-struct-drm_pvr_ioctl_dev_query_args).type must be set
to `DRM_PVR_DEV_QUERY_RUNTIME_INFO_GET`.

#### <a id="c-struct-drm_pvr_dev_query_quirks"></a>`struct drm_pvr_dev_query_quirks`

Container used to fetch information about hardware fixes for which the device may require support in the user mode driver.

**Definition**

```c
struct drm_pvr_dev_query_quirks {
    __u64 quirks;
    __u16 count;
    __u16 musthave_count;
    __u32 _padding_c;
};
```

**Members**

- `quirks`: A userspace address for the hardware quirks __u32 array.

  The first **musthave_count** items in the list are quirks that the
  client must support for this device. If userspace does not support
  all these quirks then functionality is not guaranteed and client
  initialisation must fail.
  The remaining quirks in the list affect userspace and the kernel or
  firmware. They are disabled by default and require userspace to
  opt-in. The opt-in mechanism depends on the quirk.
- `count`: Length of **quirks** (number of __u32).
- `musthave_count`: The number of entries in **quirks** that are
  mandatory, starting at index 0.
- `_padding_c`: Reserved. This field must be zeroed.

**Description**

When fetching this type [`struct drm_pvr_ioctl_dev_query_args`](#c-struct-drm_pvr_ioctl_dev_query_args).type must be set
to `DRM_PVR_DEV_QUERY_QUIRKS_GET`.

#### <a id="c-struct-drm_pvr_dev_query_enhancements"></a>`struct drm_pvr_dev_query_enhancements`

Container used to fetch information about optional enhancements supported by the device that require support in the user mode driver.

**Definition**

```c
struct drm_pvr_dev_query_enhancements {
    __u64 enhancements;
    __u16 count;
    __u16 _padding_a;
    __u32 _padding_c;
};
```

**Members**

- `enhancements`: A userspace address for the hardware enhancements
  __u32 array.

  These enhancements affect userspace and the kernel or firmware. They
  are disabled by default and require userspace to opt-in. The opt-in
  mechanism depends on the enhancement.
- `count`: Length of **enhancements** (number of __u32).
- `_padding_a`: Reserved. This field must be zeroed.
- `_padding_c`: Reserved. This field must be zeroed.

**Description**

When fetching this type [`struct drm_pvr_ioctl_dev_query_args`](#c-struct-drm_pvr_ioctl_dev_query_args).type must be set
to `DRM_PVR_DEV_ENHANCEMENTS_GET`.



#### <a id="c-enum-drm_pvr_heap_id"></a>`enum drm_pvr_heap_id`

Array index for heap info data returned by `DRM_PVR_DEV_QUERY_HEAP_INFO_GET`.

**Constants**

- `DRM_PVR_HEAP_GENERAL`: General purpose heap.
- `DRM_PVR_HEAP_PDS_CODE_DATA`: PDS code and data heap.
- `DRM_PVR_HEAP_USC_CODE`: USC code heap.
- `DRM_PVR_HEAP_RGNHDR`: Region header heap. Only used if GPU has BRN63142.
- `DRM_PVR_HEAP_VIS_TEST`: Visibility test heap.
- `DRM_PVR_HEAP_TRANSFER_FRAG`: Transfer fragment heap.
- `DRM_PVR_HEAP_COUNT`: The number of heaps returned by
  `DRM_PVR_DEV_QUERY_HEAP_INFO_GET`.

  More heaps may be added, so this also serves as the copy limit when
  sent by the caller.

**Description**

For compatibility reasons all indices will be present in the returned array,
however some heaps may not be present. These are indicated where
[`struct drm_pvr_heap`](#c-struct-drm_pvr_heap).size is set to zero.

#### <a id="c-struct-drm_pvr_heap"></a>`struct drm_pvr_heap`

Container holding information about a single heap.

**Definition**

```c
struct drm_pvr_heap {
    __u64 base;
    __u64 size;
    __u32 flags;
    __u32 page_size_log2;
};
```

**Members**

- `base`: Base address of heap.
- `size`: Size of heap, in bytes. Will be 0 if the heap is not present.
- `flags`: Flags for this heap. Currently always 0.
- `page_size_log2`: Log2 of page size.

**Description**

This will always be fetched as an array.

#### <a id="c-struct-drm_pvr_dev_query_heap_info"></a>`struct drm_pvr_dev_query_heap_info`

Container used to fetch information about heaps supported by the device driver.

**Definition**

```c
struct drm_pvr_dev_query_heap_info {
    struct drm_pvr_obj_array heaps;
};
```

**Members**

- `heaps`: Array of [`struct drm_pvr_heap`](#c-struct-drm_pvr_heap). If pointer is NULL, the count
  and stride will be updated with those known to the driver version, to
  facilitate allocation by the caller.

**Description**

Please note all driver-supported heaps will be returned up to `heaps.count`.
Some heaps will not be present in all devices, which will be indicated by
[`struct drm_pvr_heap`](#c-struct-drm_pvr_heap).size being set to zero.

When fetching this type [`struct drm_pvr_ioctl_dev_query_args`](#c-struct-drm_pvr_ioctl_dev_query_args).type must be set
to `DRM_PVR_DEV_QUERY_HEAP_INFO_GET`.



#### <a id="c-enum-drm_pvr_static_data_area_usage"></a>`enum drm_pvr_static_data_area_usage`

Array index for static data area info returned by `DRM_PVR_DEV_QUERY_STATIC_DATA_AREAS_GET`.

**Constants**

- `DRM_PVR_STATIC_DATA_AREA_EOT`: End of Tile PDS program code segment.

  The End of Tile PDS task runs at completion of a tile during a fragment job, and is
  responsible for emitting the tile to the Pixel Back End.
- `DRM_PVR_STATIC_DATA_AREA_FENCE`: MCU fence area, used during cache flush and
  invalidation.

  This must point to valid physical memory but the contents otherwise are not used.
- `DRM_PVR_STATIC_DATA_AREA_VDM_SYNC`: VDM sync program.

  The VDM sync program is used to synchronise multiple areas of the GPU hardware.
- `DRM_PVR_STATIC_DATA_AREA_YUV_CSC`: YUV coefficients.

  Area contains up to 16 slots with stride of 64 bytes. Each is a 3x4 matrix of u16 fixed
  point numbers, with 1 sign bit, 2 integer bits and 13 fractional bits.

  The slots are :
  0 = VK_SAMPLER_YCBCR_MODEL_CONVERSION_RGB_IDENTITY_KHR
  1 = VK_SAMPLER_YCBCR_MODEL_CONVERSION_YCBCR_IDENTITY_KHR (full range)
  2 = VK_SAMPLER_YCBCR_MODEL_CONVERSION_YCBCR_IDENTITY_KHR (conformant range)
  3 = VK_SAMPLER_YCBCR_MODEL_CONVERSION_YCBCR_709_KHR (full range)
  4 = VK_SAMPLER_YCBCR_MODEL_CONVERSION_YCBCR_709_KHR (conformant range)
  5 = VK_SAMPLER_YCBCR_MODEL_CONVERSION_YCBCR_601_KHR (full range)
  6 = VK_SAMPLER_YCBCR_MODEL_CONVERSION_YCBCR_601_KHR (conformant range)
  7 = VK_SAMPLER_YCBCR_MODEL_CONVERSION_YCBCR_2020_KHR (full range)
  8 = VK_SAMPLER_YCBCR_MODEL_CONVERSION_YCBCR_2020_KHR (conformant range)
  9 = VK_SAMPLER_YCBCR_MODEL_CONVERSION_YCBCR_601_KHR (conformant range, 10 bit)
  10 = VK_SAMPLER_YCBCR_MODEL_CONVERSION_YCBCR_709_KHR (conformant range, 10 bit)
  11 = VK_SAMPLER_YCBCR_MODEL_CONVERSION_YCBCR_2020_KHR (conformant range, 10 bit)
  14 = Identity (biased)
  15 = Identity

**Description**

For compatibility reasons all indices will be present in the returned array,
however some areas may not be present. These are indicated where
[`struct drm_pvr_static_data_area`](#c-struct-drm_pvr_static_data_area).size is set to zero.

#### <a id="c-struct-drm_pvr_static_data_area"></a>`struct drm_pvr_static_data_area`

Container holding information about a single static data area.

**Definition**

```c
struct drm_pvr_static_data_area {
    __u16 area_usage;
    __u16 location_heap_id;
    __u32 size;
    __u64 offset;
};
```

**Members**

- `area_usage`: Usage of static data area.
  See [`enum drm_pvr_static_data_area_usage`](#c-enum-drm_pvr_static_data_area_usage).
- `location_heap_id`: Array index of heap where this of static data
  area is located. This array is fetched using
  `DRM_PVR_DEV_QUERY_HEAP_INFO_GET`.
- `size`: Size of static data area. Not present if set to zero.
- `offset`: Offset of static data area from start of heap.

**Description**

This will always be fetched as an array.

#### <a id="c-struct-drm_pvr_dev_query_static_data_areas"></a>`struct drm_pvr_dev_query_static_data_areas`

Container used to fetch information about the static data areas in heaps supported by the device driver.

**Definition**

```c
struct drm_pvr_dev_query_static_data_areas {
    struct drm_pvr_obj_array static_data_areas;
};
```

**Members**

- `static_data_areas`: Array of [`struct drm_pvr_static_data_area`](#c-struct-drm_pvr_static_data_area). If
  pointer is NULL, the count and stride will be updated with those
  known to the driver version, to facilitate allocation by the caller.

**Description**

Please note all driver-supported static data areas will be returned up to
`static_data_areas.count`. Some will not be present for all devices which,
will be indicated by [`struct drm_pvr_static_data_area`](#c-struct-drm_pvr_static_data_area).size being set to zero.

Further, some heaps will not be present either. See [`struct drm_pvr_dev_query_heap_info`](#c-struct-drm_pvr_dev_query_heap_info).

When fetching this type [`struct drm_pvr_ioctl_dev_query_args`](#c-struct-drm_pvr_ioctl_dev_query_args).type must be set
to `DRM_PVR_DEV_QUERY_STATIC_DATA_AREAS_GET`.


<a id="rst-create-bo"></a>

### CREATE_BO





#### <a id="c-struct-drm_pvr_ioctl_create_bo_args"></a>`struct drm_pvr_ioctl_create_bo_args`

Arguments for `DRM_IOCTL_PVR_CREATE_BO`

**Definition**

```c
struct drm_pvr_ioctl_create_bo_args {
    __u64 size;
    __u32 handle;
    __u32 _padding_c;
    __u64 flags;
};
```

**Members**

- `size`: \[IN\] Size of buffer object to create. This must be page size
  aligned.
- `handle`: \[OUT\] GEM handle of the new buffer object for use in
  userspace.
- `_padding_c`: Reserved. This field must be zeroed.
- `flags`: \[IN\] Options which will affect the behaviour of this
  creation operation and future mapping operations on the created
  object. This field must be a valid combination of `DRM_PVR_BO_*`
  values, with all bits marked as reserved set to zero.



We use "device" to refer to the GPU here because of the ambiguity between CPU and GPU in some
fonts.

- Device mapping options

  :DRM_PVR_BO_BYPASS_DEVICE_CACHE: Specify that device accesses to this memory will bypass the
  cache. This is used for buffers that will either be regularly updated by the CPU (eg free
  lists) or will be accessed only once and therefore isn't worth caching (eg partial render
  buffers).
  By default, the device flushes its memory caches after every job, so this is not normally
  required for coherency.
  :DRM_PVR_BO_PM_FW_PROTECT: Specify that only the Parameter Manager (PM) and/or firmware
  processor should be allowed to access this memory when mapped to the device. It is not
  valid to specify this flag with DRM_PVR_BO_ALLOW_CPU_USERSPACE_ACCESS.

- CPU mapping options

  :DRM_PVR_BO_ALLOW_CPU_USERSPACE_ACCESS: Allow userspace to map and access the contents of this
  memory. It is not valid to specify this flag with DRM_PVR_BO_PM_FW_PROTECT.


<a id="rst-get-bo-mmap-offset"></a>

### GET_BO_MMAP_OFFSET





#### <a id="c-struct-drm_pvr_ioctl_get_bo_mmap_offset_args"></a>`struct drm_pvr_ioctl_get_bo_mmap_offset_args`

Arguments for `DRM_IOCTL_PVR_GET_BO_MMAP_OFFSET`

**Definition**

```c
struct drm_pvr_ioctl_get_bo_mmap_offset_args {
    __u32 handle;
    __u32 _padding_4;
    __u64 offset;
};
```

**Members**

- `handle`: \[IN\] GEM handle of the buffer object to be mapped.
- `_padding_4`: Reserved. This field must be zeroed.
- `offset`: \[OUT\] Fake offset to use in the real mmap call.

**Description**

Like other DRM drivers, the "mmap" IOCTL doesn't actually map any memory.
Instead, it allocates a fake offset which refers to the specified buffer
object. This offset can be used with a real mmap call on the DRM device
itself.


<a id="rst-create-vm-context-and-destroy-vm-context"></a>

### CREATE_VM_CONTEXT and DESTROY_VM_CONTEXT





#### <a id="c-struct-drm_pvr_ioctl_create_vm_context_args"></a>`struct drm_pvr_ioctl_create_vm_context_args`

Arguments for `DRM_IOCTL_PVR_CREATE_VM_CONTEXT`

**Definition**

```c
struct drm_pvr_ioctl_create_vm_context_args {
    __u32 handle;
    __u32 _padding_4;
};
```

**Members**

- `handle`: \[OUT\] Handle for new VM context.
- `_padding_4`: Reserved. This field must be zeroed.

#### <a id="c-struct-drm_pvr_ioctl_destroy_vm_context_args"></a>`struct drm_pvr_ioctl_destroy_vm_context_args`

Arguments for `DRM_IOCTL_PVR_DESTROY_VM_CONTEXT`

**Definition**

```c
struct drm_pvr_ioctl_destroy_vm_context_args {
    __u32 handle;
    __u32 _padding_4;
};
```

**Members**

- `handle`: \[IN\] Handle for VM context to be destroyed.
- `_padding_4`: Reserved. This field must be zeroed.


<a id="rst-vm-map-and-vm-unmap"></a>

### VM_MAP and VM_UNMAP


The VM UAPI allows userspace to create buffer object mappings in GPU virtual address space.

The client is responsible for managing GPU address space. It should allocate mappings within
the heaps returned by `DRM_PVR_DEV_QUERY_HEAP_INFO_GET`.

`DRM_IOCTL_PVR_VM_MAP` creates a new mapping. The client provides the target virtual address for
the mapping. Size and offset within the mapped buffer object can be specified, so the client can
partially map a buffer.

`DRM_IOCTL_PVR_VM_UNMAP` removes a mapping. The entire mapping will be removed from GPU address
space only if the size of the mapping matches that known to the driver.



#### <a id="c-struct-drm_pvr_ioctl_vm_map_args"></a>`struct drm_pvr_ioctl_vm_map_args`

Arguments for `DRM_IOCTL_PVR_VM_MAP`.

**Definition**

```c
struct drm_pvr_ioctl_vm_map_args {
    __u32 vm_context_handle;
    __u32 flags;
    __u64 device_addr;
    __u32 handle;
    __u32 _padding_14;
    __u64 offset;
    __u64 size;
};
```

**Members**

- `vm_context_handle`: \[IN\] Handle for VM context for this mapping to
  exist in.
- `flags`: \[IN\] Flags which affect this mapping. Currently always 0.
- `device_addr`: \[IN\] Requested device-virtual address for the mapping.
  This must be non-zero and aligned to the device page size for the
  heap containing the requested address. It is an error to specify an
  address which is not contained within one of the heaps returned by
  `DRM_PVR_DEV_QUERY_HEAP_INFO_GET`.
- `handle`: \[IN\] Handle of the target buffer object. This must be a
  valid handle returned by `DRM_IOCTL_PVR_CREATE_BO`.
- `_padding_14`: Reserved. This field must be zeroed.
- `offset`: \[IN\] Offset into the target bo from which to begin the
  mapping.
- `size`: \[IN\] Size of the requested mapping. Must be aligned to
  the device page size for the heap containing the requested address,
  as well as the host page size. When added to **device_addr**, the
  result must not overflow the heap which contains **device_addr** (i.e.
  the range specified by **device_addr** and **size** must be completely
  contained within a single heap specified by
  `DRM_PVR_DEV_QUERY_HEAP_INFO_GET`).

#### <a id="c-struct-drm_pvr_ioctl_vm_unmap_args"></a>`struct drm_pvr_ioctl_vm_unmap_args`

Arguments for `DRM_IOCTL_PVR_VM_UNMAP`.

**Definition**

```c
struct drm_pvr_ioctl_vm_unmap_args {
    __u32 vm_context_handle;
    __u32 _padding_4;
    __u64 device_addr;
    __u64 size;
};
```

**Members**

- `vm_context_handle`: \[IN\] Handle for VM context that this mapping
  exists in.
- `_padding_4`: Reserved. This field must be zeroed.
- `device_addr`: \[IN\] Device-virtual address at the start of the target
  mapping. This must be non-zero.
- `size`: Size in bytes of the target mapping. This must be non-zero.


<a id="rst-create-context-and-destroy-context"></a>

### CREATE_CONTEXT and DESTROY_CONTEXT





#### <a id="c-struct-drm_pvr_ioctl_create_context_args"></a>`struct drm_pvr_ioctl_create_context_args`

Arguments for `DRM_IOCTL_PVR_CREATE_CONTEXT`

**Definition**

```c
struct drm_pvr_ioctl_create_context_args {
    __u32 type;
    __u32 flags;
    __s32 priority;
    __u32 handle;
    __u64 static_context_state;
    __u32 static_context_state_len;
    __u32 vm_context_handle;
    __u64 callstack_addr;
};
```

**Members**

- `type`: \[IN\] Type of context to create.

  This must be one of the values defined by [`enum drm_pvr_ctx_type`](#c-enum-drm_pvr_ctx_type).
- `flags`: \[IN\] Flags for context.
- `priority`: \[IN\] Priority of new context.

  This must be one of the values defined by [`enum drm_pvr_ctx_priority`](#c-enum-drm_pvr_ctx_priority).
- `handle`: \[OUT\] Handle for new context.
- `static_context_state`: \[IN\] Pointer to static context state stream.
- `static_context_state_len`: \[IN\] Length of static context state, in bytes.
- `vm_context_handle`: \[IN\] Handle for VM context that this context is
  associated with.
- `callstack_addr`: \[IN\] Address for initial call stack pointer. Only valid
  if **type** is `DRM_PVR_CTX_TYPE_RENDER`, otherwise must be 0.



#### <a id="c-enum-drm_pvr_ctx_priority"></a>`enum drm_pvr_ctx_priority`

Arguments for [`drm_pvr_ioctl_create_context_args.priority`](#c-struct-drm_pvr_ioctl_create_context_args)

**Constants**

- `DRM_PVR_CTX_PRIORITY_LOW`: Priority below normal.
- `DRM_PVR_CTX_PRIORITY_NORMAL`: Normal priority.
- `DRM_PVR_CTX_PRIORITY_HIGH`: Priority above normal.
  Note this requires `CAP_SYS_NICE` or `DRM_MASTER`.

#### <a id="c-enum-drm_pvr_ctx_type"></a>`enum drm_pvr_ctx_type`

Arguments for [`struct drm_pvr_ioctl_create_context_args`](#c-struct-drm_pvr_ioctl_create_context_args).type

**Constants**

- `DRM_PVR_CTX_TYPE_RENDER`: Render context.
- `DRM_PVR_CTX_TYPE_COMPUTE`: Compute context.
- `DRM_PVR_CTX_TYPE_TRANSFER_FRAG`: Transfer context for fragment data
  master.



#### <a id="c-struct-drm_pvr_ioctl_destroy_context_args"></a>`struct drm_pvr_ioctl_destroy_context_args`

Arguments for `DRM_IOCTL_PVR_DESTROY_CONTEXT`

**Definition**

```c
struct drm_pvr_ioctl_destroy_context_args {
    __u32 handle;
    __u32 _padding_4;
};
```

**Members**

- `handle`: \[IN\] Handle for context to be destroyed.
- `_padding_4`: Reserved. This field must be zeroed.


<a id="rst-create-free-list-and-destroy-free-list"></a>

### CREATE_FREE_LIST and DESTROY_FREE_LIST





#### <a id="c-struct-drm_pvr_ioctl_create_free_list_args"></a>`struct drm_pvr_ioctl_create_free_list_args`

Arguments for `DRM_IOCTL_PVR_CREATE_FREE_LIST`

**Definition**

```c
struct drm_pvr_ioctl_create_free_list_args {
    __u64 free_list_gpu_addr;
    __u32 initial_num_pages;
    __u32 max_num_pages;
    __u32 grow_num_pages;
    __u32 grow_threshold;
    __u32 vm_context_handle;
    __u32 handle;
};
```

**Members**

- `free_list_gpu_addr`: \[IN\] Address of GPU mapping of buffer object
  containing memory to be used by free list.

  The mapped region of the buffer object must be at least
  **max_num_pages** * `sizeof(__u32)`.

  The buffer object must have been created with
  `DRM_PVR_BO_DEVICE_PM_FW_PROTECT` set and
  `DRM_PVR_BO_CPU_ALLOW_USERSPACE_ACCESS` not set.
- `initial_num_pages`: \[IN\] Pages initially allocated to free list.
- `max_num_pages`: \[IN\] Maximum number of pages in free list.
- `grow_num_pages`: \[IN\] Pages to grow free list by per request.
- `grow_threshold`: \[IN\] Percentage of FL memory used that should
  trigger a new grow request.
- `vm_context_handle`: \[IN\] Handle for VM context that the free list buffer
  object is mapped in.
- `handle`: \[OUT\] Handle for created free list.

**Description**

Free list arguments have the following constraints :

- **max_num_pages** must be greater than zero.
- **grow_threshold** must be between 0 and 100.
- **grow_num_pages** must be less than or equal to `max_num_pages`.
- **initial_num_pages**, **max_num_pages** and **grow_num_pages** must be multiples
  of 4.
- When `grow_num_pages` is 0, **initial_num_pages** must be equal to
  **max_num_pages**.
- When `grow_num_pages` is non-zero, **initial_num_pages** must be less than
  **max_num_pages**.



#### <a id="c-struct-drm_pvr_ioctl_destroy_free_list_args"></a>`struct drm_pvr_ioctl_destroy_free_list_args`

Arguments for `DRM_IOCTL_PVR_DESTROY_FREE_LIST`

**Definition**

```c
struct drm_pvr_ioctl_destroy_free_list_args {
    __u32 handle;
    __u32 _padding_4;
};
```

**Members**

- `handle`: \[IN\] Handle for free list to be destroyed.
- `_padding_4`: Reserved. This field must be zeroed.


<a id="rst-create-hwrt-dataset-and-destroy-hwrt-dataset"></a>

### CREATE_HWRT_DATASET and DESTROY_HWRT_DATASET





#### <a id="c-struct-drm_pvr_ioctl_create_hwrt_dataset_args"></a>`struct drm_pvr_ioctl_create_hwrt_dataset_args`

Arguments for `DRM_IOCTL_PVR_CREATE_HWRT_DATASET`

**Definition**

```c
struct drm_pvr_ioctl_create_hwrt_dataset_args {
    struct drm_pvr_create_hwrt_geom_data_args geom_data_args;
    struct drm_pvr_create_hwrt_rt_data_args rt_data_args[2];
    __u32 free_list_handles[2];
    __u32 width;
    __u32 height;
    __u32 samples;
    __u32 layers;
    __u32 isp_merge_lower_x;
    __u32 isp_merge_lower_y;
    __u32 isp_merge_scale_x;
    __u32 isp_merge_scale_y;
    __u32 isp_merge_upper_x;
    __u32 isp_merge_upper_y;
    __u32 region_header_size;
    __u32 handle;
};
```

**Members**

- `geom_data_args`: \[IN\] Geometry data arguments.
- `rt_data_args`: \[IN\] Array of render target arguments.

  Each entry in this array represents a render target in a double buffered
  setup.
- `free_list_handles`: \[IN\] Array of free list handles.

  free_list_handles\[PVR_DRM_HWRT_FREE_LIST_LOCAL\] must have initial
  size of at least that reported by
  [`drm_pvr_dev_query_runtime_info.free_list_min_pages`](#c-struct-drm_pvr_dev_query_runtime_info).
- `width`: \[IN\] Width in pixels.
- `height`: \[IN\] Height in pixels.
- `samples`: \[IN\] Number of samples.
- `layers`: \[IN\] Number of layers.
- `isp_merge_lower_x`: \[IN\] Lower X coefficient for triangle merging.
- `isp_merge_lower_y`: \[IN\] Lower Y coefficient for triangle merging.
- `isp_merge_scale_x`: \[IN\] Scale X coefficient for triangle merging.
- `isp_merge_scale_y`: \[IN\] Scale Y coefficient for triangle merging.
- `isp_merge_upper_x`: \[IN\] Upper X coefficient for triangle merging.
- `isp_merge_upper_y`: \[IN\] Upper Y coefficient for triangle merging.
- `region_header_size`: \[IN\] Size of region header array. This common field is used by
  both render targets in this data set.

  The units for this field differ depending on what version of the simple internal
  parameter format the device uses. If format 2 is in use then this is interpreted as the
  number of region headers. For other formats it is interpreted as the size in dwords.
- `handle`: \[OUT\] Handle for created HWRT dataset.



#### <a id="c-struct-drm_pvr_create_hwrt_geom_data_args"></a>`struct drm_pvr_create_hwrt_geom_data_args`

Geometry data arguments used for [`struct drm_pvr_ioctl_create_hwrt_dataset_args`](#c-struct-drm_pvr_ioctl_create_hwrt_dataset_args).geom_data_args.

**Definition**

```c
struct drm_pvr_create_hwrt_geom_data_args {
    __u64 tpc_dev_addr;
    __u32 tpc_size;
    __u32 tpc_stride;
    __u64 vheap_table_dev_addr;
    __u64 rtc_dev_addr;
};
```

**Members**

- `tpc_dev_addr`: \[IN\] Tail pointer cache GPU virtual address.
- `tpc_size`: \[IN\] Size of TPC, in bytes.
- `tpc_stride`: \[IN\] Stride between layers in TPC, in pages
- `vheap_table_dev_addr`: \[IN\] VHEAP table GPU virtual address.
- `rtc_dev_addr`: \[IN\] Render Target Cache virtual address.

#### <a id="c-struct-drm_pvr_create_hwrt_rt_data_args"></a>`struct drm_pvr_create_hwrt_rt_data_args`

Render target arguments used for [`struct drm_pvr_ioctl_create_hwrt_dataset_args`](#c-struct-drm_pvr_ioctl_create_hwrt_dataset_args).rt_data_args.

**Definition**

```c
struct drm_pvr_create_hwrt_rt_data_args {
    __u64 pm_mlist_dev_addr;
    __u64 macrotile_array_dev_addr;
    __u64 region_header_dev_addr;
};
```

**Members**

- `pm_mlist_dev_addr`: \[IN\] PM MLIST GPU virtual address.
- `macrotile_array_dev_addr`: \[IN\] Macrotile array GPU virtual address.
- `region_header_dev_addr`: \[IN\] Region header array GPU virtual address.



#### <a id="c-struct-drm_pvr_ioctl_destroy_hwrt_dataset_args"></a>`struct drm_pvr_ioctl_destroy_hwrt_dataset_args`

Arguments for `DRM_IOCTL_PVR_DESTROY_HWRT_DATASET`

**Definition**

```c
struct drm_pvr_ioctl_destroy_hwrt_dataset_args {
    __u32 handle;
    __u32 _padding_4;
};
```

**Members**

- `handle`: \[IN\] Handle for HWRT dataset to be destroyed.
- `_padding_4`: Reserved. This field must be zeroed.


<a id="rst-submit-jobs"></a>

### SUBMIT_JOBS





#### <a id="c-DRM_PVR_SYNC_OP_HANDLE_TYPE_MASK"></a>`DRM_PVR_SYNC_OP_HANDLE_TYPE_MASK`

Handle type mask for the drm_pvr_sync_op::flags field.

#### <a id="c-DRM_PVR_SYNC_OP_FLAG_HANDLE_TYPE_SYNCOBJ"></a>`DRM_PVR_SYNC_OP_FLAG_HANDLE_TYPE_SYNCOBJ`

Indicates the handle passed in drm_pvr_sync_op::handle is a syncobj handle.
This is the default type.

#### <a id="c-DRM_PVR_SYNC_OP_FLAG_HANDLE_TYPE_TIMELINE_SYNCOBJ"></a>`DRM_PVR_SYNC_OP_FLAG_HANDLE_TYPE_TIMELINE_SYNCOBJ`

Indicates the handle passed in drm_pvr_sync_op::handle is a timeline syncobj handle.

#### <a id="c-DRM_PVR_SYNC_OP_FLAG_SIGNAL"></a>`DRM_PVR_SYNC_OP_FLAG_SIGNAL`

Signal operation requested. The out-fence bound to the job will be attached to
the syncobj whose handle is passed in drm_pvr_sync_op::handle.

#### <a id="c-DRM_PVR_SYNC_OP_FLAG_WAIT"></a>`DRM_PVR_SYNC_OP_FLAG_WAIT`

Wait operation requested. The job will wait for this particular syncobj or syncobj
point to be signaled before being started.
This is the default operation.



#### <a id="c-struct-drm_pvr_ioctl_submit_jobs_args"></a>`struct drm_pvr_ioctl_submit_jobs_args`

Arguments for `DRM_IOCTL_PVR_SUBMIT_JOB`

**Definition**

```c
struct drm_pvr_ioctl_submit_jobs_args {
    struct drm_pvr_obj_array jobs;
};
```

**Members**

- `jobs`: \[IN\] Array of jobs to submit.

**Description**

If the syscall returns an error it is important to check the value of
**jobs.count**. This indicates the index into **jobs.array** where the
error occurred.



#### <a id="c-DRM_PVR_SUBMIT_JOB_GEOM_CMD_FIRST"></a>`DRM_PVR_SUBMIT_JOB_GEOM_CMD_FIRST`

Indicates if this the first command to be issued for a render.

#### <a id="c-DRM_PVR_SUBMIT_JOB_GEOM_CMD_LAST"></a>`DRM_PVR_SUBMIT_JOB_GEOM_CMD_LAST`

Indicates if this the last command to be issued for a render.

#### <a id="c-DRM_PVR_SUBMIT_JOB_GEOM_CMD_SINGLE_CORE"></a>`DRM_PVR_SUBMIT_JOB_GEOM_CMD_SINGLE_CORE`

Forces to use single core in a multi core device.

#### <a id="c-DRM_PVR_SUBMIT_JOB_GEOM_CMD_FLAGS_MASK"></a>`DRM_PVR_SUBMIT_JOB_GEOM_CMD_FLAGS_MASK`

Logical OR of all the geometry cmd flags.



#### <a id="c-DRM_PVR_SUBMIT_JOB_FRAG_CMD_SINGLE_CORE"></a>`DRM_PVR_SUBMIT_JOB_FRAG_CMD_SINGLE_CORE`

Use single core in a multi core setup.

#### <a id="c-DRM_PVR_SUBMIT_JOB_FRAG_CMD_DEPTHBUFFER"></a>`DRM_PVR_SUBMIT_JOB_FRAG_CMD_DEPTHBUFFER`

Indicates whether a depth buffer is present.

#### <a id="c-DRM_PVR_SUBMIT_JOB_FRAG_CMD_STENCILBUFFER"></a>`DRM_PVR_SUBMIT_JOB_FRAG_CMD_STENCILBUFFER`

Indicates whether a stencil buffer is present.

#### <a id="c-DRM_PVR_SUBMIT_JOB_FRAG_CMD_PREVENT_CDM_OVERLAP"></a>`DRM_PVR_SUBMIT_JOB_FRAG_CMD_PREVENT_CDM_OVERLAP`

Disallow compute overlapped with this render.

#### <a id="c-DRM_PVR_SUBMIT_JOB_FRAG_CMD_GET_VIS_RESULTS"></a>`DRM_PVR_SUBMIT_JOB_FRAG_CMD_GET_VIS_RESULTS`

Indicates whether this render produces visibility results.

#### <a id="c-DRM_PVR_SUBMIT_JOB_FRAG_CMD_SCRATCHBUFFER"></a>`DRM_PVR_SUBMIT_JOB_FRAG_CMD_SCRATCHBUFFER`

Indicates whether partial renders write to a scratch buffer instead of
the final surface. It also forces the full screen copy expected to be
present on the last render after all partial renders have completed.

#### <a id="c-DRM_PVR_SUBMIT_JOB_FRAG_CMD_DISABLE_PIXELMERGE"></a>`DRM_PVR_SUBMIT_JOB_FRAG_CMD_DISABLE_PIXELMERGE`

Disable pixel merging for this render.

#### <a id="c-DRM_PVR_SUBMIT_JOB_FRAG_CMD_FLAGS_MASK"></a>`DRM_PVR_SUBMIT_JOB_FRAG_CMD_FLAGS_MASK`

Logical OR of all the fragment cmd flags.



#### <a id="c-DRM_PVR_SUBMIT_JOB_COMPUTE_CMD_PREVENT_ALL_OVERLAP"></a>`DRM_PVR_SUBMIT_JOB_COMPUTE_CMD_PREVENT_ALL_OVERLAP`

Disallow other jobs overlapped with this compute.

#### <a id="c-DRM_PVR_SUBMIT_JOB_COMPUTE_CMD_SINGLE_CORE"></a>`DRM_PVR_SUBMIT_JOB_COMPUTE_CMD_SINGLE_CORE`

Forces to use single core in a multi core device.

#### <a id="c-DRM_PVR_SUBMIT_JOB_COMPUTE_CMD_FLAGS_MASK"></a>`DRM_PVR_SUBMIT_JOB_COMPUTE_CMD_FLAGS_MASK`

Logical OR of all the compute cmd flags.



#### <a id="c-DRM_PVR_SUBMIT_JOB_TRANSFER_CMD_SINGLE_CORE"></a>`DRM_PVR_SUBMIT_JOB_TRANSFER_CMD_SINGLE_CORE`

Forces job to use a single core in a multi core device.

#### <a id="c-DRM_PVR_SUBMIT_JOB_TRANSFER_CMD_FLAGS_MASK"></a>`DRM_PVR_SUBMIT_JOB_TRANSFER_CMD_FLAGS_MASK`

Logical OR of all the transfer cmd flags.



#### <a id="c-struct-drm_pvr_sync_op"></a>`struct drm_pvr_sync_op`

Object describing a sync operation

**Definition**

```c
struct drm_pvr_sync_op {
    __u32 handle;
    __u32 flags;
    __u64 value;
};
```

**Members**

- `handle`: Handle of sync object.
- `flags`: Combination of `DRM_PVR_SYNC_OP_FLAG_` flags.
- `value`: Timeline value for this drm_syncobj. MBZ for a binary syncobj.

#### <a id="c-enum-drm_pvr_job_type"></a>`enum drm_pvr_job_type`

Arguments for [`struct drm_pvr_job`](#c-struct-drm_pvr_job).job_type

**Constants**

- `DRM_PVR_JOB_TYPE_GEOMETRY`: Job type is geometry.
- `DRM_PVR_JOB_TYPE_FRAGMENT`: Job type is fragment.
- `DRM_PVR_JOB_TYPE_COMPUTE`: Job type is compute.
- `DRM_PVR_JOB_TYPE_TRANSFER_FRAG`: Job type is a fragment transfer.

#### <a id="c-struct-drm_pvr_hwrt_data_ref"></a>`struct drm_pvr_hwrt_data_ref`

Reference HWRT data

**Definition**

```c
struct drm_pvr_hwrt_data_ref {
    __u32 set_handle;
    __u32 data_index;
};
```

**Members**

- `set_handle`: HWRT data set handle.
- `data_index`: Index of the HWRT data inside the data set.

#### <a id="c-struct-drm_pvr_job"></a>`struct drm_pvr_job`

Job arguments passed to the `DRM_IOCTL_PVR_SUBMIT_JOBS` ioctl

**Definition**

```c
struct drm_pvr_job {
    __u32 type;
    __u32 context_handle;
    __u32 flags;
    __u32 cmd_stream_len;
    __u64 cmd_stream;
    struct drm_pvr_obj_array sync_ops;
    struct drm_pvr_hwrt_data_ref hwrt;
};
```

**Members**

- `type`: \[IN\] Type of job being submitted

  This must be one of the values defined by [`enum drm_pvr_job_type`](#c-enum-drm_pvr_job_type).
- `context_handle`: \[IN\] Context handle.

  When **job_type** is `DRM_PVR_JOB_TYPE_RENDER`, `DRM_PVR_JOB_TYPE_COMPUTE` or
  `DRM_PVR_JOB_TYPE_TRANSFER_FRAG`, this must be a valid handle returned by
  `DRM_IOCTL_PVR_CREATE_CONTEXT`. The type of context must be compatible
  with the type of job being submitted.

  When **job_type** is `DRM_PVR_JOB_TYPE_NULL`, this must be zero.
- `flags`: \[IN\] Flags for command.

  Those are job-dependent. See all `DRM_PVR_SUBMIT_JOB_*`.
- `cmd_stream_len`: \[IN\] Length of command stream, in bytes.
- `cmd_stream`: \[IN\] Pointer to command stream for command.

  The command stream must be u64-aligned.
- `sync_ops`: \[IN\] Fragment sync operations.
- `hwrt`: \[IN\] HWRT data used by render jobs (geometry or fragment).

  Must be zero for non-render jobs.


<a id="rst-internal-notes"></a>

## Internal notes


To validate the constraints imposed on IOCTL argument structs, a collection
of macros and helper functions exist in `pvr_device.h`.

Of the current helpers, it should only be necessary to call
[`PVR_IOCTL_UNION_PADDING_CHECK()`](#c-PVR_IOCTL_UNION_PADDING_CHECK) directly. This macro should be used once in
every code path which extracts a union member from a struct passed from
userspace.



#### <a id="c-pvr_ioctl_union_padding_check"></a>`pvr_ioctl_union_padding_check()`

```c
bool pvr_ioctl_union_padding_check(void *instance, size_t union_offset, size_t union_size, size_t member_size)
```

Validate that the implicit padding between the end of a union member and the end of the union itself is zeroed.

**Parameters**

- `void *instance`: Pointer to the instance of the struct to validate.
- `size_t union_offset`: Offset into the type of **instance** of the target union. Must
  be 64-bit aligned.
- `size_t union_size`: Size of the target union in the type of **instance**. Must be
  64-bit aligned.
- `size_t member_size`: Size of the target member in the target union specified by
  **union_offset** and **union_size**. It is assumed that the offset of the target
  member is zero relative to **union_offset**. Must be 64-bit aligned.

**Description**

You probably want to use [`PVR_IOCTL_UNION_PADDING_CHECK()`](#c-PVR_IOCTL_UNION_PADDING_CHECK) instead of calling
this function directly, since that macro abstracts away much of the setup,
and also provides some static validation. See its docs for details.

**Return**

* `true` if every byte between the end of the used member of the union and
  the end of that union is zeroed, or
* `false` otherwise.

#### <a id="c-PVR_STATIC_ASSERT_64BIT_ALIGNED"></a>`PVR_STATIC_ASSERT_64BIT_ALIGNED()`

```c
PVR_STATIC_ASSERT_64BIT_ALIGNED(static_expr_)
```

Inline assertion for 64-bit alignment.

**Parameters**

- `static_expr_`: Target expression to evaluate.

**Description**

If **static_expr_** does not evaluate to a constant integer which would be a
64-bit aligned address (i.e. a multiple of 8), compilation will fail.

**Return**

The value of **static_expr_**.

#### <a id="c-PVR_IOCTL_UNION_PADDING_CHECK"></a>`PVR_IOCTL_UNION_PADDING_CHECK()`

```c
PVR_IOCTL_UNION_PADDING_CHECK(struct_instance_, union_, member_)
```

Validate that the implicit padding between the end of a union member and the end of the union itself is zeroed.

**Parameters**

- `struct_instance_`: An expression which evaluates to a pointer to a UAPI data
  struct.
- `union_`: The name of the union member of **struct_instance_** to check. If the
  union member is nested within the type of **struct_instance_**, this may
  contain the member access operator (".").
- `member_`: The name of the member of **union_** to assess.

**Description**

This is a wrapper around [`pvr_ioctl_union_padding_check()`](#c-pvr_ioctl_union_padding_check) which performs
alignment checks and simplifies things for the caller.

**Return**

* `true` if every byte in **struct_instance_** between the end of **member_** and
  the end of **union_** is zeroed, or
* `false` otherwise.

---

# nova NVIDIA GPU drivers

_Peios Kernel / Hardware and drivers / Graphics / nova_

> The nova driver project consists out of two separate drivers nova-core and nova-drm and intends to supersede the nouveau driver for NVIDIA GPUs based on the GPU System Processor (GSP).

<a id="rst-nova-nvidia-gpu-drivers"></a>

<!-- SPDX-License-Identifier: (GPL-2.0+ OR MIT) -->

The nova driver project consists out of two separate drivers nova-core and nova-drm and intends to supersede the nouveau driver for NVIDIA GPUs based on the GPU System Processor (GSP).

The following documents apply to both nova-core and nova-drm.

- [Guidelines](</kernel/hardware/gpu/nova/guidelines.md>)

<a id="rst-nova-core"></a>

## nova-core

The nova-core driver is the core driver for NVIDIA GPUs based on GSP. nova-core, as the 1st level driver, provides an abstraction around the GPUs hard- and firmware interfaces providing a common base for 2nd level drivers, such as the vGPU manager VFIO driver and the nova-drm driver.

- [Guidelines](</kernel/hardware/gpu/nova-core/guidelines.md>)
- [Task List](</kernel/hardware/gpu/nova-core/todo.md>)
- [VBIOS](</kernel/hardware/gpu/nova-core/vbios.md>)
- [Device Initialization (devinit)](</kernel/hardware/gpu/nova-core/devinit.md>)
- [FWSEC (Firmware Security)](</kernel/hardware/gpu/nova-core/fwsec.md>)
- [Falcon (FAst Logic Controller)](</kernel/hardware/gpu/nova-core/falcon.md>)

---

# Guidelines

_Peios Kernel / Hardware and drivers / Graphics / nova_

> This document describes the general project guidelines that apply to nova-core and nova-drm.

<a id="rst-guidelines"></a>

<!-- SPDX-License-Identifier: (GPL-2.0+ OR MIT) -->

This document describes the general project guidelines that apply to nova-core and nova-drm.

<a id="rst-language"></a>

## Language

The Nova project uses the Rust programming language. In this context, all rules of the Rust for Linux project as documented in [General Information](</kernel/development/rust/general-information.md>) apply. Additionally, the following rules apply.

- Unless technically necessary otherwise (e.g. uAPI), any driver code is written in Rust.

- Unless technically necessary, unsafe Rust code must be avoided. In case of technical necessity, unsafe code should be isolated in a separate component providing a safe API for other driver code to use.

<a id="rst-style"></a>

### Style

All rules of the Rust for Linux project as documented in [Coding Guidelines](</kernel/development/rust/coding-guidelines.md>) apply.

For a submit checklist, please also see the [Rust for Linux Submit checklist addendum](<https://rust-for-linux.com/contributing#submit-checklist-addendum>)<a id="rst-rust-for-linux-submit-checklist-addendum"></a>.

<a id="rst-documentation"></a>

## Documentation

The availability of proper documentation is essential in terms of scalability, accessibility for new contributors and maintainability of a project in general, but especially for a driver running as complex hardware as Nova is targeting.

Hence, adding documentation of any kind is very much encouraged by the project.

Besides that, there are some minimum requirements.

- Every non-private structure needs at least a brief doc comment explaining the semantical sense of the structure, as well as potential locking and lifetime requirements. It is encouraged to have the same minimum documentation for non-trivial private structures.

- uAPIs must be fully documented with kernel-doc comments; additionally, the semantical behavior must be explained including potential special or corner cases.

- The APIs connecting the 1st level driver (nova-core) with 2nd level drivers must be fully documented. This includes doc comments, potential locking and lifetime requirements, as well as example code if applicable.

- Abbreviations must be explained when introduced; terminology must be uniquely defined.

- Register addresses, layouts, shift values and masks must be defined properly; unless obvious, the semantical sense must be documented. This only applies if the author is able to obtain the corresponding information.

<a id="rst-acceptance-criteria"></a>

## Acceptance Criteria

- Patches must only be applied if reviewed by at least one other person on the mailing list; this also applies for maintainers.

---

# Device Initialization (devinit)

_Peios Kernel / Hardware and drivers / Graphics / nova / core_

> The devinit process is complex and subject to change. This document provides a high-level overview using the Ampere GPU family as an example. The goal is to provide a conceptual overview of the process to aid in understanding the…

<a id="rst-device-initialization-devinit"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

The devinit process is complex and subject to change. This document provides a high-level overview using the Ampere GPU family as an example. The goal is to provide a conceptual overview of the process to aid in understanding the corresponding kernel code.

Device initialization (devinit) is a crucial sequence of register read/write operations that occur after a GPU reset. The devinit sequence is essential for properly configuring the GPU hardware before it can be used.

The devinit engine is an interpreter program that typically runs on the PMU (Power Management Unit) microcontroller of the GPU. This interpreter executes a "script" of initialization commands. The devinit engine itself is part of the VBIOS ROM in the same ROM image as the FWSEC (Firmware Security) image (see [fwsec.rst](/kernel/hardware/gpu/nova-core/fwsec.md) and [vbios.rst](/kernel/hardware/gpu/nova-core/vbios.md)) and it runs before the nova-core driver is even loaded. On an Ampere GPU, the devinit ucode is separate from the FWSEC ucode. It is launched by FWSEC, which runs on the GSP in 'heavy-secure' mode, while devinit runs on the PMU in 'light-secure' mode.

<a id="rst-key-functions-of-devinit"></a>

## Key Functions of devinit

devinit performs several critical tasks:

1. Programming VRAM memory controller timings

2. Power sequencing

3. Clock and PLL (Phase-Locked Loop) configuration

4. Thermal management

<a id="rst-low-level-firmware-initialization-flow"></a>

## Low-level Firmware Initialization Flow

Upon reset, several microcontrollers on the GPU (such as PMU, SEC2, GSP, etc.) run GPU firmware (gfw) code to set up the GPU and its core parameters. Most of the GPU is considered unusable until this initialization process completes.

These low-level GPU firmware components are typically:

1. Located in the VBIOS ROM in the same ROM partition (see [vbios.rst](/kernel/hardware/gpu/nova-core/vbios.md) and [fwsec.rst](/kernel/hardware/gpu/nova-core/fwsec.md)).

2. Executed in sequence on different microcontrollers:

> - The devinit engine typically but not necessarily runs on the PMU.
>
> - On an Ampere GPU, the FWSEC typically runs on the GSP (GPU System Processor) in heavy-secure mode.

Before the driver can proceed with further initialization, it must wait for a signal indicating that core initialization is complete (known as GFW_BOOT). This signal is asserted by the FWSEC running on the GSP in heavy-secure mode.

<a id="rst-runtime-considerations"></a>

## Runtime Considerations

It's important to note that the devinit sequence also needs to run during suspend/resume operations at runtime, not just during initial boot, as it is critical to power management.

<a id="rst-security-and-access-control"></a>

## Security and Access Control

The initialization process involves careful privilege management. For example, before accessing certain completion status registers, the driver must check privilege level masks. Some registers are only accessible after secure firmware (FWSEC) lowers the privilege level to allow CPU (LS/low-secure) access. This is the case, for example, when receiving the GFW_BOOT signal.

---

# Falcon (FAst Logic Controller)

_Peios Kernel / Hardware and drivers / Graphics / nova / core_

> The following sections describe the Falcon core and the ucode running on it. The descriptions are based on the Ampere GPU or earlier designs; however, they should mostly apply to future designs as well, but everything is subject to change.…

<a id="rst-falcon-fast-logic-controller"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

The following sections describe the Falcon core and the ucode running on it. The descriptions are based on the Ampere GPU or earlier designs; however, they should mostly apply to future designs as well, but everything is subject to change. The overview provided here is mainly tailored towards understanding the interactions of nova-core driver with the Falcon.

NVIDIA GPUs embed small RISC-like microcontrollers called Falcon cores, which handle secure firmware tasks, initialization, and power management. Modern NVIDIA GPUs may have multiple such Falcon instances (e.g., GSP (the GPU system processor) and SEC2 (the security engine)) and also may integrate a RISC-V core. This core is capable of running both RISC-V and Falcon code.

The code running on the Falcon cores is also called 'ucode', and will be referred to as such in the following sections.

Falcons have separate instruction and data memories (IMEM/DMEM) and provide a small DMA engine (via the FBIF - "Frame Buffer Interface") to load code from system memory. The nova-core driver must reset and configure the Falcon, load its firmware via DMA, and start its CPU.

<a id="rst-falcon-security-levels"></a>

## Falcon security levels

Falcons can run in Non-secure (NS), Light Secure (LS), or Heavy Secure (HS) modes.

<a id="rst-heavy-secured-hs-also-known-as-privilege-level-3-pl3"></a>

### Heavy Secured (HS) also known as Privilege Level 3 (PL3)

HS ucode is the most trusted code and has access to pretty much everything on the chip. The HS binary includes a signature in it which is verified at boot. This signature verification is done by the hardware itself, thus establishing a root of trust. For example, the FWSEC-FRTS command (see [fwsec.rst](/kernel/hardware/gpu/nova-core/fwsec.md)) runs on the GSP in HS mode. FRTS, which involves setting up and loading content into the WPR (Write Protect Region), has to be done by the HS ucode and cannot be done by the host CPU or LS ucode.

<a id="rst-light-secured-ls-or-pl2-and-non-secured-ns-or-pl0"></a>

### Light Secured (LS or PL2) and Non Secured (NS or PL0)

These modes are less secure than HS. Like HS, the LS or NS ucode binary also typically includes a signature in it. To load firmware in LS or NS mode onto a Falcon, another Falcon needs to be running in HS mode, which also establishes the root of trust. For example, in the case of an Ampere GPU, the CPU runs the "Booter" ucode in HS mode on the SEC2 Falcon, which then authenticates and runs the run-time GSP binary (GSP-RM) in LS mode on the GSP Falcon. Similarly, as an example, after reset on an Ampere, FWSEC runs on the GSP which then loads the devinit engine onto the PMU in LS mode.

<a id="rst-root-of-trust-establishment"></a>

### Root of trust establishment

To establish a root of trust, the code running on a Falcon must be immutable and hardwired into a read-only memory (ROM). This follows industry norms for verification of firmware. This code is called the Boot ROM (BROM). The nova-core driver on the CPU communicates with Falcon's Boot ROM through various Falcon registers prefixed with "BROM" (see regs.rs).

After nova-core driver reads the necessary ucode from VBIOS, it programs the BROM and DMA registers to trigger the Falcon to load the HS ucode from the system memory into the Falcon's IMEM/DMEM. Once the HS ucode is loaded, it is verified by the Falcon's Boot ROM.

Once the verified HS code is running on a Falcon, it can verify and load other LS/NS ucode binaries onto other Falcons and start them. The process of signature verification is the same as HS; just in this case, the hardware (BROM) doesn't compute the signature, but the HS ucode does.

- **The root of trust is therefore established as follows:**

  Hardware (Boot ROM running on the Falcon) -&gt; HS ucode -&gt; LS/NS ucode.

- **On an Ampere GPU, for example, the boot verification flow is:**

  - **Hardware (Boot ROM running on the SEC2) -&gt;**

    - **HS ucode (Booter running on the SEC2) -&gt;**

      LS ucode (GSP-RM running on the GSP)

> [!NOTE]
>
> While the CPU can load HS ucode onto a Falcon microcontroller and have it verified by the hardware and run, the CPU itself typically does not load LS or NS ucode and run it. Loading of LS or NS ucode is done mainly by the HS ucode. For example, on an Ampere GPU, after the Booter ucode runs on the SEC2 in HS mode and loads the GSP-RM binary onto the GSP, it needs to run the "SEC2-RTOS" ucode at runtime. This presents a problem: there is no component to load the SEC2-RTOS ucode onto the SEC2. The CPU cannot load LS code, and GSP-RM must run in LS mode. To overcome this, the GSP is temporarily made to run HS ucode (which is itself loaded by the CPU via the nova-core driver using a "GSP-provided sequencer") which then loads the SEC2-RTOS ucode onto the SEC2 in LS mode. The GSP then resumes running its own GSP-RM LS ucode.

<a id="rst-falcon-memory-subsystem-and-dma-engine"></a>

## Falcon memory subsystem and DMA engine

Falcons have separate instruction and data memories (IMEM/DMEM) and contains a small DMA engine called FBDMA (Framebuffer DMA) which does DMA transfers to/from the IMEM/DMEM memory inside the Falcon via the FBIF (Framebuffer Interface), to external memory.

DMA transfers are possible from the Falcon's memory to both the system memory and the framebuffer memory (VRAM).

To perform a DMA via the FBDMA, the FBIF is configured to decide how the memory is accessed (also known as aperture type). In the nova-core driver, this is determined by the `FalconFbifTarget` enum.

The IO-PMP block (Input/Output Physical Memory Protection) unit in the Falcon controls access by the FBDMA to the external memory.

Conceptual diagram (not exact) of the Falcon and its memory subsystem is as follows:



```text
          External Memory (Framebuffer / System DRAM)
                         ^  |
                         |  |
                         |  v
+-----------------------------------------------------+
|                           |                         |
|   +---------------+       |                         |
|   |     FBIF      |-------+                         |  FALCON
|   | (FrameBuffer  |   Memory Interface              |  PROCESSOR
|   |  InterFace)   |                                 |
|   |  Apertures    |                                 |
|   |  Configures   |                                 |
|   |  mem access   |                                 |
|   +-------^-------+                                 |
|           |                                         |
|           | FBDMA uses configured FBIF apertures    |
|           | to access External Memory
|           |
|   +-------v--------+      +---------------+
|   |    FBDMA       |  cfg |     RISC      |
|   | (FrameBuffer   |<---->|     CORE      |----->. Direct Core Access
|   |  DMA Engine)   |      |               |      |
|   | - Master dev.  |      | (can run both |      |
|   +-------^--------+      | Falcon and    |      |
|           |        cfg--->| RISC-V code)  |      |
|           |        /      |               |      |
|           |        |      +---------------+      |    +------------+
|           |        |                             |    |   BROM     |
|           |        |                             <--->| (Boot ROM) |
|           |       /                              |    +------------+
|           |      v                               |
|   +---------------+                              |
|   |    IO-PMP     | Controls access by FBDMA     |
|   | (IO Physical  | and other IO Masters         |
|   | Memory Protect)                              |
|   +-------^-------+                              |
|           |                                      |
|           | Protected Access Path for FBDMA      |
|           v                                      |
|   +---------------------------------------+      |
|   |       Memory                          |      |
|   |   +---------------+  +------------+   |      |
|   |   |    IMEM       |  |    DMEM    |   |<-----+
|   |   | (Instruction  |  |   (Data    |   |
|   |   |  Memory)      |  |   Memory)  |   |
|   |   +---------------+  +------------+   |
|   +---------------------------------------+
+-----------------------------------------------------+
```

---

# FWSEC (Firmware Security)

_Peios Kernel / Hardware and drivers / Graphics / nova / core_

> This document briefly/conceptually describes the FWSEC (Firmware Security) image and its role in the GPU boot sequence. As such, this information is subject to change in the future and is only current as of the Ampere GPU family. However,…

<a id="rst-fwsec-firmware-security"></a>

<!-- SPDX-License-Identifier: (GPL-2.0+ OR MIT) -->

This document briefly/conceptually describes the FWSEC (Firmware Security) image and its role in the GPU boot sequence. As such, this information is subject to change in the future and is only current as of the Ampere GPU family. However, hopefully the concepts described will be useful for understanding the kernel code that deals with it. All the information is derived from publicly available sources such as public drivers and documentation.

The role of FWSEC is to provide a secure boot process. It runs in 'Heavy-secure' mode, and performs firmware verification after a GPU reset before loading various ucode images onto other microcontrollers on the GPU, such as the PMU and GSP.

FWSEC itself is an application stored in the VBIOS ROM in the FWSEC partition of ROM (see [vbios.rst](/kernel/hardware/gpu/nova-core/vbios.md) for more details). It contains different commands like FRTS (Firmware Runtime Services) and SB (Secure Booting other microcontrollers after reset and loading them with other non-FWSEC ucode). The kernel driver only needs to perform FRTS, since Secure Boot (SB) has already completed by the time the driver is loaded.

The FRTS command carves out the WPR2 region (Write protected region) which contains data required for power management. Once setup, only HS mode ucode can access it (see [falcon.rst](/kernel/hardware/gpu/nova-core/falcon.md) for privilege levels).

The FWSEC image is located in the VBIOS ROM in the partition of the ROM that contains various ucode images (also known as applications) -- one of them being FWSEC. For how it is extracted, see [vbios.rst](/kernel/hardware/gpu/nova-core/vbios.md) and the vbios.rs source code.

The Falcon data for each ucode images (including the FWSEC image) is a combination of headers, data sections (DMEM) and instruction code sections (IMEM). All these ucode images are stored in the same ROM partition and the PMU table is used to look up the application to load it based on its application ID (see vbios.rs).

For the nova-core driver, the FWSEC contains an 'application interface' called DMEMMAPPER. This interface is used to execute the 'FWSEC-FRTS' command, among others. For Ampere, FWSEC is running on the GSP in Heavy-secure mode and runs FRTS.

<a id="rst-fwsec-memory-layout"></a>

## FWSEC Memory Layout

The memory layout of the FWSEC image is as follows:



```text
+---------------------------------------------------------------+
|                         FWSEC ROM image (type 0xE0)           |
|                                                               |
|  +---------------------------------+                          |
|  |     PMU Falcon Ucode Table      |                          |
|  |     (PmuLookupTable)            |                          |
|  |  +-------------------------+    |                          |
|  |  | Table Header            |    |                          |
|  |  | - version: 0x01         |    |                          |
|  |  | - header_size: 6        |    |                          |
|  |  | - entry_size: 6         |    |                          |
|  |  | - entry_count: N        |    |                          |
|  |  | - desc_version:3(unused)|    |                          |
|  |  +-------------------------+    |                          |
|  |         ...                     |                          |
|  |  +-------------------------+    |                          |
|  |  | Entry for FWSEC (0x85)  |    |                          |
|  |  | (PmuLookupTableEntry)   |    |                          |
|  |  | - app_id: 0x85 (FWSEC)  |----|----+                     |
|  |  | - target_id: 0x01 (PMU) |    |    |                     |
|  |  | - data: offset ---------|----|----|---+ look up FWSEC   |
|  |  +-------------------------+    |    |   |                 |
|  +---------------------------------+    |   |                 |
|                                         |   |                 |
|                                         |   |                 |
|  +---------------------------------+    |   |                 |
|  |     FWSEC Ucode Component       |<---+   |                 |
|  |     (aka Falcon data)           |        |                 |
|  |  +-------------------------+    |        |                 |
|  |  | FalconUCodeDescV3       |<---|--------+                 |
|  |  | - hdr                   |    |                          |
|  |  | - stored_size           |    |                          |
|  |  | - pkc_data_offset       |    |                          |
|  |  | - interface_offset -----|----|----------------+         |
|  |  | - imem_phys_base        |    |                |         |
|  |  | - imem_load_size        |    |                |         |
|  |  | - imem_virt_base        |    |                |         |
|  |  | - dmem_phys_base        |    |                |         |
|  |  | - dmem_load_size        |    |                |         |
|  |  | - engine_id_mask        |    |                |         |
|  |  | - ucode_id              |    |                |         |
|  |  | - signature_count       |    |    look up sig |         |
|  |  | - signature_versions --------------+          |         |
|  |  +-------------------------+    |     |          |         |
|  |         (no gap)                |     |          |         |
|  |  +-------------------------+    |     |          |         |
|  |  | Signatures Section      |<---|-----+          |         |
|  |  | (384 bytes per sig)     |    |                |         |
|  |  | - RSA-3K Signature 1    |    |                |         |
|  |  | - RSA-3K Signature 2    |    |                |         |
|  |  |   ...                   |    |                |         |
|  |  +-------------------------+    |                |         |
|  |                                 |                |         |
|  |  +-------------------------+    |                |         |
|  |  | IMEM Section (Code)     |    |                |         |
|  |  |                         |    |                |         |
|  |  | Contains instruction    |    |                |         |
|  |  | code etc.               |    |                |         |
|  |  +-------------------------+    |                |         |
|  |                                 |                |         |
|  |  +-------------------------+    |                |         |
|  |  | DMEM Section (Data)     |    |                |         |
|  |  |                         |    |                |         |
|  |  | +---------------------+ |    |                |         |
|  |  | | Application         | |<---|----------------+         |
|  |  | | Interface Table     | |    |                          |
|  |  | | (FalconAppifHdrV1)  | |    |                          |
|  |  | | Header:             | |    |                          |
|  |  | | - version: 0x01     | |    |                          |
|  |  | | - header_size: 4    | |    |                          |
|  |  | | - entry_size: 8     | |    |                          |
|  |  | | - entry_count: N    | |    |                          |
|  |  | |                     | |    |                          |
|  |  | | Entries:            | |    |                          |
|  |  | | +-----------------+ | |    |                          |
|  |  | | | DEVINIT (ID 1)  | | |    |                          |
|  |  | | | - id: 0x01      | | |    |                          |
|  |  | | | - dmemOffset X -|-|-|----+                          |
|  |  | | +-----------------+ | |    |                          |
|  |  | | +-----------------+ | |    |                          |
|  |  | | | DMEMMAPPER(ID 4)| | |    |                          |
|  |  | | | - id: 0x04      | | |    | Used only for DevInit    |
|  |  | | |  (NVFW_FALCON_  | | |    | application (not FWSEC)  |
|  |  | | |   APPIF_ID_DMEMMAPPER)   |                          |
|  |  | | | - dmemOffset Y -|-|-|----|-----+                    |
|  |  | | +-----------------+ | |    |     |                    |
|  |  | +---------------------+ |    |     |                    |
|  |  |                         |    |     |                    |
|  |  | +---------------------+ |    |     |                    |
|  |  | | DEVINIT Engine      |<|----+     | Used by FWSEC      |
|  |  | | Interface           | |    |     |         app.       |
|  |  | +---------------------+ |    |     |                    |
|  |  |                         |    |     |                    |
|  |  | +---------------------+ |    |     |                    |
|  |  | | DMEM Mapper (ID 4)  |<|----+-----+                    |
|  |  | | (FalconAppifDmemmapperV3)  |                          |
|  |  | | - signature: "DMAP" | |    |                          |
|  |  | | - version: 0x0003   | |    |                          |
|  |  | | - Size: 64 bytes    | |    |                          |
|  |  | | - cmd_in_buffer_off | |----|------------+             |
|  |  | | - cmd_in_buffer_size| |    |            |             |
|  |  | | - cmd_out_buffer_off| |----|------------|-----+       |
|  |  | | - cmd_out_buffer_sz | |    |            |     |       |
|  |  | | - init_cmd          | |    |            |     |       |
|  |  | | - features          | |    |            |     |       |
|  |  | | - cmd_mask0/1       | |    |            |     |       |
|  |  | +---------------------+ |    |            |     |       |
|  |  |                         |    |            |     |       |
|  |  | +---------------------+ |    |            |     |       |
|  |  | | Command Input Buffer|<|----|------------+     |       |
|  |  | | - Command data      | |    |                  |       |
|  |  | | - Arguments         | |    |                  |       |
|  |  | +---------------------+ |    |                  |       |
|  |  |                         |    |                  |       |
|  |  | +---------------------+ |    |                  |       |
|  |  | | Command Output      |<|----|------------------+       |
|  |  | | Buffer              | |    |                          |
|  |  | | - Results           | |    |                          |
|  |  | | - Status            | |    |                          |
|  |  | +---------------------+ |    |                          |
|  |  +-------------------------+    |                          |
|  +---------------------------------+                          |
|                                                               |
+---------------------------------------------------------------+
```

> [!NOTE]
>
> This is using an GA-102 Ampere GPU as an example and could vary for future GPUs.

> [!NOTE]
>
> The FWSEC image also plays a role in memory scrubbing (ECC initialization) and VPR (Video Protected Region) initialization as well. Before the nova-core driver is even loaded, the FWSEC image is running on the GSP in heavy-secure mode. After the devinit sequence completes, it does VRAM memory scrubbing (ECC initialization). On consumer GPUs, it scrubs only part of memory and then initiates 'async scrubbing'. Before this async scrubbing completes, the unscrubbed VRAM cannot be used for allocation (thus DRM memory allocators need to wait for this scrubbing to complete).

---

# Guidelines

_Peios Kernel / Hardware and drivers / Graphics / nova / core_

> This documents contains the guidelines for nova-core. Additionally, all common guidelines of the Nova project do apply.

<a id="rst-guidelines"></a>

<!-- SPDX-License-Identifier: (GPL-2.0+ OR MIT) -->

This documents contains the guidelines for nova-core. Additionally, all common guidelines of the Nova project do apply.

<a id="rst-driver-api"></a>

## Driver API

One main purpose of nova-core is to implement the abstraction around the firmware interface of GSP and provide a firmware (version) independent API for 2nd level drivers, such as nova-drm or the vGPU manager VFIO driver.

Therefore, it is not permitted to leak firmware (version) specifics, through the driver API, to 2nd level drivers.

<a id="rst-acceptance-criteria"></a>

## Acceptance Criteria

- To the extend possible, patches submitted to nova-core must be tested for regressions with all 2nd level drivers.

---

# Task List

_Peios Kernel / Hardware and drivers / Graphics / nova / core_

> Tasks may have the following fields:

<a id="rst-task-list"></a>

<!-- SPDX-License-Identifier: (GPL-2.0+ OR MIT) -->

Tasks may have the following fields:

- `Complexity`: Describes the required familiarity with Rust and / or the corresponding kernel APIs or subsystems. There are four different complexities, `Beginner`, `Intermediate`, `Advanced` and `Expert`.

- `Reference`: References to other tasks.

- `Link`: Links to external resources.

- `Contact`: The person that can be contacted for further information about the task.

A task might have `[ABCD]` code after its name. This code can be used to grep into the code for `TODO` entries related to it.

<a id="rst-enablement-rust"></a>

## Enablement (Rust)

Tasks that are not directly related to nova-core, but are preconditions in terms of required APIs.

<a id="rst-fromprimitive-api-fpri"></a>

### FromPrimitive API \[FPRI\]

Sometimes the need arises to convert a number to a value of an enum or a structure.

A good example from nova-core would be the `Chipset` enum type, which defines the value `AD102`. When probing the GPU the value `0x192` can be read from a certain register indication the chipset AD102. Hence, the enum value `AD102` should be derived from the number `0x192`. Currently, nova-core uses a custom implementation (`Chipset::from_u32` for this.

Instead, it would be desirable to have something like the `FromPrimitive` trait \[1\] from the num crate.

Having this generalization also helps with implementing a generic macro that automatically generates the corresponding mappings between a value and a number.

FromPrimitive support has been worked on in the past, but hasn't been followed since then \[1\].

There also have been considerations of ToPrimitive \[2\].

Complexity: Beginner  
Link: [https://docs.rs/num/latest/num/trait.FromPrimitive.html](<https://docs.rs/num/latest/num/trait.FromPrimitive.html>)  
Link: [https://lore.kernel.org/all/cover.1750689857.git.y.j3ms.n@gmail.com/](<https://lore.kernel.org/all/cover.1750689857.git.y.j3ms.n@gmail.com/>) \[1\]  
Link: [https://rust-for-linux.zulipchat.com/\#narrow/channel/288089-General/topic/Implement.20.60FromPrimitive.60.20trait.20.2B.20derive.20macro.20for.20nova-core/with/541971854](<https://rust-for-linux.zulipchat.com/#narrow/channel/288089-General/topic/Implement.20.60FromPrimitive.60.20trait.20.2B.20derive.20macro.20for.20nova-core/with/541971854>) \[2\]

<a id="rst-generic-register-abstraction-rega"></a>

### Generic register abstraction \[REGA\]

Work out how register constants and structures can be automatically generated through generalized macros.

Example:



```rust
register!(BOOT0, 0x0, u32, pci::Bar<SIZE>, Fields [
   MINOR_REVISION(3:0, RO),
   MAJOR_REVISION(7:4, RO),
   REVISION(7:0, RO), // Virtual register combining major and minor rev.
])
```

This could expand to something like:



```rust
const BOOT0_OFFSET: usize = 0x00000000;
const BOOT0_MINOR_REVISION_SHIFT: u8 = 0;
const BOOT0_MINOR_REVISION_MASK: u32 = 0x0000000f;
const BOOT0_MAJOR_REVISION_SHIFT: u8 = 4;
const BOOT0_MAJOR_REVISION_MASK: u32 = 0x000000f0;
const BOOT0_REVISION_SHIFT: u8 = BOOT0_MINOR_REVISION_SHIFT;
const BOOT0_REVISION_MASK: u32 = BOOT0_MINOR_REVISION_MASK | BOOT0_MAJOR_REVISION_MASK;

struct Boot0(u32);

impl Boot0 {
   #[inline]
   fn read(bar: &RevocableGuard<'_, pci::Bar<SIZE>>) -> Self {
      Self(bar.readl(BOOT0_OFFSET))
   }

   #[inline]
   fn minor_revision(&self) -> u32 {
      (self.0 & BOOT0_MINOR_REVISION_MASK) >> BOOT0_MINOR_REVISION_SHIFT
   }

   #[inline]
   fn major_revision(&self) -> u32 {
      (self.0 & BOOT0_MAJOR_REVISION_MASK) >> BOOT0_MAJOR_REVISION_SHIFT
   }

   #[inline]
   fn revision(&self) -> u32 {
      (self.0 & BOOT0_REVISION_MASK) >> BOOT0_REVISION_SHIFT
   }
}
```

Usage:



```rust
let bar = bar.try_access().ok_or(ENXIO)?;

let boot0 = Boot0::read(&bar);
pr_info!("Revision: {}\n", boot0.revision());
```

A work-in-progress implementation currently resides in `drivers/gpu/nova-core/regs/macros.rs` and is used in nova-core. It would be nice to improve it (possibly using proc macros) and move it to the `kernel` crate so it can be used by other components as well.

Features desired before this happens:

- Make I/O optional I/O (for field values that are not registers),

- Support other sizes than `u32`,

- Allow visibility control for registers and individual fields,

- Use Rust slice syntax to express fields ranges.

Complexity: Advanced  
Contact: Alexandre Courbot

<a id="rst-numerical-operations-numm"></a>

### Numerical operations \[NUMM\]

Nova uses integer operations that are not part of the standard library (or not implemented in an optimized way for the kernel). These include:

- The "Find Last Set Bit" (`fls` function of the C part of the kernel) operation.

A `num` core kernel module is being designed to provide these operations.

Complexity: Intermediate  
Contact: Alexandre Courbot

<a id="rst-page-abstraction-for-foreign-pages"></a>

### Page abstraction for foreign pages

Rust abstractions for pages not created by the Rust page abstraction without direct ownership.

There is active onging work from Abdiel Janulgue \[1\] and Lina \[2\].

Complexity: Advanced  
Link: [https://lore.kernel.org/linux-mm/20241119112408.779243-1-abdiel.janulgue@gmail.com/](<https://lore.kernel.org/linux-mm/20241119112408.779243-1-abdiel.janulgue@gmail.com/>) \[1\]  
Link: [https://lore.kernel.org/rust-for-linux/20250202-rust-page-v1-0-e3170d7fe55e@asahilina.net/](<https://lore.kernel.org/rust-for-linux/20250202-rust-page-v1-0-e3170d7fe55e@asahilina.net/>) \[2\]

<a id="rst-pci-misc-apis"></a>

### PCI MISC APIs

Extend the existing PCI device / driver abstractions by SR-IOV, capability, MSI API abstractions.

SR-IOV \[1\] is work in progress.

Complexity: Beginner  
Link: [https://lore.kernel.org/all/20251119-rust-pci-sriov-v1-0-883a94599a97@redhat.com/](<https://lore.kernel.org/all/20251119-rust-pci-sriov-v1-0-883a94599a97@redhat.com/>) \[1\]

<a id="rst-gpu-general"></a>

## GPU (general)

<a id="rst-initial-devinit-support"></a>

### Initial Devinit support

Implement BIOS Device Initialization, i.e. memory sizing, waiting, PLL configuration.

Contact: Dave Airlie  
Complexity: Beginner

<a id="rst-mmu-pt-management"></a>

### MMU / PT management

Work out the architecture for MMU / page table management.

We need to consider that nova-drm will need rather fine-grained control, especially in terms of locking, in order to be able to implement asynchronous Vulkan queues.

While generally sharing the corresponding code is desirable, it needs to be evaluated how (and if at all) sharing the corresponding code is expedient.

Complexity: Expert

<a id="rst-vram-memory-allocator"></a>

### VRAM memory allocator

Investigate options for a VRAM memory allocator.

- **Some possible options:**

  - Rust abstractions for - RB tree (interval tree) / drm_mm - maple_tree

  - native Rust collections

There is work in progress for using drm_buddy \[1\].

Complexity: Advanced  
Link: [https://lore.kernel.org/all/20251219203805.1246586-4-joelagnelf@nvidia.com/](<https://lore.kernel.org/all/20251219203805.1246586-4-joelagnelf@nvidia.com/>) \[1\]

<a id="rst-instance-memory"></a>

### Instance Memory

Implement support for instmem (bar2) used to store page tables.

Complexity: Intermediate  
Contact: Dave Airlie

<a id="rst-gpu-system-processor-gsp"></a>

## GPU System Processor (GSP)

<a id="rst-export-gsp-log-buffers"></a>

### Export GSP log buffers

Recent patches from Timur Tabi \[1\] added support to expose GSP-RM log buffers (even after failure to probe the driver) through debugfs.

This is also an interesting feature for nova-core, especially in the early days.

Link: [https://lore.kernel.org/nouveau/20241030202952.694055-2-ttabi@nvidia.com/](<https://lore.kernel.org/nouveau/20241030202952.694055-2-ttabi@nvidia.com/>) \[1\]  
Reference: Debugfs abstractions  
Complexity: Intermediate

<a id="rst-gsp-firmware-abstraction"></a>

### GSP firmware abstraction

The GSP-RM firmware API is unstable and may incompatibly change from version to version, in terms of data structures and semantics.

This problem is one of the big motivations for using Rust for nova-core, since it turns out that Rust's procedural macro feature provides a rather elegant way to address this issue:

1. generate Rust structures from the C headers in a separate namespace per version

2. build abstraction structures (within a generic namespace) that implement the firmware interfaces; annotate the differences in implementation with version identifiers

3. use a procedural macro to generate the actual per version implementation out of this abstraction

4. instantiate the correct version type one on runtime (can be sure that all have the same interface because it's defined by a common trait)

There is a PoC implementation of this pattern, in the context of the nova-core PoC driver.

This task aims at refining the feature and ideally generalize it, to be usable by other drivers as well.

Complexity: Expert

<a id="rst-gsp-message-queue"></a>

### GSP message queue

Implement low level GSP message queue (command, status) for communication between the kernel driver and GSP.

Complexity: Advanced  
Contact: Dave Airlie

<a id="rst-bootstrap-gsp"></a>

### Bootstrap GSP

Call the boot firmware to boot the GSP processor; execute initial control messages.

Complexity: Intermediate  
Contact: Dave Airlie

<a id="rst-client-device-apis"></a>

### Client / Device APIs

Implement the GSP message interface for client / device allocation and the corresponding client and device allocation APIs.

Complexity: Intermediate  
Contact: Dave Airlie

<a id="rst-bar-pde-handling"></a>

### Bar PDE handling

Synchronize page table handling for BARs between the kernel driver and GSP.

Complexity: Beginner  
Contact: Dave Airlie

<a id="rst-fifo-engine"></a>

### FIFO engine

Implement support for the FIFO engine, i.e. the corresponding GSP message interface and provide an API for chid allocation and channel handling.

Complexity: Advanced  
Contact: Dave Airlie

<a id="rst-gr-engine"></a>

### GR engine

Implement support for the graphics engine, i.e. the corresponding GSP message interface and provide an API for (golden) context creation and promotion.

Complexity: Advanced  
Contact: Dave Airlie

<a id="rst-ce-engine"></a>

### CE engine

Implement support for the copy engine, i.e. the corresponding GSP message interface.

Complexity: Intermediate  
Contact: Dave Airlie

<a id="rst-vfn-irq-controller"></a>

### VFN IRQ controller

Support for the VFN interrupt controller.

Complexity: Intermediate  
Contact: Dave Airlie

<a id="rst-external-apis"></a>

## External APIs

<a id="rst-nova-core-base-api"></a>

### nova-core base API

Work out the common pieces of the API to connect 2nd level drivers, i.e. vGPU manager and nova-drm.

Complexity: Advanced

<a id="rst-vgpu-manager-api"></a>

### vGPU manager API

Work out the API parts required by the vGPU manager, which are not covered by the base API.

Complexity: Advanced

<a id="rst-nova-core-c-api"></a>

### nova-core C API

Implement a C wrapper for the APIs required by the vGPU manager driver.

Complexity: Intermediate

<a id="rst-testing"></a>

## Testing

<a id="rst-ci-pipeline"></a>

### CI pipeline

Investigate option for continuous integration testing.

This can go from as simple as running KUnit tests over running (graphics) CTS to booting up (multiple) guest VMs to test VFIO use-cases.

It might also be worth to consider the introduction of a new test suite directly sitting on top of the uAPI for more targeted testing and debugging. There may be options for collaboration / shared code with the Mesa project.

Complexity: Advanced

---

# VBIOS

_Peios Kernel / Hardware and drivers / Graphics / nova / core_

> This document describes the layout of the VBIOS image which is a series of concatenated images in the ROM of the GPU. The VBIOS is mirrored onto the BAR 0 space and is read by both Boot ROM firmware (also known as IFR or init-from-rom…

<a id="rst-vbios"></a>

<!-- SPDX-License-Identifier: (GPL-2.0+ OR MIT) -->

This document describes the layout of the VBIOS image which is a series of concatenated images in the ROM of the GPU. The VBIOS is mirrored onto the BAR 0 space and is read by both Boot ROM firmware (also known as IFR or init-from-rom firmware) on the GPU to bootstrap various microcontrollers (PMU, SEC, GSP) with critical initialization before the driver loads, as well as by the nova-core driver in the kernel to boot the GSP.

The format of the images in the ROM follow the "BIOS Specification" part of the PCI specification, with Nvidia-specific extensions. The ROM images of type FwSec are the ones that contain Falcon ucode and what we are mainly looking for.

As an example, the following are the different image types that can be found in the VBIOS of an Ampere GA102 GPU which is supported by the nova-core driver.

- PciAt Image (Type 0x00) - This is the standard PCI BIOS image, whose name likely comes from the "IBM PC/AT" architecture.

- EFI Image (Type 0x03) - This is the EFI BIOS image. It contains the UEFI GOP driver that is used to display UEFI graphics output.

- First FwSec Image (Type 0xE0) - The first FwSec image (Secure Firmware)

- Second FwSec Image (Type 0xE0) - The second FwSec image (Secure Firmware) contains various  microcodes (also known as an applications) that do a range of different functions. The FWSEC ucode is run in heavy-secure mode and typically runs directly on the GSP (it could be running on a different designated processor in future generations but as of Ampere, it is the GSP). This firmware then loads other firmware ucodes onto the PMU and SEC2 microcontrollers for gfw initialization after GPU reset and before the driver loads (see [devinit.rst](/kernel/hardware/gpu/nova-core/devinit.md)). The DEVINIT ucode is itself another ucode that is stored in this ROM partition.

Once located, the Falcon ucodes have "Application Interfaces" in their data memory (DMEM). For FWSEC, the application interface we use for FWSEC is the "DMEM mapper" interface which is configured to run the "FRTS" command. This command carves out the WPR2 (Write-Protected Region) in VRAM. It then places important power-management data, called 'FRTS', into this region. The WPR2 region is only accessible to heavy-secure ucode.

> [!NOTE]
>
> It is not clear why FwSec has 2 different partitions in the ROM, but they both are of type 0xE0 and can be identified as such. This could be subject to change in future generations.

<a id="rst-vbios-rom-layout"></a>

## VBIOS ROM Layout

The VBIOS layout is roughly a series of concatenated images laid out as follows:



```text
+----------------------------------------------------------------------------+
| VBIOS (Starting at ROM_OFFSET: 0x300000)                                   |
+----------------------------------------------------------------------------+
| +-----------------------------------------------+                          |
| | PciAt Image (Type 0x00)                       |                          |
| +-----------------------------------------------+                          |
| | +-------------------+                         |                          |
| | | ROM Header        |                         |                          |
| | | (Signature 0xAA55)|                         |                          |
| | +-------------------+                         |                          |
| |         | rom header's pci_data_struct_offset |                          |
| |         | points to the PCIR structure        |                          |
| |         V                                     |                          |
| | +-------------------+                         |                          |
| | | PCIR Structure    |                         |                          |
| | | (Signature "PCIR")|                         |                          |
| | | last_image: 0x80  |                         |                          |
| | | image_len: size   |                         |                          |
| | | in 512-byte units |                         |                          |
| | +-------------------+                         |                          |
| |         |                                     |                          |
| |         | NPDE immediately follows PCIR       |                          |
| |         V                                     |                          |
| | +-------------------+                         |                          |
| | | NPDE Structure    |                         |                          |
| | | (Signature "NPDE")|                         |                          |
| | | last_image: 0x00  |                         |                          |
| | +-------------------+                         |                          |
| |                                               |                          |
| | +-------------------+                         |                          |
| | | BIT Header        | (Signature scanning     |                          |
| | | (Signature "BIT") |  provides the location  |                          |
| | +-------------------+  of the BIT table)      |                          |
| |         | header is                           |                          |
| |         | followed by a table of tokens       |                          |
| |         V one of which is for falcon data.    |                          |
| | +-------------------+                         |                          |
| | | BIT Tokens        |                         |                          |
| | |  ______________   |                         |                          |
| | | | Falcon Data |   |                         |                          |
| | | | Token (0x70)|---+------------>------------+--+                       |
| | | +-------------+   |  falcon_data_ptr()      |  |                       |
| | +-------------------+                         |  V                       |
| +-----------------------------------------------+  |                       |
|              (no gap between images)               |                       |
| +-----------------------------------------------+  |                       |
| | EFI Image (Type 0x03)                         |  |                       |
| +-----------------------------------------------+  |                       |
| | Contains the UEFI GOP driver (Graphics Output)|  |                       |
| | +-------------------+                         |  |                       |
| | | ROM Header        |                         |  |                       |
| | +-------------------+                         |  |                       |
| | | PCIR Structure    |                         |  |                       |
| | +-------------------+                         |  |                       |
| | | NPDE Structure    |                         |  |                       |
| | +-------------------+                         |  |                       |
| | | Image data        |                         |  |                       |
| | +-------------------+                         |  |                       |
| +-----------------------------------------------+  |                       |
|              (no gap between images)               |                       |
| +-----------------------------------------------+  |                       |
| | First FwSec Image (Type 0xE0)                 |  |                       |
| +-----------------------------------------------+  |                       |
| | +-------------------+                         |  |                       |
| | | ROM Header        |                         |  |                       |
| | +-------------------+                         |  |                       |
| | | PCIR Structure    |                         |  |                       |
| | +-------------------+                         |  |                       |
| | | NPDE Structure    |                         |  |                       |
| | +-------------------+                         |  |                       |
| | | Image data        |                         |  |                       |
| | +-------------------+                         |  |                       |
| +-----------------------------------------------+  |                       |
|              (no gap between images)               |                       |
| +-----------------------------------------------+  |                       |
| | Second FwSec Image (Type 0xE0)                |  |                       |
| +-----------------------------------------------+  |                       |
| | +-------------------+                         |  |                       |
| | | ROM Header        |                         |  |                       |
| | +-------------------+                         |  |                       |
| | | PCIR Structure    |                         |  |                       |
| | +-------------------+                         |  |                       |
| | | NPDE Structure    |                         |  |                       |
| | +-------------------+                         |  |                       |
| |                                               |  |                       |
| | +-------------------+                         |  |                       |
| | | PMU Lookup Table  | <- falcon_data_offset <----+                       |
| | | +-------------+   |    pmu_lookup_table     |                          |
| | | | Entry 0x85  |   |                         |                          |
| | | | FWSEC_PROD  |   |                         |                          |
| | | +-------------+   |                         |                          |
| | +-------------------+                         |                          |
| |         |                                     |                          |
| |         | points to                           |                          |
| |         V                                     |                          |
| | +-------------------+                         |                          |
| | | FalconUCodeDescV3 | <- falcon_ucode_offset  |                          |
| | | (FWSEC Firmware)  |    fwsec_header()       |                          |
| | +-------------------+                         |                          |
| |         |   immediately followed  by...       |                          |
| |         V                                     |                          |
| | +----------------------------+                |                          |
| | | Signatures + FWSEC Ucode   |                |                          |
| | | fwsec_sigs(), fwsec_ucode()|                |                          |
| | +----------------------------+                |                          |
| +-----------------------------------------------+                          |
|                                                                            |
+----------------------------------------------------------------------------+
```

> [!NOTE]
>
> This diagram is created based on an GA-102 Ampere GPU as an example and could vary for future or other GPUs.

> [!NOTE]
>
> For more explanations of acronyms, see the detailed descriptions in `vbios.rs`.

<a id="rst-falcon-data-lookup"></a>

## Falcon data Lookup

A key part of the VBIOS extraction code (vbios.rs) is to find the location of the Falcon data in the VBIOS which contains the PMU lookup table. This lookup table is used to find the required Falcon ucode based on an application ID.

The location of the PMU lookup table is found by scanning the BIT ([BIOS Information Table](<https://download.nvidia.com/open-gpu-doc/BIOS-Information-Table/1/BIOS-Information-Table.html>)) tokens for a token with the id `BIT_TOKEN_ID_FALCON_DATA` (0x70) which indicates the offset of the same from the start of the VBIOS image. Unfortunately, the offset does not account for the EFI image located between the PciAt and FwSec images. The `vbios.rs` code compensates for this with appropriate arithmetic.

<a id="rst-bios-information-table"></a>

---

# GPU RFC Section

_Peios Kernel / Hardware and drivers / Graphics / rfc_

> For complex work, especially new uapi, it is often good to nail the high level design issues before getting lost in the code details. This section is meant to host such documentation:

<a id="rst-gpu-rfc-section"></a>

For complex work, especially new uapi, it is often good to nail the high level design issues before getting lost in the code details. This section is meant to host such documentation:

- Each RFC should be a section in this file, explaining the goal and main design considerations. Especially for uapi make sure you Cc: all relevant project mailing lists and involved people outside of dri-devel.

- For uapi structures add a file to this directory with and then pull the kerneldoc in like with real uapi headers.

- Once the code has landed move all the documentation to the right places in the main core, helper or driver sections.

- [GPU SVM Section](</kernel/hardware/gpu/rfc/gpusvm.md>)

- [I915 DG1/LMEM RFC Section](</kernel/hardware/gpu/rfc/i915-gem-lmem.md>)

- [i915_scheduler](<https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/Documentation/gpu/rfc/i915_scheduler.rst?id=9021cc14f7d98b4a1d2c932f52c5343d4d0f6b92>)

- [I915 Small BAR RFC Section](<https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/Documentation/gpu/rfc/i915_small_bar.rst?id=9021cc14f7d98b4a1d2c932f52c5343d4d0f6b92>)

- [I915 VM_BIND feature design and use cases](</kernel/hardware/gpu/rfc/i915-vm-bind.md>)

- [Linux Color Pipeline API](</kernel/hardware/gpu/rfc/color-pipeline.md>)

---

# Linux Color Pipeline API

_Peios Kernel / Hardware and drivers / Graphics / rfc_

> We would like to support pre-, and post-blending complex color transformations in display controller hardware in order to allow for HW-supported HDR use-cases, as well as to provide support to color-managed applications, such as video or…

<a id="rst-linux-color-pipeline-api"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-what-problem-are-we-solving"></a>

## What problem are we solving?

We would like to support pre-, and post-blending complex color transformations in display controller hardware in order to allow for HW-supported HDR use-cases, as well as to provide support to color-managed applications, such as video or image editors.

It is possible to support an HDR output on HW supporting the Colorspace and HDR Metadata drm_connector properties, but that requires the compositor or application to render and compose the content into one final buffer intended for display. Doing so is costly.

Most modern display HW offers various 1D LUTs, 3D LUTs, matrices, and other operations to support color transformations. These operations are often implemented in fixed-function HW and therefore much more power efficient than performing similar operations via shaders or CPU.

We would like to make use of this HW functionality to support complex color transformations with no, or minimal CPU or shader load. The switch between HW fixed-function blocks and shaders/CPU must be seamless with no visible difference when fallback to shaders/CPU is neceesary at any time.

<a id="rst-how-are-other-oses-solving-this-problem"></a>

## How are other OSes solving this problem?

The most widely supported use-cases regard HDR content, whether video or gaming.

Most OSes will specify the source content format (color gamut, encoding transfer function, and other metadata, such as max and average light levels) to a driver. Drivers will then program their fixed-function HW accordingly to map from a source content buffer's space to a display's space.

When fixed-function HW is not available the compositor will assemble a shader to ask the GPU to perform the transformation from the source content format to the display's format.

A compositor's mapping function and a driver's mapping function are usually entirely separate concepts. On OSes where a HW vendor has no insight into closed-source compositor code such a vendor will tune their color management code to visually match the compositor's. On other OSes, where both mapping functions are open to an implementer they will ensure both mappings match.

This results in mapping algorithm lock-in, meaning that no-one alone can experiment with or introduce new mapping algorithms and achieve consistent results regardless of which implementation path is taken.

<a id="rst-why-is-linux-different"></a>

## Why is Linux different?

Unlike other OSes, where there is one compositor for one or more drivers, on Linux we have a many-to-many relationship. Many compositors; many drivers. In addition each compositor vendor or community has their own view of how color management should be done. This is what makes Linux so beautiful.

This means that a HW vendor can now no longer tune their driver to one compositor, as tuning it to one could make it look fairly different from another compositor's color mapping.

We need a better solution.

<a id="rst-descriptive-api"></a>

## Descriptive API

An API that describes the source and destination colorspaces is a descriptive API. It describes the input and output color spaces but does not describe how precisely they should be mapped. Such a mapping includes many minute design decision that can greatly affect the look of the final result.

It is not feasible to describe such mapping with enough detail to ensure the same result from each implementation. In fact, these mappings are a very active research area.

<a id="rst-prescriptive-api"></a>

## Prescriptive API

A prescriptive API describes not the source and destination colorspaces. It instead prescribes a recipe for how to manipulate pixel values to arrive at the desired outcome.

This recipe is generally an ordered list of straight-forward operations, with clear mathematical definitions, such as 1D LUTs, 3D LUTs, matrices, or other operations that can be described in a precise manner.

<a id="rst-the-color-pipeline-api"></a>

## The Color Pipeline API

HW color management pipelines can significantly differ between HW vendors in terms of availability, ordering, and capabilities of HW blocks. This makes a common definition of color management blocks and their ordering nigh impossible. Instead we are defining an API that allows user space to discover the HW capabilities in a generic manner, agnostic of specific drivers and hardware.

<a id="rst-drm-colorop-object"></a>

## drm_colorop Object

To support the definition of color pipelines we define the DRM core object type drm_colorop. Individual drm_colorop objects will be chained via the NEXT property of a drm_colorop to constitute a color pipeline. Each drm_colorop object is unique, i.e., even if multiple color pipelines have the same operation they won't share the same drm_colorop object to describe that operation.

Note that drivers are not expected to map drm_colorop objects statically to specific HW blocks. The mapping of drm_colorop objects is entirely a driver-internal detail and can be as dynamic or static as a driver needs it to be. See more in the Driver Implementation Guide section below.

Each drm_colorop has three core properties:

TYPE: An enumeration property, defining the type of transformation, such as \* enumerated curve \* custom (uniform) 1D LUT \* 3x3 matrix \* 3x4 matrix \* 3D LUT \* etc.

Depending on the type of transformation other properties will describe more details.

BYPASS: A boolean property that can be used to easily put a block into bypass mode. The BYPASS property is not mandatory for a colorop, as long as the entire pipeline can get bypassed by setting the COLOR_PIPELINE on a plane to '0'.

NEXT: The ID of the next drm_colorop in a color pipeline, or 0 if this drm_colorop is the last in the chain.

An example of a drm_colorop object might look like one of these:



```text
/* 1D enumerated curve */
Color operation 42
├─ "TYPE": immutable enum {1D enumerated curve, 1D LUT, 3x3 matrix, 3x4 matrix, 3D LUT, etc.} = 1D enumerated curve
├─ "BYPASS": bool {true, false}
├─ "CURVE_1D_TYPE": enum {sRGB EOTF, sRGB inverse EOTF, PQ EOTF, PQ inverse EOTF, …}
└─ "NEXT": immutable color operation ID = 43

/* custom 4k entry 1D LUT */
Color operation 52
├─ "TYPE": immutable enum {1D enumerated curve, 1D LUT, 3x3 matrix, 3x4 matrix, 3D LUT, etc.} = 1D LUT
├─ "BYPASS": bool {true, false}
├─ "SIZE": immutable range = 4096
├─ "DATA": blob
└─ "NEXT": immutable color operation ID = 0

/* 17^3 3D LUT */
Color operation 72
├─ "TYPE": immutable enum {1D enumerated curve, 1D LUT, 3x3 matrix, 3x4 matrix, 3D LUT, etc.} = 3D LUT
├─ "BYPASS": bool {true, false}
├─ "SIZE": immutable range = 17
├─ "DATA": blob
└─ "NEXT": immutable color operation ID = 73
```

<a id="rst-drm-colorop-extensibility"></a>

### drm_colorop extensibility

Unlike existing DRM core objects, like &amp;drm_plane, drm_colorop is not extensible. This simplifies implementations and keeps all functionality for managing &amp;drm_colorop objects in the DRM core.

If there is a need one may introduce a simple &amp;drm_colorop_funcs function table in the future, for example to support an IN_FORMATS property on a &amp;drm_colorop.

If a driver requires the ability to create a driver-specific colorop object they will need to add &amp;drm_colorop func table support with support for the usual functions, like destroy, atomic_duplicate_state, and atomic_destroy_state.

<a id="rst-color-pipeline-plane-property"></a>

## COLOR_PIPELINE Plane Property

Color Pipelines are created by a driver and advertised via a new COLOR_PIPELINE enum property on each plane. Values of the property always include object id 0, which is the default and means all color processing is disabled. Additional values will be the object IDs of the first drm_colorop in a pipeline. A driver can create and advertise none, one, or more possible color pipelines. A DRM client will select a color pipeline by setting the COLOR PIPELINE to the respective value.

NOTE: Many DRM clients will set enumeration properties via the string value, often hard-coding it. Since this enumeration is generated based on the colorop object IDs it is important to perform the Color Pipeline Discovery, described below, instead of hard-coding color pipeline assignment. Drivers might generate the enum strings dynamically. Hard-coded strings might only work for specific drivers on a specific pieces of HW. Color Pipeline Discovery can work universally, as long as drivers implement the required color operations.

The COLOR_PIPELINE property is only exposed when the DRM_CLIENT_CAP_PLANE_COLOR_PIPELINE is set. Drivers shall ignore any existing pre-blend color operations when this cap is set, such as COLOR_RANGE and COLOR_ENCODING. If drivers want to support COLOR_RANGE or COLOR_ENCODING functionality when the color pipeline client cap is set, they are expected to expose colorops in the pipeline to allow for the appropriate color transformation.

Setting of the COLOR_PIPELINE plane property or drm_colorop properties is only allowed for userspace that sets this client cap.

An example of a COLOR_PIPELINE property on a plane might look like this:



```text
Plane 10
├─ "TYPE": immutable enum {Overlay, Primary, Cursor} = Primary
├─ …
└─ "COLOR_PIPELINE": enum {0, 42, 52} = 0
```

<a id="rst-color-pipeline-discovery"></a>

## Color Pipeline Discovery

A DRM client wanting color management on a drm_plane will:

1. Get the COLOR_PIPELINE property of the plane

2. iterate all COLOR_PIPELINE enum values

3. for each enum value walk the color pipeline (via the NEXT pointers) and see if the available color operations are suitable for the desired color management operations

If userspace encounters an unknown or unsuitable color operation during discovery it does not need to reject the entire color pipeline outright, as long as the unknown or unsuitable colorop has a "BYPASS" property. Drivers will ensure that a bypassed block does not have any effect.

An example of chained properties to define an AMD pre-blending color pipeline might look like this:



```text
Plane 10
├─ "TYPE" (immutable) = Primary
└─ "COLOR_PIPELINE": enum {0, 44} = 0

Color operation 44
├─ "TYPE" (immutable) = 1D enumerated curve
├─ "BYPASS": bool
├─ "CURVE_1D_TYPE": enum {sRGB EOTF, PQ EOTF} = sRGB EOTF
└─ "NEXT" (immutable) = 45

Color operation 45
├─ "TYPE" (immutable) = 3x4 Matrix
├─ "BYPASS": bool
├─ "DATA": blob
└─ "NEXT" (immutable) = 46

Color operation 46
├─ "TYPE" (immutable) = 1D enumerated curve
├─ "BYPASS": bool
├─ "CURVE_1D_TYPE": enum {sRGB Inverse EOTF, PQ Inverse EOTF} = sRGB EOTF
└─ "NEXT" (immutable) = 47

Color operation 47
├─ "TYPE" (immutable) = 1D LUT
├─ "SIZE": immutable range = 4096
├─ "DATA": blob
└─ "NEXT" (immutable) = 48

Color operation 48
├─ "TYPE" (immutable) = 3D LUT
├─ "DATA": blob
└─ "NEXT" (immutable) = 49

Color operation 49
├─ "TYPE" (immutable) = 1D enumerated curve
├─ "BYPASS": bool
├─ "CURVE_1D_TYPE": enum {sRGB EOTF, PQ EOTF} = sRGB EOTF
└─ "NEXT" (immutable) = 0
```

<a id="rst-color-pipeline-programming"></a>

## Color Pipeline Programming

Once a DRM client has found a suitable pipeline it will:

1. Set the COLOR_PIPELINE enum value to the one pointing at the first drm_colorop object of the desired pipeline

2. Set the properties for all drm_colorop objects in the pipeline to the desired values, setting BYPASS to true for unused drm_colorop blocks, and false for enabled drm_colorop blocks

3. Perform (TEST_ONLY or not) atomic commit with all the other KMS states it wishes to change

To configure the pipeline for an HDR10 PQ plane and blending in linear space, a compositor might perform an atomic commit with the following property values:



```text
Plane 10
└─ "COLOR_PIPELINE" = 42

Color operation 42
└─ "BYPASS" = true

Color operation 44
└─ "BYPASS" = true

Color operation 45
└─ "BYPASS" = true

Color operation 46
└─ "BYPASS" = true

Color operation 47
├─ "DATA" = Gamut mapping + tone mapping + night mode
└─ "BYPASS" = false

Color operation 48
├─ "CURVE_1D_TYPE" = PQ EOTF
└─ "BYPASS" = false
```

<a id="rst-driver-implementer-s-guide"></a>

## Driver Implementer's Guide

What does this all mean for driver implementations? As noted above the colorops can map to HW directly but don't need to do so. Here are some suggestions on how to think about creating your color pipelines:

- Try to expose pipelines that use already defined colorops, even if your hardware pipeline is split differently. This allows existing userspace to immediately take advantage of the hardware.

- Additionally, try to expose your actual hardware blocks as colorops. Define new colorop types where you believe it can offer significant benefits if userspace learns to program them.

- Avoid defining new colorops for compound operations with very narrow scope. If you have a hardware block for a special operation that cannot be split further, you can expose that as a new colorop type. However, try to not define colorops for "use cases", especially if they require you to combine multiple hardware blocks.

- Design new colorops as prescriptive, not descriptive; by the mathematical formula, not by the assumed input and output.

A defined colorop type must be deterministic. The exact behavior of the colorop must be documented entirely, whether via a mathematical formula or some other description. Its operation can depend only on its properties and input and nothing else, allowed error tolerance notwithstanding.

<a id="rst-driver-forward-backward-compatibility"></a>

## Driver Forward/Backward Compatibility

As this is uAPI drivers can't regress color pipelines that have been introduced for a given HW generation. New HW generations are free to abandon color pipelines advertised for previous generations. Nevertheless, it can be beneficial to carry support for existing color pipelines forward as those will likely already have support in DRM clients.

Introducing new colorops to a pipeline is fine, as long as they can be bypassed or are purely informational. DRM clients implementing support for the pipeline can always skip unknown properties as long as they can be confident that doing so will not cause unexpected results.

If a new colorop doesn't fall into one of the above categories (bypassable or informational) the modified pipeline would be unusable for user space. In this case a new pipeline should be defined.

<a id="rst-references"></a>

## References

1. [https://lore.kernel.org/dri-devel/QMers3awXvNCQlyhWdTtsPwkp5ie9bze_hD5nAccFW7a_RXlWjYB7MoUW_8CKLT2bSQwIXVi5H6VULYIxCdgvryZoAoJnC5lZgyK1QWn488=@emersion.fr/](<https://lore.kernel.org/dri-devel/QMers3awXvNCQlyhWdTtsPwkp5ie9bze_hD5nAccFW7a_RXlWjYB7MoUW_8CKLT2bSQwIXVi5H6VULYIxCdgvryZoAoJnC5lZgyK1QWn488=@emersion.fr/>)

---

# GPU SVM Section

_Peios Kernel / Hardware and drivers / Graphics / rfc_

> Rely only on core MM concepts (migration PTEs, page references, and page locking).

<a id="rst-gpu-svm-section"></a>

<!-- SPDX-License-Identifier: (GPL-2.0+ OR MIT) -->

<a id="rst-agreed-upon-design-principles"></a>

## Agreed upon design principles

- - **migrate_to_ram path**

    - Rely only on core MM concepts (migration PTEs, page references, and page locking).

    - No driver specific locks other than locks for hardware interaction in this path. These are not required and generally a bad idea to invent driver defined locks to seal core MM races.

    - An example of a driver-specific lock causing issues occurred before fixing do_swap_page to lock the faulting page. A driver-exclusive lock in migrate_to_ram produced a stable livelock if enough threads read the faulting page.

    - Partial migration is supported (i.e., a subset of pages attempting to migrate can actually migrate, with only the faulting page guaranteed to migrate).

    - Driver handles mixed migrations via retry loops rather than locking.

- - **Eviction**

    - Eviction is defined as migrating data from the GPU back to the CPU without a virtual address to free up GPU memory.

    - Only looking at physical memory data structures and locks as opposed to looking at virtual memory data structures and locks.

    - No looking at mm/vma structs or relying on those being locked.

    - The rationale for the above two points is that CPU virtual addresses can change at any moment, while the physical pages remain stable.

    - GPU page table invalidation, which requires a GPU virtual address, is handled via the notifier that has access to the GPU virtual address.

- - **GPU fault side**

    - mmap_read only used around core MM functions which require this lock and should strive to take mmap_read lock only in GPU SVM layer.

    - Big retry loop to handle all races with the mmu notifier under the gpu pagetable locks/mmu notifier range lock/whatever we end up calling those.

    - Races (especially against concurrent eviction or migrate_to_ram) should not be handled on the fault side by trying to hold locks; rather, they should be handled using retry loops. One possible exception is holding a BO's dma-resv lock during the initial migration to VRAM, as this is a well-defined lock that can be taken underneath the mmap_read lock.

    - One possible issue with the above approach is if a driver has a strict migration policy requiring GPU access to occur in GPU memory. Concurrent CPU access could cause a livelock due to endless retries. While no current user (Xe) of GPU SVM has such a policy, it is likely to be added in the future. Ideally, this should be resolved on the core-MM side rather than through a driver-side lock.

- - **Physical memory to virtual backpointer**

    - This does not work, as no pointers from physical memory to virtual memory should exist. mremap() is an example of the core MM updating the virtual address without notifying the driver of address change rather the driver only receiving the invalidation notifier.

    - The physical memory backpointer (page-&gt;zone_device_data) should remain stable from allocation to page free. Safely updating this against a concurrent user would be very difficult unless the page is free.

- - **GPU pagetable locking**

    - Notifier lock only protects range tree, pages valid state for a range (rather than seqno due to wider notifiers), pagetable entries, and mmu notifier seqno tracking, it is not a global lock to protect against races.

    - All races handled with big retry as mentioned above.

<a id="rst-overview-of-baseline-design"></a>

## Overview of baseline design


GPU Shared Virtual Memory (GPU SVM) layer for the Direct Rendering Manager (DRM)
is a component of the DRM framework designed to manage shared virtual memory
between the CPU and GPU. It enables efficient data exchange and processing
for GPU-accelerated applications by allowing memory sharing and
synchronization between the CPU's and GPU's virtual address spaces.

Key GPU SVM Components:

- Notifiers:
  Used for tracking memory intervals and notifying the GPU of changes,
  notifiers are sized based on a GPU SVM initialization parameter, with a
  recommendation of 512M or larger. They maintain a Red-BlacK tree and a
  list of ranges that fall within the notifier interval.  Notifiers are
  tracked within a GPU SVM Red-BlacK tree and list and are dynamically
  inserted or removed as ranges within the interval are created or
  destroyed.
- Ranges:
  Represent memory ranges mapped in a DRM device and managed by GPU SVM.
  They are sized based on an array of chunk sizes, which is a GPU SVM
  initialization parameter, and the CPU address space.  Upon GPU fault,
  the largest aligned chunk that fits within the faulting CPU address
  space is chosen for the range size. Ranges are expected to be
  dynamically allocated on GPU fault and removed on an MMU notifier UNMAP
  event. As mentioned above, ranges are tracked in a notifier's Red-Black
  tree.

- Operations:
  Define the interface for driver-specific GPU SVM operations such as
  range allocation, notifier allocation, and invalidations.

- Device Memory Allocations:
  Embedded structure containing enough information for GPU SVM to migrate
  to / from device memory.

- Device Memory Operations:
  Define the interface for driver-specific device memory operations
  release memory, populate pfns, and copy to / from device memory.

This layer provides interfaces for allocating, mapping, migrating, and
releasing memory ranges between the CPU and GPU. It handles all core memory
management interactions (DMA mapping, HMM, and migration) and provides
driver-specific virtual functions (vfuncs). This infrastructure is sufficient
to build the expected driver components for an SVM implementation as detailed
below.

Expected Driver Components:

- GPU page fault handler:
  Used to create ranges and notifiers based on the fault address,
  optionally migrate the range to device memory, and create GPU bindings.

- Garbage collector:
  Used to unmap and destroy GPU bindings for ranges.  Ranges are expected
  to be added to the garbage collector upon a MMU_NOTIFY_UNMAP event in
  notifier callback.

- Notifier callback:
  Used to invalidate and DMA unmap GPU bindings for ranges.



GPU SVM handles locking for core MM interactions, i.e., it locks/unlocks the
mmap lock as needed.

GPU SVM introduces a global notifier lock, which safeguards the notifier's
range RB tree and list, as well as the range's DMA mappings and sequence
number. GPU SVM manages all necessary locking and unlocking operations,
except for the recheck range's pages being valid
(drm_gpusvm_range_pages_valid) when the driver is committing GPU bindings.
This lock corresponds to the `driver->update` lock mentioned in
Documentation/mm/hmm.rst. Future revisions may transition from a GPU SVM
global lock to a per-notifier lock if finer-grained locking is deemed
necessary.

In addition to the locking mentioned above, the driver should implement a
lock to safeguard core GPU SVM function calls that modify state, such as
drm_gpusvm_range_find_or_insert and drm_gpusvm_range_remove. This lock is
denoted as 'driver_svm_lock' in code examples. Finer grained driver side
locking should also be possible for concurrent GPU fault processing within a
single GPU SVM. The 'driver_svm_lock' can be via drm_gpusvm_driver_set_lock
to add annotations to GPU SVM.



Partial unmapping of ranges (e.g., 1M out of 2M is unmapped by CPU resulting
in MMU_NOTIFY_UNMAP event) presents several challenges, with the main one
being that a subset of the range still has CPU and GPU mappings. If the
backing store for the range is in device memory, a subset of the backing
store has references. One option would be to split the range and device
memory backing store, but the implementation for this would be quite
complicated. Given that partial unmappings are rare and driver-defined range
sizes are relatively small, GPU SVM does not support splitting of ranges.

With no support for range splitting, upon partial unmapping of a range, the
driver is expected to invalidate and destroy the entire range. If the range
has device memory as its backing, the driver is also expected to migrate any
remaining pages back to RAM.



This section provides three examples of how to build the expected driver
components: the GPU page fault handler, the garbage collector, and the
notifier callback.

The generic code provided does not include logic for complex migration
policies, optimized invalidations, fined grained driver locking, or other
potentially required driver locking (e.g., DMA-resv locks).

1) GPU page fault handler

```c
int driver_bind_range(struct drm_gpusvm *gpusvm, struct drm_gpusvm_range *range)
{
        int err = 0;

        driver_alloc_and_setup_memory_for_bind(gpusvm, range);

        drm_gpusvm_notifier_lock(gpusvm);
        if (drm_gpusvm_range_pages_valid(range))
                driver_commit_bind(gpusvm, range);
        else
                err = -EAGAIN;
        drm_gpusvm_notifier_unlock(gpusvm);

        return err;
}

int driver_gpu_fault(struct drm_gpusvm *gpusvm, unsigned long fault_addr,
                     unsigned long gpuva_start, unsigned long gpuva_end)
{
        struct drm_gpusvm_ctx ctx = {};
        int err;

        driver_svm_lock();
retry:
        // Always process UNMAPs first so view of GPU SVM ranges is current
        driver_garbage_collector(gpusvm);

        range = drm_gpusvm_range_find_or_insert(gpusvm, fault_addr,
                                                gpuva_start, gpuva_end,
                                                &ctx);
        if (IS_ERR(range)) {
                err = PTR_ERR(range);
                goto unlock;
        }

        if (driver_migration_policy(range)) {
                err = drm_pagemap_populate_mm(driver_choose_drm_pagemap(),
                                              gpuva_start, gpuva_end, gpusvm->mm,
                                              ctx->timeslice_ms);
                if (err)        // CPU mappings may have changed
                        goto retry;
        }

        err = drm_gpusvm_range_get_pages(gpusvm, range, &ctx);
        if (err == -EOPNOTSUPP || err == -EFAULT || err == -EPERM) {    // CPU mappings changed
                if (err == -EOPNOTSUPP)
                        drm_gpusvm_range_evict(gpusvm, range);
                goto retry;
        } else if (err) {
                goto unlock;
        }

        err = driver_bind_range(gpusvm, range);
        if (err == -EAGAIN)     // CPU mappings changed
                goto retry

unlock:
        driver_svm_unlock();
        return err;
}
```

2) Garbage Collector

```c
void __driver_garbage_collector(struct drm_gpusvm *gpusvm,
                                struct drm_gpusvm_range *range)
{
        assert_driver_svm_locked(gpusvm);

        // Partial unmap, migrate any remaining device memory pages back to RAM
        if (range->flags.partial_unmap)
                drm_gpusvm_range_evict(gpusvm, range);

        driver_unbind_range(range);
        drm_gpusvm_range_remove(gpusvm, range);
}

void driver_garbage_collector(struct drm_gpusvm *gpusvm)
{
        assert_driver_svm_locked(gpusvm);

        for_each_range_in_garbage_collector(gpusvm, range)
                __driver_garbage_collector(gpusvm, range);
}
```

3) Notifier callback

```c
void driver_invalidation(struct drm_gpusvm *gpusvm,
                         struct drm_gpusvm_notifier *notifier,
                         const struct mmu_notifier_range *mmu_range)
{
        struct drm_gpusvm_ctx ctx = { .in_notifier = true, };
        struct drm_gpusvm_range *range = NULL;

        driver_invalidate_device_pages(gpusvm, mmu_range->start, mmu_range->end);

        drm_gpusvm_for_each_range(range, notifier, mmu_range->start,
                                  mmu_range->end) {
                drm_gpusvm_range_unmap_pages(gpusvm, range, &ctx);

                if (mmu_range->event != MMU_NOTIFY_UNMAP)
                        continue;

                drm_gpusvm_range_set_unmapped(range, mmu_range);
                driver_garbage_collector_add(gpusvm, range);
        }
}
```


<a id="rst-overview-of-drm-pagemap-design"></a>

## Overview of drm_pagemap design


The DRM pagemap layer is intended to augment the dev_pagemap functionality by
providing a way to populate a struct mm_struct virtual range with device
private pages and to provide helpers to abstract device memory allocations,
to migrate memory back and forth between device memory and system RAM and
to handle access (and in the future migration) between devices implementing
a fast interconnect that is not necessarily visible to the rest of the
system.

Typically the DRM pagemap receives requests from one or more DRM GPU SVM
instances to populate struct mm_struct virtual ranges with memory, and the
migration is best effort only and may thus fail. The implementation should
also handle device unbinding by blocking (return an -ENODEV) error for new
population requests and after that migrate all device pages to system ram.



Migration granularity typically follows the GPU SVM range requests, but
if there are clashes, due to races or due to the fact that multiple GPU
SVM instances have different views of the ranges used, and because of that
parts of a requested range is already present in the requested device memory,
the implementation has a variety of options. It can fail and it can choose
to populate only the part of the range that isn't already in device memory,
and it can evict the range to system before trying to migrate. Ideally an
implementation would just try to migrate the missing part of the range and
allocate just enough memory to do so.

When migrating to system memory as a response to a cpu fault or a device
memory eviction request, currently a full device memory allocation is
migrated back to system. Moving forward this might need improvement for
situations where a single page needs bouncing between system memory and
device memory due to, for example, atomic operations.

Key DRM pagemap components:

- Device Memory Allocations:
  Embedded structure containing enough information for the drm_pagemap to
  migrate to / from device memory.

- Device Memory Operations:
  Define the interface for driver-specific device memory operations
  release memory, populate pfns, and copy to / from device memory.


<a id="rst-possible-future-design-features"></a>

## Possible future design features

- - **Concurrent GPU faults**

    - CPU faults are concurrent so makes sense to have concurrent GPU faults.

    - Should be possible with fined grained locking in the driver GPU fault handler.

    - No expected GPU SVM changes required.

- - **Ranges with mixed system and device pages**

    - Can be added if required to drm_gpusvm_get_pages fairly easily.

- - **Multi-GPU support**

    - Work in progress and patches expected after initially landing on GPU SVM.

    - Ideally can be done with little to no changes to GPU SVM.

- - **Drop ranges in favor of radix tree**

    - May be desirable for faster notifiers.

- - **Compound device pages**

    - Nvidia, AMD, and Intel all have agreed expensive core MM functions in migrate device layer are a performance bottleneck, having compound device pages should help increase performance by reducing the number of these expensive calls.

- - **Higher order dma mapping for migration**

    - 4k dma mapping adversely affects migration performance on Intel hardware, higher order (2M) dma mapping should help here.

- Build common userptr implementation on top of GPU SVM

- Driver side madvise implementation and migration policies

- Pull in pending dma-mapping API changes from Leon / Nvidia when these land

---

# I915 DG1/LMEM RFC Section

_Peios Kernel / Hardware and drivers / Graphics / rfc_

> For upstream the overall plan for landing all the DG1 stuff and turning it for real, with all the uAPI bits is:

<a id="rst-i915-dg1-lmem-rfc-section"></a>

<a id="rst-upstream-plan"></a>

## Upstream plan

For upstream the overall plan for landing all the DG1 stuff and turning it for real, with all the uAPI bits is:

- Merge basic HW enabling of DG1(still without pciid)

- - **Merge the uAPI bits behind special CONFIG_BROKEN(or so) flag**

    - At this point we can still make changes, but importantly this lets us start running IGTs which can utilize local-memory in CI

- - **Convert over to TTM, make sure it all keeps working. Some of the work items:**

    - TTM shrinker for discrete

    - dma_resv_lockitem for full dma_resv_lock, i.e not just trylock

    - Use TTM CPU pagefault handler

    - Route shmem backend over to TTM SYSTEM for discrete

    - TTM purgeable object support

    - Move i915 buddy allocator over to TTM

- Send RFC(with mesa-dev on cc) for final sign off on the uAPI

- Add pciid for DG1 and turn on uAPI for real

---

# I915 GuC Submission/DRM Scheduler Section

_Peios Kernel / Hardware and drivers / Graphics / rfc_

> For upstream the overall plan for landing GuC submission and integrating the i915 with the DRM scheduler is:

<a id="rst-i915-guc-submission-drm-scheduler-section"></a>

<a id="rst-upstream-plan"></a>

## Upstream plan

For upstream the overall plan for landing GuC submission and integrating the i915 with the DRM scheduler is:

- - **Merge basic GuC submission**

    - Basic submission support for all gen11+ platforms

    - Not enabled by default on any current platforms but can be enabled via modparam enable\_guc

    - Lots of rework will need to be done to integrate with DRM scheduler so no need to nit pick everything in the code, it just should be functional, no major coding style / layering errors, and not regress execlists

    - Update IGTs / selftests as needed to work with GuC submission

    - Enable CI on supported platforms for a baseline

    - Rework / get CI heathly for GuC submission in place as needed

- - **Merge new parallel submission uAPI**

    - Bonding uAPI completely incompatible with GuC submission, plus it has severe design issues in general, which is why we want to retire it no matter what

    - New uAPI adds I915\_CONTEXT\_ENGINES\_EXT\_PARALLEL context setup step which configures a slot with N contexts

    - After I915\_CONTEXT\_ENGINES\_EXT\_PARALLEL a user can submit N batches to a slot in a single execbuf IOCTL and the batches run on the GPU in parallel

    - Initially only for GuC submission but execlists can be supported if needed

- - **Convert the i915 to use the DRM scheduler**

    - - **GuC submission backend fully integrated with DRM scheduler**

        - All request queues removed from backend (e.g. all backpressure handled in DRM scheduler)

        - Resets / cancels hook in DRM scheduler

        - Watchdog hooks into DRM scheduler

        - Lots of complexity of the GuC backend can be pulled out once integrated with DRM scheduler (e.g. state machine gets simpler, locking gets simpler, etc...)

    - - **Execlists backend will minimum required to hook in the DRM scheduler**

        - Legacy interface

        - Features like timeslicing / preemption / virtual engines would be difficult to integrate with the DRM scheduler and these features are not required for GuC submission as the GuC does these things for us

        - ROI low on fully integrating into DRM scheduler

        - Fully integrating would add lots of complexity to DRM scheduler

    - - **Port i915 priority inheritance / boosting feature in DRM scheduler**

        - Used for i915 page flip, may be useful to other DRM drivers as well

        - Will be an optional feature in the DRM scheduler

    - - **Remove in-order completion assumptions from DRM scheduler**

        - Even when using the DRM scheduler the backends will handle preemption, timeslicing, etc... so it is possible for jobs to finish out of order

    - Pull out i915 priority levels and use DRM priority levels

    - Optimize DRM scheduler as needed

<a id="rst-todos-for-guc-submission-upstream"></a>

## TODOs for GuC submission upstream

- Need an update to GuC firmware / i915 to enable error state capture

- Open source tool to decode GuC logs

- Public GuC spec

<a id="rst-new-uapi-for-basic-guc-submission"></a>

## New uAPI for basic GuC submission

No major changes are required to the uAPI for basic GuC submission. The only change is a new scheduler attribute: I915\_SCHEDULER\_CAP\_STATIC\_PRIORITY\_MAP. This attribute indicates the 2k i915 user priority levels are statically mapped into 3 levels as follows:

- -1k to -1 Low priority

- 0 Medium priority

- 1 to 1k High priority

This is needed because the GuC only has 4 priority bands. The highest priority band is reserved with the kernel. This aligns with the DRM scheduler priority levels too.

<a id="rst-spec-references"></a>

### Spec references:

- [https://www.khronos.org/registry/EGL/extensions/IMG/EGL\_IMG\_context\_priority.txt](<https://www.khronos.org/registry/EGL/extensions/IMG/EGL_IMG_context_priority.txt>)

- [https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/chap5.html\#devsandqueues-priority](<https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/chap5.html#devsandqueues-priority>)

- [https://spec.oneapi.com/level-zero/latest/core/api.html\#ze-command-queue-priority-t](<https://spec.oneapi.com/level-zero/latest/core/api.html#ze-command-queue-priority-t>)

<a id="rst-new-parallel-submission-uapi"></a>

## New parallel submission uAPI

The existing bonding uAPI is completely broken with GuC submission because whether a submission is a single context submit or parallel submit isn't known until execbuf time activated via the I915\_SUBMIT\_FENCE. To submit multiple contexts in parallel with the GuC the context must be explicitly registered with N contexts and all N contexts must be submitted in a single command to the GuC. The GuC interfaces do not support dynamically changing between N contexts as the bonding uAPI does. Hence the need for a new parallel submission interface. Also the legacy bonding uAPI is quite confusing and not intuitive at all. Furthermore I915\_SUBMIT\_FENCE is by design a future fence, so not really something we should continue to support.

The new parallel submission uAPI consists of 3 parts:

- Export engines logical mapping

- A 'set\_parallel' extension to configure contexts for parallel submission

- Extend execbuf2 IOCTL to support submitting N BBs in a single IOCTL

<a id="rst-export-engines-logical-mapping"></a>

### Export engines logical mapping

Certain use cases require BBs to be placed on engine instances in logical order (e.g. split-frame on gen11+). The logical mapping of engine instances can change based on fusing. Rather than making UMDs be aware of fusing, simply expose the logical mapping with the existing query engine info IOCTL. Also the GuC submission interface currently only supports submitting multiple contexts to engines in logical order which is a new requirement compared to execlists. Lastly, all current platforms have at most 2 engine instances and the logical order is the same as uAPI order. This will change on platforms with more than 2 engine instances.

A single bit will be added to drm\_i915\_engine\_info.flags indicating that the logical instance has been returned and a new field, drm\_i915\_engine\_info.logical\_instance, returns the logical instance.

<a id="rst-a-set-parallel-extension-to-configure-contexts-for-parallel-submission"></a>

### A 'set\_parallel' extension to configure contexts for parallel submission

The 'set\_parallel' extension configures a slot for parallel submission of N BBs. It is a setup step that must be called before using any of the contexts. See I915\_CONTEXT\_ENGINES\_EXT\_LOAD\_BALANCE or I915\_CONTEXT\_ENGINES\_EXT\_BOND for similar existing examples. Once a slot is configured for parallel submission the execbuf2 IOCTL can be called submitting N BBs in a single IOCTL. Initially only supports GuC submission. Execlists supports can be added later if needed.

Add I915\_CONTEXT\_ENGINES\_EXT\_PARALLEL\_SUBMIT and drm\_i915\_context\_engines\_parallel\_submit to the uAPI to implement this extension.

<!-- c:namespace-push: rfc -->


#### <a id="c-struct-i915_context_engines_parallel_submit"></a>`struct i915_context_engines_parallel_submit`

Configure engine for parallel submission.

**Definition**

```c
struct i915_context_engines_parallel_submit {
    struct i915_user_extension base;
    __u16 engine_index;
    __u16 width;
    __u16 num_siblings;
    __u16 mbz16;
    __u64 flags;
    __u64 mbz64[3];
    struct i915_engine_class_instance engines[];
};
```

**Members**

- `base`: base user extension.
- `engine_index`: slot for parallel engine
- `width`: number of contexts per parallel engine or in other words the
  number of batches in each submission
- `num_siblings`: number of siblings per context or in other words the
  number of possible placements for each submission
- `mbz16`: reserved for future use; must be zero
- `flags`: all undefined flags must be zero, currently not defined flags
- `mbz64`: reserved for future use; must be zero
- `engines`: 2-d array of engine instances to configure parallel engine

  length = width (i) * num_siblings (j)
  index = j + i * num_siblings

**Description**

Setup a slot in the context engine map to allow multiple BBs to be submitted
in a single execbuf IOCTL. Those BBs will then be scheduled to run on the GPU
in parallel. Multiple hardware contexts are created internally in the i915 to
run these BBs. Once a slot is configured for N BBs only N BBs can be
submitted in each execbuf IOCTL and this is implicit behavior e.g. The user
doesn't tell the execbuf IOCTL there are N BBs, the execbuf IOCTL knows how
many BBs there are based on the slot's configuration. The N BBs are the last
N buffer objects or first N if I915_EXEC_BATCH_FIRST is set.

The default placement behavior is to create implicit bonds between each
context if each context maps to more than 1 physical engine (e.g. context is
a virtual engine). Also we only allow contexts of same engine class and these
contexts must be in logically contiguous order. Examples of the placement
behavior are described below. Lastly, the default is to not allow BBs to be
preempted mid-batch. Rather insert coordinated preemption points on all
hardware contexts between each set of BBs. Flags could be added in the future
to change both of these default behaviors.

Returns -EINVAL if hardware context placement configuration is invalid or if
the placement configuration isn't supported on the platform / submission
interface.
Returns -ENODEV if extension isn't supported on the platform / submission
interface.

```none
Examples syntax:
CS[X] = generic engine of same class, logical instance X
INVALID = I915_ENGINE_CLASS_INVALID, I915_ENGINE_CLASS_INVALID_NONE

Example 1 pseudo code:
set_engines(INVALID)
set_parallel(engine_index=0, width=2, num_siblings=1,
             engines=CS[0],CS[1])

Results in the following valid placement:
CS[0], CS[1]

Example 2 pseudo code:
set_engines(INVALID)
set_parallel(engine_index=0, width=2, num_siblings=2,
             engines=CS[0],CS[2],CS[1],CS[3])

Results in the following valid placements:
CS[0], CS[1]
CS[2], CS[3]

This can be thought of as two virtual engines, each containing two
engines thereby making a 2D array. However, there are bonds tying the
entries together and placing restrictions on how they can be scheduled.
Specifically, the scheduler can choose only vertical columns from the 2D
array. That is, CS[0] is bonded to CS[1] and CS[2] to CS[3]. So if the
scheduler wants to submit to CS[0], it must also choose CS[1] and vice
versa. Same for CS[2] requires also using CS[3].
VE[0] = CS[0], CS[2]
VE[1] = CS[1], CS[3]

Example 3 pseudo code:
set_engines(INVALID)
set_parallel(engine_index=0, width=2, num_siblings=2,
             engines=CS[0],CS[1],CS[1],CS[3])

Results in the following valid and invalid placements:
CS[0], CS[1]
CS[1], CS[3] - Not logically contiguous, return -EINVAL
```


<!-- c:namespace-pop:  -->

<a id="rst-extend-execbuf2-ioctl-to-support-submitting-n-bbs-in-a-single-ioctl"></a>

### Extend execbuf2 IOCTL to support submitting N BBs in a single IOCTL

Contexts that have been configured with the 'set\_parallel' extension can only submit N BBs in a single execbuf2 IOCTL. The BBs are either the last N objects in the drm\_i915\_gem\_exec\_object2 list or the first N if I915\_EXEC\_BATCH\_FIRST is set. The number of BBs is implicit based on the slot submitted and how it has been configured by 'set\_parallel' or other extensions. No uAPI changes are required to the execbuf2 IOCTL.

---

# I915 Small BAR RFC Section

_Peios Kernel / Hardware and drivers / Graphics / rfc_

> Starting from DG2 we will have resizable BAR support for device local-memory(i.e I915_MEMORY_CLASS_DEVICE), but in some cases the final BAR size might still be smaller than the total probed_size. In such cases, only some subset of…

<a id="rst-i915-small-bar-rfc-section"></a>

Starting from DG2 we will have resizable BAR support for device local-memory(i.e I915\_MEMORY\_CLASS\_DEVICE), but in some cases the final BAR size might still be smaller than the total probed\_size. In such cases, only some subset of I915\_MEMORY\_CLASS\_DEVICE will be CPU accessible(for example the first 256M), while the remainder is only accessible via the GPU.

<a id="rst-i915-gem-create-ext-flag-needs-cpu-access-flag"></a>

## I915\_GEM\_CREATE\_EXT\_FLAG\_NEEDS\_CPU\_ACCESS flag

New gem\_create\_ext flag to tell the kernel that a BO will require CPU access. This becomes important when placing an object in I915\_MEMORY\_CLASS\_DEVICE, where underneath the device has a small BAR, meaning only some portion of it is CPU accessible. Without this flag the kernel will assume that CPU access is not required, and prioritize using the non-CPU visible portion of I915\_MEMORY\_CLASS\_DEVICE.


#### <a id="c-struct-__drm_i915_gem_create_ext"></a>`struct __drm_i915_gem_create_ext`

Existing gem_create behaviour, with added extension support using struct i915_user_extension.

**Definition**

```c
struct __drm_i915_gem_create_ext {
        __u64 size;
        __u32 handle;
    #define I915_GEM_CREATE_EXT_FLAG_NEEDS_CPU_ACCESS (1 << 0);
        __u32 flags;
    #define I915_GEM_CREATE_EXT_MEMORY_REGIONS 0;
    #define I915_GEM_CREATE_EXT_PROTECTED_CONTENT 1;
        __u64 extensions;
};
```

**Members**

- `size`: Requested size for the object.

  The (page-aligned) allocated size for the object will be returned.

  Note that for some devices we have might have further minimum
  page-size restrictions (larger than 4K), like for device local-memory.
  However in general the final size here should always reflect any
  rounding up, if for example using the I915_GEM_CREATE_EXT_MEMORY_REGIONS
  extension to place the object in device local-memory. The kernel will
  always select the largest minimum page-size for the set of possible
  placements as the value to use when rounding up the **size**.
- `handle`: Returned handle for the object.

  Object handles are nonzero.
- `flags`: Optional flags.

  Supported values:

  I915_GEM_CREATE_EXT_FLAG_NEEDS_CPU_ACCESS - Signal to the kernel that
  the object will need to be accessed via the CPU.

  Only valid when placing objects in I915_MEMORY_CLASS_DEVICE, and only
  strictly required on configurations where some subset of the device
  memory is directly visible/mappable through the CPU (which we also
  call small BAR), like on some DG2+ systems. Note that this is quite
  undesirable, but due to various factors like the client CPU, BIOS etc
  it's something we can expect to see in the wild. See
  [`__drm_i915_memory_region_info.probed_cpu_visible_size`](#c-struct-__drm_i915_memory_region_info) for how to
  determine if this system applies.

  Note that one of the placements MUST be I915_MEMORY_CLASS_SYSTEM, to
  ensure the kernel can always spill the allocation to system memory,
  if the object can't be allocated in the mappable part of
  I915_MEMORY_CLASS_DEVICE.

  Also note that since the kernel only supports flat-CCS on objects
  that can *only* be placed in I915_MEMORY_CLASS_DEVICE, we therefore
  don't support I915_GEM_CREATE_EXT_FLAG_NEEDS_CPU_ACCESS together with
  flat-CCS.

  Without this hint, the kernel will assume that non-mappable
  I915_MEMORY_CLASS_DEVICE is preferred for this object. Note that the
  kernel can still migrate the object to the mappable part, as a last
  resort, if userspace ever CPU faults this object, but this might be
  expensive, and so ideally should be avoided.

  On older kernels which lack the relevant small-bar uAPI support (see
  also [`__drm_i915_memory_region_info.probed_cpu_visible_size`](#c-struct-__drm_i915_memory_region_info)),
  usage of the flag will result in an error, but it should NEVER be
  possible to end up with a small BAR configuration, assuming we can
  also successfully load the i915 kernel module. In such cases the
  entire I915_MEMORY_CLASS_DEVICE region will be CPU accessible, and as
  such there are zero restrictions on where the object can be placed.
- `extensions`: The chain of extensions to apply to this object.

  This will be useful in the future when we need to support several
  different extensions, and we need to apply more than one when
  creating the object. See struct i915_user_extension.

  If we don't supply any extensions then we get the same old gem_create
  behaviour.

  For I915_GEM_CREATE_EXT_MEMORY_REGIONS usage see
  struct drm_i915_gem_create_ext_memory_regions.

  For I915_GEM_CREATE_EXT_PROTECTED_CONTENT usage see
  struct drm_i915_gem_create_ext_protected_content.

**Description**

Note that new buffer flags should be added here, at least for the stuff that
is immutable. Previously we would have two ioctls, one to create the object
with gem_create, and another to apply various parameters, however this
creates some ambiguity for the params which are considered immutable. Also in
general we're phasing out the various SET/GET ioctls.


<a id="rst-probed-cpu-visible-size-attribute"></a>

## probed\_cpu\_visible\_size attribute

New struct\_\_drm\_i915\_memory\_region attribute which returns the total size of the CPU accessible portion, for the particular region. This should only be applicable for I915\_MEMORY\_CLASS\_DEVICE. We also report the unallocated\_cpu\_visible\_size, alongside the unallocated\_size.

Vulkan will need this as part of creating a separate VkMemoryHeap with the VK\_MEMORY\_PROPERTY\_HOST\_VISIBLE\_BIT set, to represent the CPU visible portion, where the total size of the heap needs to be known. It also wants to be able to give a rough estimate of how memory can potentially be allocated.


#### <a id="c-struct-__drm_i915_memory_region_info"></a>`struct __drm_i915_memory_region_info`

Describes one region as known to the driver.

**Definition**

```c
struct __drm_i915_memory_region_info {
    struct drm_i915_gem_memory_class_instance region;
    __u32 rsvd0;
    __u64 probed_size;
    __u64 unallocated_size;
    union {
        __u64 rsvd1[8];
        struct {
            __u64 probed_cpu_visible_size;
            __u64 unallocated_cpu_visible_size;
        };
    };
};
```

**Members**

- `region`: The class:instance pair encoding
- `rsvd0`: MBZ
- `probed_size`: Memory probed by the driver

  Note that it should not be possible to ever encounter a zero value
  here, also note that no current region type will ever return -1 here.
  Although for future region types, this might be a possibility. The
  same applies to the other size fields.
- `unallocated_size`: Estimate of memory remaining

  Requires CAP_PERFMON or CAP_SYS_ADMIN to get reliable accounting.
  Without this (or if this is an older kernel) the value here will
  always equal the **probed_size**. Note this is only currently tracked
  for I915_MEMORY_CLASS_DEVICE regions (for other types the value here
  will always equal the **probed_size**).
- `{unnamed_union}`: anonymous
- `rsvd1`: MBZ
- `{unnamed_struct}`: anonymous
- `probed_cpu_visible_size`: Memory probed by the driver
  that is CPU accessible.

  This will be always be \<= **probed_size**, and the
  remainder (if there is any) will not be CPU
  accessible.

  On systems without small BAR, the **probed_size** will
  always equal the **probed_cpu_visible_size**, since all
  of it will be CPU accessible.

  Note this is only tracked for
  I915_MEMORY_CLASS_DEVICE regions (for other types the
  value here will always equal the **probed_size**).

  Note that if the value returned here is zero, then
  this must be an old kernel which lacks the relevant
  small-bar uAPI support (including
  I915_GEM_CREATE_EXT_FLAG_NEEDS_CPU_ACCESS), but on
  such systems we should never actually end up with a
  small BAR configuration, assuming we are able to load
  the kernel module. Hence it should be safe to treat
  this the same as when **probed_cpu_visible_size** ==
  **probed_size**.
- `unallocated_cpu_visible_size`: Estimate of CPU
  visible memory remaining

  Note this is only tracked for
  I915_MEMORY_CLASS_DEVICE regions (for other types the
  value here will always equal the
  **probed_cpu_visible_size**).

  Requires CAP_PERFMON or CAP_SYS_ADMIN to get reliable
  accounting.  Without this the value here will always
  equal the **probed_cpu_visible_size**. Note this is only
  currently tracked for I915_MEMORY_CLASS_DEVICE
  regions (for other types the value here will also
  always equal the **probed_cpu_visible_size**).

  If this is an older kernel the value here will be
  zero, see also **probed_cpu_visible_size**.

**Description**

Note this is using both struct drm_i915_query_item and struct drm_i915_query.
For this new query we are adding the new query id DRM_I915_QUERY_MEMORY_REGIONS
at [`drm_i915_query_item.query_id`](/kernel/hardware/gpu/driver-uapi.md#c-struct-drm_i915_query_item).


<a id="rst-error-capture-restrictions"></a>

## Error Capture restrictions

With error capture we have two new restrictions:

> 1\) Error capture is best effort on small BAR systems; if the pages are not CPU accessible, at the time of capture, then the kernel is free to skip trying to capture them.
>
> 2\) On discrete and newer integrated platforms we now reject error capture on recoverable contexts. In the future the kernel may want to blit during error capture, when for example something is not currently CPU accessible.

---

# I915 VM_BIND feature design and use cases

_Peios Kernel / Hardware and drivers / Graphics / rfc_

> DRM_I915_GEM_VM_BIND/UNBIND ioctls allows UMD to bind/unbind GEM buffer objects (BOs) or sections of a BOs at specified GPU virtual addresses on a specified address space (VM). These mappings (also referred to as persistent mappings) will…

<a id="rst-i915-vm-bind-feature-design-and-use-cases"></a>

<a id="rst-vm-bind-feature"></a>

## VM_BIND feature

DRM_I915_GEM_VM_BIND/UNBIND ioctls allows UMD to bind/unbind GEM buffer objects (BOs) or sections of a BOs at specified GPU virtual addresses on a specified address space (VM). These mappings (also referred to as persistent mappings) will be persistent across multiple GPU submissions (execbuf calls) issued by the UMD, without user having to provide a list of all required mappings during each submission (as required by older execbuf mode).

The VM_BIND/UNBIND calls allow UMDs to request a timeline out fence for signaling the completion of bind/unbind operation.

VM_BIND feature is advertised to user via I915_PARAM_VM_BIND_VERSION. User has to opt-in for VM_BIND mode of binding for an address space (VM) during VM creation time via I915_VM_CREATE_FLAGS_USE_VM_BIND extension.

VM_BIND/UNBIND ioctl calls executed on different CPU threads concurrently are not ordered. Furthermore, parts of the VM_BIND/UNBIND operations can be done asynchronously, when valid out fence is specified.

VM_BIND features include:

- Multiple Virtual Address (VA) mappings can map to the same physical pages of an object (aliasing).

- VA mapping can map to a partial section of the BO (partial binding).

- Support capture of persistent mappings in the dump upon GPU error.

- Support for userptr gem objects (no special uapi is required for this).

<a id="rst-tlb-flush-consideration"></a>

### TLB flush consideration

The i915 driver flushes the TLB for each submission and when an object's pages are released. The VM_BIND/UNBIND operation will not do any additional TLB flush. Any VM_BIND mapping added will be in the working set for subsequent submissions on that VM and will not be in the working set for currently running batches (which would require additional TLB flushes, which is not supported).

<a id="rst-execbuf-ioctl-in-vm-bind-mode"></a>

### Execbuf ioctl in VM_BIND mode

A VM in VM_BIND mode will not support older execbuf mode of binding. The execbuf ioctl handling in VM_BIND mode differs significantly from the older execbuf2 ioctl (See struct drm_i915_gem_execbuffer2). Hence, a new execbuf3 ioctl has been added to support VM_BIND mode. (See struct drm_i915_gem_execbuffer3). The execbuf3 ioctl will not accept any execlist. Hence, no support for implicit sync. It is expected that the below work will be able to support requirements of object dependency setting in all use cases:

"dma-buf: Add an API for exporting sync files" ([https://lwn.net/Articles/859290/](<https://lwn.net/Articles/859290/>))

The new execbuf3 ioctl only works in VM_BIND mode and the VM_BIND mode only works with execbuf3 ioctl for submission. All BOs mapped on that VM (through VM_BIND call) at the time of execbuf3 call are deemed required for that submission.

The execbuf3 ioctl directly specifies the batch addresses instead of as object handles as in execbuf2 ioctl. The execbuf3 ioctl will also not support many of the older features like in/out/submit fences, fence array, default gem context and many more (See struct drm_i915_gem_execbuffer3).

In VM_BIND mode, VA allocation is completely managed by the user instead of the i915 driver. Hence all VA assignment, eviction are not applicable in VM_BIND mode. Also, for determining object activeness, VM_BIND mode will not be using the i915_vma active reference tracking. It will instead use dma-resv object for that (See [VM_BIND dma_resv usage](<#rst-vm-bind-dma-resv-usage>)).

So, a lot of existing code supporting execbuf2 ioctl, like relocations, VA evictions, vma lookup table, implicit sync, vma active reference tracking etc., are not applicable for execbuf3 ioctl. Hence, all execbuf3 specific handling should be in a separate file and only functionalities common to these ioctls can be the shared code where possible.

<a id="rst-vm-private-objects"></a>

### VM_PRIVATE objects

By default, BOs can be mapped on multiple VMs and can also be dma-buf exported. Hence these BOs are referred to as Shared BOs. During each execbuf submission, the request fence must be added to the dma-resv fence list of all shared BOs mapped on the VM.

VM_BIND feature introduces an optimization where user can create BO which is private to a specified VM via I915_GEM_CREATE_EXT_VM_PRIVATE flag during BO creation. Unlike Shared BOs, these VM private BOs can only be mapped on the VM they are private to and can't be dma-buf exported. All private BOs of a VM share the dma-resv object. Hence during each execbuf submission, they need only one dma-resv fence list updated. Thus, the fast path (where required mappings are already bound) submission latency is O(1) w.r.t the number of VM private BOs.

<a id="rst-vm-bind-locking-hierarchy"></a>

### VM_BIND locking hierarchy

The locking design here supports the older (execlist based) execbuf mode, the newer VM_BIND mode, the VM_BIND mode with GPU page faults and possible future system allocator support (See [Shared Virtual Memory (SVM) support](<#rst-shared-virtual-memory-svm-support>)). The older execbuf mode and the newer VM_BIND mode without page faults manages residency of backing storage using dma_fence. The VM_BIND mode with page faults and the system allocator support do not use any dma_fence at all.

VM_BIND locking order is as below.

1. Lock-A: A vm_bind mutex will protect vm_bind lists. This lock is taken in vm_bind/vm_unbind ioctl calls, in the execbuf path and while releasing the mapping.

   In future, when GPU page faults are supported, we can potentially use a rwsem instead, so that multiple page fault handlers can take the read side lock to lookup the mapping and hence can run in parallel. The older execbuf mode of binding do not need this lock.

2. Lock-B: The object's dma-resv lock will protect i915_vma state and needs to be held while binding/unbinding a vma in the async worker and while updating dma-resv fence list of an object. Note that private BOs of a VM will all share a dma-resv object.

   The future system allocator support will use the HMM prescribed locking instead.

3. Lock-C: Spinlock/s to protect some of the VM's lists like the list of invalidated vmas (due to eviction and userptr invalidation) etc.

When GPU page faults are supported, the execbuf path do not take any of these locks. There we will simply smash the new batch buffer address into the ring and then tell the scheduler run that. The lock taking only happens from the page fault handler, where we take lock-A in read mode, whichever lock-B we need to find the backing storage (dma_resv lock for gem objects, and hmm/core mm for system allocator) and some additional locks (lock-D) for taking care of page table races. Page fault mode should not need to ever manipulate the vm lists, so won't ever need lock-C.

<a id="rst-vm-bind-lru-handling"></a>

### VM_BIND LRU handling

We need to ensure VM_BIND mapped objects are properly LRU tagged to avoid performance degradation. We will also need support for bulk LRU movement of VM_BIND objects to avoid additional latencies in execbuf path.

The page table pages are similar to VM_BIND mapped objects (See [Evictable page table allocations](<#rst-evictable-page-table-allocations>)) and are maintained per VM and needs to be pinned in memory when VM is made active (ie., upon an execbuf call with that VM). So, bulk LRU movement of page table pages is also needed.

<a id="rst-vm-bind-dma-resv-usage"></a>

### VM_BIND dma_resv usage

Fences needs to be added to all VM_BIND mapped objects. During each execbuf submission, they are added with DMA_RESV_USAGE_BOOKKEEP usage to prevent over sync (See enum dma_resv_usage). One can override it with either DMA_RESV_USAGE_READ or DMA_RESV_USAGE_WRITE usage during explicit object dependency setting.

Note that DRM_I915_GEM_WAIT and DRM_I915_GEM_BUSY ioctls do not check for DMA_RESV_USAGE_BOOKKEEP usage and hence should not be used for end of batch check. Instead, the execbuf3 out fence should be used for end of batch check (See struct drm_i915_gem_execbuffer3).

Also, in VM_BIND mode, use dma-resv apis for determining object activeness (See dma_resv_test_signaled() and dma_resv_wait_timeout()) and do not use the older i915_vma active reference tracking which is deprecated. This should be easier to get it working with the current TTM backend.

<a id="rst-mesa-use-case"></a>

### Mesa use case

VM_BIND can potentially reduce the CPU overhead in Mesa (both Vulkan and Iris), hence improving performance of CPU-bound applications. It also allows us to implement Vulkan's Sparse Resources. With increasing GPU hardware performance, reducing CPU overhead becomes more impactful.

<a id="rst-other-vm-bind-use-cases"></a>

## Other VM_BIND use cases

<a id="rst-long-running-compute-contexts"></a>

### Long running Compute contexts

Usage of dma-fence expects that they complete in reasonable amount of time. Compute on the other hand can be long running. Hence it is appropriate for compute to use user/memory fence (See [User/Memory Fence](<#rst-user-memory-fence>)) and dma-fence usage must be limited to in-kernel consumption only.

Where GPU page faults are not available, kernel driver upon buffer invalidation will initiate a suspend (preemption) of long running context, finish the invalidation, revalidate the BO and then resume the compute context. This is done by having a per-context preempt fence which is enabled when someone tries to wait on it and triggers the context preemption.

<a id="rst-user-memory-fence"></a>

#### User/Memory Fence

User/Memory fence is a &lt;address, value&gt; pair. To signal the user fence, the specified value will be written at the specified virtual address and wakeup the waiting process. User fence can be signaled either by the GPU or kernel async worker (like upon bind completion). User can wait on a user fence with a new user fence wait ioctl.

Here is some prior work on this: [https://patchwork.freedesktop.org/patch/349417/](<https://patchwork.freedesktop.org/patch/349417/>)

<a id="rst-low-latency-submission"></a>

#### Low Latency Submission

Allows compute UMD to directly submit GPU jobs instead of through execbuf ioctl. This is made possible by VM_BIND is not being synchronized against execbuf. VM_BIND allows bind/unbind of mappings required for the directly submitted jobs.

<a id="rst-debugger"></a>

### Debugger

With debug event interface user space process (debugger) is able to keep track of and act upon resources created by another process (debugged) and attached to GPU via vm_bind interface.

<a id="rst-gpu-page-faults"></a>

### GPU page faults

GPU page faults when supported (in future), will only be supported in the VM_BIND mode. While both the older execbuf mode and the newer VM_BIND mode of binding will require using dma-fence to ensure residency, the GPU page faults mode when supported, will not use any dma-fence as residency is purely managed by installing and removing/invalidating page table entries.

<a id="rst-page-level-hints-settings"></a>

### Page level hints settings

VM_BIND allows any hints setting per mapping instead of per BO. Possible hints include placement and atomicity. Sub-BO level placement hint will be even more relevant with upcoming GPU on-demand page fault support.

<a id="rst-page-level-cache-clos-settings"></a>

### Page level Cache/CLOS settings

VM_BIND allows cache/CLOS settings per mapping instead of per BO.

<a id="rst-evictable-page-table-allocations"></a>

### Evictable page table allocations

Make pagetable allocations evictable and manage them similar to VM_BIND mapped objects. Page table pages are similar to persistent mappings of a VM (difference here are that the page table pages will not have an i915_vma structure and after swapping pages back in, parent page link needs to be updated).

<a id="rst-shared-virtual-memory-svm-support"></a>

### Shared Virtual Memory (SVM) support

VM_BIND interface can be used to map system memory directly (without gem BO abstraction) using the HMM interface. SVM is only supported with GPU page faults enabled.

<a id="rst-vm-bind-uapi"></a>

## VM_BIND UAPI


**I915_PARAM_VM_BIND_VERSION**

VM_BIND feature version supported.
See typedef drm_i915_getparam_t param.

Specifies the VM_BIND feature version supported.
The following versions of VM_BIND have been defined:

0: No VM_BIND support.

- 1: In VM_UNBIND calls, the UMD must specify the exact mappings created

  previously with VM_BIND, the ioctl will not support unbinding multiple
  mappings or splitting them. Similarly, VM_BIND calls will not replace
  any existing mappings.

- 2: The restrictions on unbinding partial or multiple mappings is

  lifted, Similarly, binding will replace any mappings in the given range.

See struct drm_i915_gem_vm_bind and struct drm_i915_gem_vm_unbind.

**I915_VM_CREATE_FLAGS_USE_VM_BIND**

Flag to opt-in for VM_BIND mode of binding during VM creation.
See struct drm_i915_gem_vm_control flags.

The older execbuf2 ioctl will not support VM_BIND mode of operation.
For VM_BIND mode, we have new execbuf3 ioctl which will not accept any
execlist (See struct drm_i915_gem_execbuffer3 for more details).

#### <a id="c-struct-drm_i915_gem_timeline_fence"></a>`struct drm_i915_gem_timeline_fence`

An input or output timeline fence.

**Definition**

```c
struct drm_i915_gem_timeline_fence {
        __u32 handle;
        __u32 flags;
    #define I915_TIMELINE_FENCE_WAIT            (1 << 0);
    #define I915_TIMELINE_FENCE_SIGNAL          (1 << 1);
    #define __I915_TIMELINE_FENCE_UNKNOWN_FLAGS (-(I915_TIMELINE_FENCE_SIGNAL << 1));
        __u64 value;
};
```

**Members**

- `handle`: User's handle for a drm_syncobj to wait on or signal.
- `flags`: Supported flags are:

  I915_TIMELINE_FENCE_WAIT:
  Wait for the input fence before the operation.

  I915_TIMELINE_FENCE_SIGNAL:
  Return operation completion fence as output.
- `value`: A point in the timeline.
  Value must be 0 for a binary drm_syncobj. A Value of 0 for a
  timeline drm_syncobj is invalid as it turns a drm_syncobj into a
  binary one.

**Description**

The operation will wait for input fence to signal.

The returned output fence will be signaled after the completion of the
operation.

#### <a id="c-struct-drm_i915_gem_vm_bind"></a>`struct drm_i915_gem_vm_bind`

VA to object mapping to bind.

**Definition**

```c
struct drm_i915_gem_vm_bind {
        __u32 vm_id;
        __u32 handle;
        __u64 start;
        __u64 offset;
        __u64 length;
        __u64 flags;
    #define I915_GEM_VM_BIND_CAPTURE        (1 << 0);
        struct drm_i915_gem_timeline_fence fence;
        __u64 extensions;
};
```

**Members**

- `vm_id`: VM (address space) id to bind
- `handle`: Object handle
- `start`: Virtual Address start to bind
- `offset`: Offset in object to bind
- `length`: Length of mapping to bind
- `flags`: Supported flags are:

  I915_GEM_VM_BIND_CAPTURE:
  Capture this mapping in the dump upon GPU error.

  Note that **fence** carries its own flags.
- `fence`: Timeline fence for bind completion signaling.

  Timeline fence is of format struct drm_i915_gem_timeline_fence.

  It is an out fence, hence using I915_TIMELINE_FENCE_WAIT flag
  is invalid, and an error will be returned.

  If I915_TIMELINE_FENCE_SIGNAL flag is not set, then out fence
  is not requested and binding is completed synchronously.
- `extensions`: Zero-terminated chain of extensions.

  For future extensions. See struct i915_user_extension.

**Description**

This structure is passed to VM_BIND ioctl and specifies the mapping of GPU
virtual address (VA) range to the section of an object that should be bound
in the device page table of the specified address space (VM).
The VA range specified must be unique (ie., not currently bound) and can
be mapped to whole object or a section of the object (partial binding).
Multiple VA mappings can be created to the same section of the object
(aliasing).

The **start**, **offset** and **length** must be 4K page aligned. However the DG2 has
64K page size for device local memory and has compact page table. On that
platform, for binding device local-memory objects, the **start**, **offset** and
**length** must be 64K aligned. Also, UMDs should not mix the local memory 64K
page and the system memory 4K page bindings in the same 2M range.

Error code -EINVAL will be returned if **start**, **offset** and **length** are not
properly aligned. In version 1 (See I915_PARAM_VM_BIND_VERSION), error code
-ENOSPC will be returned if the VA range specified can't be reserved.

VM_BIND/UNBIND ioctl calls executed on different CPU threads concurrently
are not ordered. Furthermore, parts of the VM_BIND operation can be done
asynchronously, if valid **fence** is specified.

#### <a id="c-struct-drm_i915_gem_vm_unbind"></a>`struct drm_i915_gem_vm_unbind`

VA to object mapping to unbind.

**Definition**

```c
struct drm_i915_gem_vm_unbind {
    __u32 vm_id;
    __u32 rsvd;
    __u64 start;
    __u64 length;
    __u64 flags;
    struct drm_i915_gem_timeline_fence fence;
    __u64 extensions;
};
```

**Members**

- `vm_id`: VM (address space) id to bind
- `rsvd`: Reserved, MBZ
- `start`: Virtual Address start to unbind
- `length`: Length of mapping to unbind
- `flags`: Currently reserved, MBZ.

  Note that **fence** carries its own flags.
- `fence`: Timeline fence for unbind completion signaling.

  Timeline fence is of format struct drm_i915_gem_timeline_fence.

  It is an out fence, hence using I915_TIMELINE_FENCE_WAIT flag
  is invalid, and an error will be returned.

  If I915_TIMELINE_FENCE_SIGNAL flag is not set, then out fence
  is not requested and unbinding is completed synchronously.
- `extensions`: Zero-terminated chain of extensions.

  For future extensions. See struct i915_user_extension.

**Description**

This structure is passed to VM_UNBIND ioctl and specifies the GPU virtual
address (VA) range that should be unbound from the device page table of the
specified address space (VM). VM_UNBIND will force unbind the specified
range from device page table without waiting for any GPU job to complete.
It is UMDs responsibility to ensure the mapping is no longer in use before
calling VM_UNBIND.

If the specified mapping is not found, the ioctl will simply return without
any error.

VM_BIND/UNBIND ioctl calls executed on different CPU threads concurrently
are not ordered. Furthermore, parts of the VM_UNBIND operation can be done
asynchronously, if valid **fence** is specified.

#### <a id="c-struct-drm_i915_gem_execbuffer3"></a>`struct drm_i915_gem_execbuffer3`

Structure for DRM_I915_GEM_EXECBUFFER3 ioctl.

**Definition**

```c
struct drm_i915_gem_execbuffer3 {
    __u32 ctx_id;
    __u32 engine_idx;
    __u64 batch_address;
    __u64 flags;
    __u32 rsvd1;
    __u32 fence_count;
    __u64 timeline_fences;
    __u64 rsvd2;
    __u64 extensions;
};
```

**Members**

- `ctx_id`: Context id

  Only contexts with user engine map are allowed.
- `engine_idx`: Engine index

  An index in the user engine map of the context specified by **ctx_id**.
- `batch_address`: Batch gpu virtual address/es.

  For normal submission, it is the gpu virtual address of the batch
  buffer. For parallel submission, it is a pointer to an array of
  batch buffer gpu virtual addresses with array size equal to the
  number of (parallel) engines involved in that submission (See
  struct i915_context_engines_parallel_submit).
- `flags`: Currently reserved, MBZ
- `rsvd1`: Reserved, MBZ
- `fence_count`: Number of fences in **timeline_fences** array.
- `timeline_fences`: Pointer to an array of timeline fences.

  Timeline fences are of format struct drm_i915_gem_timeline_fence.
- `rsvd2`: Reserved, MBZ
- `extensions`: Zero-terminated chain of extensions.

  For future extensions. See struct i915_user_extension.

**Description**

DRM_I915_GEM_EXECBUFFER3 ioctl only works in VM_BIND mode and VM_BIND mode
only works with this ioctl for submission.
See I915_VM_CREATE_FLAGS_USE_VM_BIND.

#### <a id="c-struct-drm_i915_gem_create_ext_vm_private"></a>`struct drm_i915_gem_create_ext_vm_private`

Extension to make the object private to the specified VM.

**Definition**

```c
struct drm_i915_gem_create_ext_vm_private {
    #define I915_GEM_CREATE_EXT_VM_PRIVATE          2;
        struct i915_user_extension base;
        __u32 vm_id;
};
```

**Members**

- `base`: Extension link. See struct i915_user_extension.
- `vm_id`: Id of the VM to which the object is private

**Description**

See struct drm_i915_gem_create_ext.

---

# drm/xe Intel GFX Driver

_Peios Kernel / Hardware and drivers / Graphics / xe_

> The drm/xe driver supports some future GFX cards with rendering, display, compute and media. Support for currently available platforms like TGL, ADL, DG2, etc is provided to prototype the driver.

<a id="rst-drm-xe-intel-gfx-driver"></a>

<!-- SPDX-License-Identifier: (GPL-2.0+ OR MIT) -->

The drm/xe driver supports some future GFX cards with rendering, display, compute and media. Support for currently available platforms like TGL, ADL, DG2, etc is provided to prototype the driver.

- [Memory Management](</kernel/hardware/gpu/xe/xe-mm.md>)
- [Map Layer](</kernel/hardware/gpu/xe/xe-map.md>)
- [Migrate Layer](</kernel/hardware/gpu/xe/xe-migrate.md>)
- [Execution Queue](</kernel/hardware/gpu/xe/xe-exec-queue.md>)
- [Command submission](</kernel/hardware/gpu/xe/xe-cs.md>)
- [Runtime Power Management](</kernel/hardware/gpu/xe/xe-pm.md>)
- [Xe GT Frequency Management](</kernel/hardware/gpu/xe/xe-gt-freq.md>)
- [Pcode](</kernel/hardware/gpu/xe/xe-pcode.md>)
- [GT Multicast/Replicated (MCR) Register Support](</kernel/hardware/gpu/xe/xe-gt-mcr.md>)
- [Hardware workarounds](</kernel/hardware/gpu/xe/xe-wa.md>)
- [Register Table Processing](</kernel/hardware/gpu/xe/xe-rtp.md>)
- [Firmware](</kernel/hardware/gpu/xe/xe-firmware.md>)
- [Multi-tile Devices](</kernel/hardware/gpu/xe/xe-tile.md>)
- [Debugging](</kernel/hardware/gpu/xe/xe-debugging.md>)
- [Xe Device Coredump](</kernel/hardware/gpu/xe/xe-devcoredump.md>)
- [Xe Device Wedging](</kernel/hardware/gpu/xe/xe-device.md>)
- [Xe DRM client usage stats implementation](</kernel/hardware/gpu/xe/xe-drm-usage-stats.md>)
- [Xe Configfs](</kernel/hardware/gpu/xe/xe-configfs.md>)

---

# Xe DRM client usage stats implementation

_Peios Kernel / Hardware and drivers / Graphics / xe_

> Reference for Xe DRM client usage stats implementation.

<a id="rst-xe-drm-client-usage-stats-implementation"></a>
<a id="rst-xe-usage-stats"></a>

<!-- SPDX-License-Identifier: GPL-2.0+ -->


The drm/xe driver implements the DRM client usage stats specification as
documented in drm-client-usage-stats.

Example of the output showing the implemented key value pairs and entirety of
the currently possible format options:

```text
pos:    0
flags:  0100002
mnt_id: 26
ino:    685
drm-driver:     xe
drm-client-id:  3
drm-pdev:       0000:03:00.0
drm-total-system:       0
drm-shared-system:      0
drm-active-system:      0
drm-resident-system:    0
drm-purgeable-system:   0
drm-total-gtt:  192 KiB
drm-shared-gtt: 0
drm-active-gtt: 0
drm-resident-gtt:       192 KiB
drm-total-vram0:        23992 KiB
drm-shared-vram0:       16 MiB
drm-active-vram0:       0
drm-resident-vram0:     23992 KiB
drm-total-stolen:       0
drm-shared-stolen:      0
drm-active-stolen:      0
drm-resident-stolen:    0
drm-cycles-rcs: 28257900
drm-total-cycles-rcs:   7655183225
drm-cycles-bcs: 0
drm-total-cycles-bcs:   7655183225
drm-cycles-vcs: 0
drm-total-cycles-vcs:   7655183225
drm-engine-capacity-vcs:        2
drm-cycles-vecs:        0
drm-total-cycles-vecs:  7655183225
drm-engine-capacity-vecs:       2
drm-cycles-ccs: 0
drm-total-cycles-ccs:   7655183225
drm-engine-capacity-ccs:        4
```

Possible `drm-cycles-` key names are: `rcs`, `ccs`, `bcs`, `vcs`, `vecs` and
"other".

---

# Xe Configfs

_Peios Kernel / Hardware and drivers / Graphics / xe_

> Reference for Xe Configfs.

<a id="rst-xe-configfs-1"></a>
<a id="rst-xe-configfs"></a>

<!-- SPDX-License-Identifier: GPL-2.0+ -->


**Overview**

Configfs is a filesystem-based manager of kernel objects. Xe KMD registers a
configfs subsystem called `xe` that creates a directory in the mounted
configfs directory. The user can create devices under this directory and
configure them as necessary. See Documentation/filesystems/configfs.rst for
more information about how configfs works.

**Create devices**

To create a device, the `xe` module should already be loaded, but some
attributes can only be set before binding the device. It can be accomplished
by blocking the driver autoprobe:

```text
# echo 0 > /sys/bus/pci/drivers_autoprobe
# modprobe xe
```

In order to create a device, the user has to create a directory inside `xe`:

```text
# mkdir /sys/kernel/config/xe/0000:03:00.0/
```

Every device created is populated by the driver with entries that can be
used to configure it:

```text
/sys/kernel/config/xe/
├── 0000:00:02.0
│   └── ...
├── 0000:00:02.1
│   └── ...
:
└── 0000:03:00.0
    ├── survivability_mode
    ├── gt_types_allowed
    ├── engines_allowed
    └── enable_psmi
```

After configuring the attributes as per next section, the device can be
probed with:

```text
# echo 0000:03:00.0 > /sys/bus/pci/drivers/xe/bind
# # or
# echo 0000:03:00.0 > /sys/bus/pci/drivers_probe
```

**Configure Attributes**

**Survivability mode:**

Enable survivability mode on supported cards. This setting only takes
effect when probing the device. Example to enable it:

```text
# echo 1 > /sys/kernel/config/xe/0000:03:00.0/survivability_mode
```

This attribute can only be set before binding to the device.

**Allowed GT types:**

Allow only specific types of GTs to be detected and initialized by the
driver.  Any combination of GT types can be enabled/disabled, although
some settings will cause the device to fail to probe.

Writes support both comma- and newline-separated input format. Reads
will always return one GT type per line. "primary" and "media" are the
GT type names supported by this interface.

This attribute can only be set before binding to the device.

Examples:

Allow both primary and media GTs to be initialized and used.  This matches
the driver's default behavior:

```text
# echo 'primary,media' > /sys/kernel/config/xe/0000:03:00.0/gt_types_allowed
```

Allow only the primary GT of each tile to be initialized and used,
effectively disabling the media GT if it exists on the platform:

```text
# echo 'primary' > /sys/kernel/config/xe/0000:03:00.0/gt_types_allowed
```

Allow only the media GT of each tile to be initialized and used,
effectively disabling the primary GT.  **This configuration will cause
device probe failure on all current platforms, but may be allowed on
igpu platforms in the future**:

```text
# echo 'media' > /sys/kernel/config/xe/0000:03:00.0/gt_types_allowed
```

Disable all GTs.  Only other GPU IP (such as display) is potentially usable.
**This configuration will cause device probe failure on all current
platforms, but may be allowed on igpu platforms in the future**:

```text
# echo '' > /sys/kernel/config/xe/0000:03:00.0/gt_types_allowed
```

**Allowed engines:**

Allow only a set of engine(s) to be available, disabling the other engines
even if they are available in hardware. This is applied after HW fuses are
considered on each tile. Examples:

Allow only one render and one copy engines, nothing else:

```text
# echo 'rcs0,bcs0' > /sys/kernel/config/xe/0000:03:00.0/engines_allowed
```

Allow only compute engines and first copy engine:

```text
# echo 'ccs*,bcs0' > /sys/kernel/config/xe/0000:03:00.0/engines_allowed
```

Note that the engine names are the per-GT hardware names. On multi-tile
platforms, writing `rcs0,bcs0` to this file would allow the first render
and copy engines on each tile.

The requested configuration may not be supported by the platform and driver
may fail to probe. For example: if at least one copy engine is expected to be
available for migrations, but it's disabled. This is intended for debugging
purposes only.

This attribute can only be set before binding to the device.

**PSMI**

Enable extra debugging capabilities to trace engine execution. Only useful
during early platform enabling and requires additional hardware connected.
Once it's enabled, additionals WAs are added and runtime configuration is
done via debugfs. Example to enable it:

```text
# echo 1 > /sys/kernel/config/xe/0000:03:00.0/enable_psmi
```

This attribute can only be set before binding to the device.

**Context restore BB**

Allow to execute a batch buffer during any context switches. When the
GPU is restoring the context, it executes additional commands. It's useful
for testing additional workarounds and validating certain HW behaviors: it's
not intended for normal execution and will taint the kernel with TAINT_TEST
when used.

The syntax allows to pass straight instructions to be executed by the engine
in a batch buffer or set specific registers.

1. Generic instruction:

```text
<engine-class> cmd <instr> [[dword0] [dword1] [...]]
```

1. Simple register setting:

```text
<engine-class> reg <address> <value>
```

Commands are saved per engine class: all instances of that class will execute
those commands during context switch. The instruction, dword arguments,
addresses and values are in hex format like in the examples below.

1. Execute a LRI command to write 0xDEADBEEF to register 0x4f10 after the
   normal context restore:

```text
# echo 'rcs cmd 11000001 4F100 DEADBEEF' \
        > /sys/kernel/config/xe/0000:03:00.0/ctx_restore_post_bb
```

1. Execute a LRI command to write 0xDEADBEEF to register 0x4f10 at the
   beginning of the context restore:

```text
# echo 'rcs cmd 11000001 4F100 DEADBEEF' \
        > /sys/kernel/config/xe/0000:03:00.0/ctx_restore_mid_bb
```

1. Load certain values in a couple of registers (it can be used as a simpler
   alternative to the `cmd`) action:

```text
# cat > /sys/kernel/config/xe/0000:03:00.0/ctx_restore_post_bb <<EOF
rcs reg 4F100 DEADBEEF
rcs reg 4F104 FFFFFFFF
EOF
```

> [!NOTE]
> When using multiple lines, make sure to use a command that is
> implemented with a single write syscall, like HEREDOC.

Currently this is implemented only for post and mid context restore and
these attributes can only be set before binding to the device.

**Max SR-IOV Virtual Functions**

This config allows to limit number of the Virtual Functions (VFs) that can
be managed by the Physical Function (PF) driver, where value 0 disables the
PF mode (no VFs).

The default max_vfs config value is taken from the max_vfs modparam.

How to enable PF with support with unlimited (up to HW limit) number of VFs:

```text
# echo unlimited > /sys/kernel/config/xe/0000:00:02.0/sriov/max_vfs
# echo 0000:00:02.0 > /sys/bus/pci/drivers/xe/bind
```

How to enable PF with support up to 3 VFs:

```text
# echo 3 > /sys/kernel/config/xe/0000:00:02.0/sriov/max_vfs
# echo 0000:00:02.0 > /sys/bus/pci/drivers/xe/bind
```

How to disable PF mode and always run as native:

```text
# echo 0 > /sys/kernel/config/xe/0000:00:02.0/sriov/max_vfs
# echo 0000:00:02.0 > /sys/bus/pci/drivers/xe/bind
```

This setting only takes effect when probing the device.

**Remove devices**

The created device directories can be removed using `rmdir`:

```text
# rmdir /sys/kernel/config/xe/0000:03:00.0/
```


<a id="rst-internal-api"></a>

## Internal API


#### <a id="c-xe_configfs_check_device"></a>`xe_configfs_check_device()`

```c
void xe_configfs_check_device(struct pci_dev *pdev)
```

Test if device was configured by configfs

**Parameters**

- `struct pci_dev *pdev`: the `pci_dev` device to test

**Description**

Try to find the configfs group that belongs to the specified pci device
and print a diagnostic message if different than the default value.

#### <a id="c-xe_configfs_get_survivability_mode"></a>`xe_configfs_get_survivability_mode()`

```c
bool xe_configfs_get_survivability_mode(struct pci_dev *pdev)
```

get configfs survivability mode attribute

**Parameters**

- `struct pci_dev *pdev`: pci device

**Return**

survivability_mode attribute in configfs

#### <a id="c-xe_configfs_primary_gt_allowed"></a>`xe_configfs_primary_gt_allowed()`

```c
bool xe_configfs_primary_gt_allowed(struct pci_dev *pdev)
```

determine whether primary GTs are supported

**Parameters**

- `struct pci_dev *pdev`: pci device

**Return**

True if primary GTs are enabled, false if they have been disabled via
configfs.

#### <a id="c-xe_configfs_media_gt_allowed"></a>`xe_configfs_media_gt_allowed()`

```c
bool xe_configfs_media_gt_allowed(struct pci_dev *pdev)
```

determine whether media GTs are supported

**Parameters**

- `struct pci_dev *pdev`: pci device

**Return**

True if the media GTs are enabled, false if they have been disabled
via configfs.

#### <a id="c-xe_configfs_get_engines_allowed"></a>`xe_configfs_get_engines_allowed()`

```c
u64 xe_configfs_get_engines_allowed(struct pci_dev *pdev)
```

get engine allowed mask from configfs

**Parameters**

- `struct pci_dev *pdev`: pci device

**Return**

engine mask with allowed engines set in configfs

#### <a id="c-xe_configfs_get_psmi_enabled"></a>`xe_configfs_get_psmi_enabled()`

```c
bool xe_configfs_get_psmi_enabled(struct pci_dev *pdev)
```

get configfs enable_psmi setting

**Parameters**

- `struct pci_dev *pdev`: pci device

**Return**

enable_psmi setting in configfs

#### <a id="c-xe_configfs_get_ctx_restore_mid_bb"></a>`xe_configfs_get_ctx_restore_mid_bb()`

```c
u32 xe_configfs_get_ctx_restore_mid_bb(struct pci_dev *pdev, enum xe_engine_class class, const u32 **cs)
```

get configfs ctx_restore_mid_bb setting

**Parameters**

- `struct pci_dev *pdev`: pci device
- `enum xe_engine_class class`: hw engine class
- `const u32 **cs`: pointer to the bb to use - only valid during probe

**Return**

Number of dwords used in the mid_ctx_restore setting in configfs

#### <a id="c-xe_configfs_get_ctx_restore_post_bb"></a>`xe_configfs_get_ctx_restore_post_bb()`

```c
u32 xe_configfs_get_ctx_restore_post_bb(struct pci_dev *pdev, enum xe_engine_class class, const u32 **cs)
```

get configfs ctx_restore_post_bb setting

**Parameters**

- `struct pci_dev *pdev`: pci device
- `enum xe_engine_class class`: hw engine class
- `const u32 **cs`: pointer to the bb to use - only valid during probe

**Return**

Number of dwords used in the post_ctx_restore setting in configfs

#### <a id="c-xe_configfs_get_max_vfs"></a>`xe_configfs_get_max_vfs()`

```c
unsigned int xe_configfs_get_max_vfs(struct pci_dev *pdev)
```

Get number of VFs that could be managed

**Parameters**

- `struct pci_dev *pdev`: the `pci_dev` device

**Description**

Find the configfs group that belongs to the PCI device and return maximum
number of Virtual Functions (VFs) that could be managed by this device.
If configfs group is not present, use value of max_vfs module parameter.

**Return**

maximum number of VFs that could be managed.

---

# Command submission

_Peios Kernel / Hardware and drivers / Graphics / xe_

> Reference for Command submission.

<a id="rst-command-submission"></a>

<!-- SPDX-License-Identifier: (GPL-2.0+ OR MIT) -->


Execs have historically been rather complicated in DRM drivers (at least in
the i915) because a few things:

- Passing in a list BO which are read / written to creating implicit syncs
- Binding at exec time
- Flow controlling the ring at exec time

In Xe we avoid all of this complication by not allowing a BO list to be
passed into an exec, using the dma-buf implicit sync uAPI, have binds as
separate operations, and using the DRM scheduler to flow control the ring.
Let's deep dive on each of these.

We can get away from a BO list by forcing the user to use in / out fences on
every exec rather than the kernel tracking dependencies of BO (e.g. if the
user knows an exec writes to a BO and reads from the BO in the next exec, it
is the user's responsibility to pass in / out fence between the two execs).

We do not allow a user to trigger a bind at exec time rather we have a VM
bind IOCTL which uses the same in / out fence interface as exec. In that
sense, a VM bind is basically the same operation as an exec from the user
perspective. e.g. If an exec depends on a VM bind use the in / out fence
interface (struct drm_xe_sync) to synchronize like syncing between two
dependent execs.

Although a user cannot trigger a bind, we still have to rebind userptrs in
the VM that have been invalidated since the last exec, likewise we also have
to rebind BOs that have been evicted by the kernel. We schedule these rebinds
behind any pending kernel operations on any external BOs in VM or any BOs
private to the VM. This is accomplished by the rebinds waiting on BOs
DMA_RESV_USAGE_KERNEL slot (kernel ops) and kernel ops waiting on all BOs
slots (inflight execs are in the DMA_RESV_USAGE_BOOKKEEP for private BOs and
for external BOs).

Rebinds / dma-resv usage applies to non-compute mode VMs only as for compute
mode VMs we use preempt fences and a rebind worker (TODO: add link).

There is no need to flow control the ring in the exec as we write the ring at
submission time and set the DRM scheduler max job limit SIZE_OF_RING /
MAX_JOB_SIZE. The DRM scheduler will then hold all jobs until space in the
ring is available.

All of this results in a rather simple exec implementation.

**Flow**

```text
Parse input arguments
Wait for any async VM bind passed as in-fences to start
<----------------------------------------------------------------------|
Lock global VM lock in read mode                                       |
Pin userptrs (also finds userptr invalidated since last exec)          |
Lock exec (VM dma-resv lock, external BOs dma-resv locks)              |
Validate BOs that have been evicted                                    |
Create job                                                             |
Rebind invalidated userptrs + evicted BOs (non-compute-mode)           |
Add rebind fence dependency to job                                     |
Add job VM dma-resv bookkeeping slot (non-compute mode)                |
Add job to external BOs dma-resv write slots (non-compute mode)        |
Check if any userptrs invalidated since pin ------ Drop locks ---------|
Install in / out fences for job
Submit job
Unlock all
```

---

# Debugging

_Peios Kernel / Hardware and drivers / Graphics / xe_

> Reference for Debugging.

<a id="rst-debugging"></a>

<!-- SPDX-License-Identifier: (GPL-2.0+ OR MIT) -->


**Xe Asserts**

While Xe driver aims to be simpler than legacy i915 driver it is still
complex enough that some changes introduced while adding new functionality
could break the existing code.

Adding `drm_WARN` or `drm_err` to catch unwanted programming usage could lead
to undesired increased driver footprint and may impact production driver
performance as this additional code will be always present.

To allow annotate functions with additional detailed debug checks to assert
that all prerequisites are satisfied, without worrying about footprint or
performance penalty on production builds where all potential misuses
introduced during code integration were already fixed, we introduce family
of Xe assert macros that try to follow classic `assert()` utility:

* [`xe_assert()`](#c-xe_assert)
* [`xe_tile_assert()`](#c-xe_tile_assert)
* [`xe_gt_assert()`](#c-xe_gt_assert)

These macros are implemented on top of `drm_WARN`, but unlikely to the origin,
warning is triggered when provided condition is false. Additionally all above
assert macros cannot be used in expressions or as a condition, since
underlying code will be compiled out on non-debug builds.

Note that these macros are not intended for use to cover known gaps in the
implementation; for such cases use regular `drm_WARN` or `drm_err` and provide
valid safe fallback.

Also in cases where performance or footprint is not an issue, developers
should continue to use the regular `drm_WARN` or `drm_err` to ensure that bug
reports from production builds will contain meaningful diagnostics data.

Below code shows how asserts could help in debug to catch unplanned use:

```text
static void one_igfx(struct xe_device *xe)
{
        xe_assert(xe, xe->info.is_dgfx == false);
        xe_assert(xe, xe->info.tile_count == 1);
}

static void two_dgfx(struct xe_device *xe)
{
        xe_assert(xe, xe->info.is_dgfx);
        xe_assert(xe, xe->info.tile_count == 2);
}

void foo(struct xe_device *xe)
{
        if (xe->info.dgfx)
                return two_dgfx(xe);
        return one_igfx(xe);
}

void bar(struct xe_device *xe)
{
        if (drm_WARN_ON(xe->drm, xe->info.tile_count > 2))
                return;

        if (xe->info.tile_count == 2)
                return two_dgfx(xe);
        return one_igfx(xe);
}
```

#### <a id="c-xe_assert"></a>`xe_assert()`

```c
xe_assert(xe, condition)
```

warn if condition is false when debugging.

**Parameters**

- `xe`: the `struct xe_device` pointer to which `condition` applies
- `condition`: condition to check

**Description**

[`xe_assert()`](#c-xe_assert) uses `drm_WARN` to emit a warning and print additional information
that could be read from the `xe` pointer if provided `condition` is false.

Contrary to `drm_WARN`, [`xe_assert()`](#c-xe_assert) is effective only on debug builds
(`CONFIG_DRM_XE_DEBUG` must be enabled) and cannot be used in expressions
or as a condition.

See `Xe Asserts` for general usage guidelines.

#### <a id="c-xe_tile_assert"></a>`xe_tile_assert()`

```c
xe_tile_assert(tile, condition)
```

warn if condition is false when debugging.

**Parameters**

- `tile`: the `struct xe_tile` pointer to which `condition` applies
- `condition`: condition to check

**Description**

[`xe_tile_assert()`](#c-xe_tile_assert) uses `drm_WARN` to emit a warning and print additional
information that could be read from the `tile` pointer if provided `condition`
is false.

Contrary to `drm_WARN`, [`xe_tile_assert()`](#c-xe_tile_assert) is effective only on debug builds
(`CONFIG_DRM_XE_DEBUG` must be enabled) and cannot be used in expressions
or as a condition.

See `Xe Asserts` for general usage guidelines.

#### <a id="c-xe_gt_assert"></a>`xe_gt_assert()`

```c
xe_gt_assert(gt, condition)
```

warn if condition is false when debugging.

**Parameters**

- `gt`: the `struct xe_gt` pointer to which `condition` applies
- `condition`: condition to check

**Description**

[`xe_gt_assert()`](#c-xe_gt_assert) uses `drm_WARN` to emit a warning and print additional
information that could be safetely read from the `gt` pointer if provided
`condition` is false.

Contrary to `drm_WARN`, [`xe_gt_assert()`](#c-xe_gt_assert) is effective only on debug builds
(`CONFIG_DRM_XE_DEBUG` must be enabled) and cannot be used in expressions
or as a condition.

See `Xe Asserts` for general usage guidelines.

---

# Xe Device Coredump

_Peios Kernel / Hardware and drivers / Graphics / xe_

> Reference for Xe Device Coredump.

<a id="rst-xe-device-coredump"></a>

<!-- SPDX-License-Identifier: (GPL-2.0+ OR MIT) -->


Xe uses dev_coredump infrastructure for exposing the crash errors in a
standardized way. Once a crash occurs, devcoredump exposes a temporary
node under `/sys/class/devcoredump/devcd<m>/`. The same node is also
accessible in `/sys/class/drm/card<n>/device/devcoredump/`. The
`failing_device` symlink points to the device that crashed and created the
coredump.

The following characteristics are observed by xe when creating a device
coredump:

- **Snapshot at hang**:
  The 'data' file contains a snapshot of the HW and driver states at the time
  the hang happened. Due to the driver recovering from resets/crashes, it may
  not correspond to the state of the system when the file is read by
  userspace.

- **Coredump release**:
  After a coredump is generated, it stays in kernel memory until released by
  userspace by writing anything to it, or after an internal timer expires. The
  exact timeout may vary and should not be relied upon. Example to release
  a coredump:

```shell
$ > /sys/class/drm/card0/device/devcoredump/data
```

- **First failure only**:
  In general, the first hang is the most critical one since the following
  hangs can be a consequence of the initial hang. For this reason a snapshot
  is taken only for the first failure. Until the devcoredump is released by
  userspace or kernel, all subsequent hangs do not override the snapshot nor
  create new ones. Devcoredump has a delayed work queue that will eventually
  delete the file node and free all the dump information.


<a id="rst-internal-api"></a>

## Internal API


#### <a id="c-xe_devcoredump_read"></a>`xe_devcoredump_read()`

```c
ssize_t xe_devcoredump_read(char *buffer, loff_t offset, size_t count, void *data, size_t datalen)
```

Read data from the Xe device coredump snapshot

**Parameters**

- `char *buffer`: Destination buffer to copy the coredump data into
- `loff_t offset`: Offset in the coredump data to start reading from
- `size_t count`: Number of bytes to read
- `void *data`: Pointer to the xe_devcoredump structure
- `size_t datalen`: Length of the data (unused)

**Description**

Reads a chunk of the coredump snapshot data into the provided buffer.
If the devcoredump is smaller than 1.5 GB (XE_DEVCOREDUMP_CHUNK_MAX),
it is read directly from a pre-written buffer. For larger devcoredumps,
the pre-written buffer must be periodically repopulated from the snapshot
state due to kmalloc size limitations.

**Return**

Number of bytes copied on success, or a negative error code on failure.

#### <a id="c-xe_devcoredump"></a>`xe_devcoredump()`

```c
void xe_devcoredump(struct xe_exec_queue *q, struct xe_sched_job *job, const char *fmt, ...)
```

Take the required snapshots and initialize coredump device.

**Parameters**

- `struct xe_exec_queue *q`: The faulty xe_exec_queue, where the issue was detected.
- `struct xe_sched_job *job`: The faulty xe_sched_job, where the issue was detected.
- `const char *fmt`: Printf format + args to describe the reason for the core dump
- `...`: variable arguments

**Description**

This function should be called at the crash time within the serialized
gt_reset. It is skipped if we still have the core dump device available
with the information of the 'first' snapshot.

#### <a id="c-xe_print_blob_ascii85"></a>`xe_print_blob_ascii85()`

```c
void xe_print_blob_ascii85(struct drm_printer *p, const char *prefix, char suffix, const void *blob, size_t offset, size_t size)
```

print a BLOB to some useful location in ASCII85

**Parameters**

- `struct drm_printer *p`: the printer object to output to
- `const char *prefix`: optional prefix to add to output string
- `char suffix`: optional suffix to add at the end. 0 disables it and is
  not added to the output, which is useful when using multiple calls
  to dump data to **p**
- `const void *blob`: the Binary Large OBject to dump out
- `size_t offset`: offset in bytes to skip from the front of the BLOB, must be a multiple of sizeof(u32)
- `size_t size`: the size in bytes of the BLOB, must be a multiple of sizeof(u32)

**Description**

The output is split into multiple calls to [`drm_puts()`](/kernel/hardware/gpu/drm-internals.md#c-drm_puts) because some print
targets, e.g. dmesg, cannot handle arbitrarily long lines. These targets may
add newlines, as is the case with dmesg: each [`drm_puts()`](/kernel/hardware/gpu/drm-internals.md#c-drm_puts) call creates a
separate line.

There is also a scheduler yield call to prevent the 'task has been stuck for
120s' kernel hang check feature from firing when printing to a slow target
such as dmesg over a serial port.

---

# Xe Device Wedging

_Peios Kernel / Hardware and drivers / Graphics / xe_

> Reference for Xe Device Wedging.

<a id="rst-xe-device-wedging-1"></a>
<a id="rst-xe-device-wedging"></a>

<!-- SPDX-License-Identifier: (GPL-2.0+ OR MIT) -->


Xe driver uses drm device wedged uevent as documented in Documentation/gpu/drm-uapi.rst.
When device is in wedged state, every IOCTL will be blocked and GT cannot
be used. The conditions under which the driver declares the device wedged
depend on the wedged mode configuration (see `enum xe_wedged_mode`). The
default recovery method for a wedged state is rebind/bus-reset.

Another recovery method is vendor-specific. Below are the cases that send
`WEDGED=vendor-specific` recovery method in drm device wedged uevent.

**Case: Firmware Flash**

**Identification Hint**

`WEDGED=vendor-specific` drm device wedged uevent with
Runtime Survivability mode is used to notify
admin/userspace consumer about the need for a firmware flash.

**Recovery Procedure**

Once `WEDGED=vendor-specific` drm device wedged uevent is received, follow
the below steps

- Check Runtime Survivability mode sysfs.
  If enabled, firmware flash is required to recover the device.

  /sys/bus/pci/devices/\<device>/survivability_mode

- Admin/userspace consumer can use firmware flashing tools like fwupd to flash
  firmware and restore device to normal operation.

---

# Execution Queue

_Peios Kernel / Hardware and drivers / Graphics / xe_

> Reference for Execution Queue.

<a id="rst-execution-queue"></a>

<!-- SPDX-License-Identifier: (GPL-2.0+ OR MIT) -->


An Execution queue is an interface for the HW context of execution.
The user creates an execution queue, submits the GPU jobs through those
queues and in the end destroys them.

Execution queues can also be created by XeKMD itself for driver internal
operations like object migration etc.

An execution queue is associated with a specified HW engine or a group of
engines (belonging to the same tile and engine class) and any GPU job
submitted on the queue will be run on one of these engines.

An execution queue is tied to an address space (VM). It holds a reference
of the associated VM and the underlying Logical Ring Context/s (LRC/s)
until the queue is destroyed.

The execution queue sits on top of the submission backend. It opaquely
handles the GuC and Execlist backends whichever the platform uses, and
the ring operations the different engine classes support.


<a id="rst-multi-queue-group"></a>

## Multi Queue Group


Multi Queue Group is another mode of execution supported by the compute
and blitter copy command streamers (CCS and BCS, respectively). It is
an enhancement of the existing hardware architecture and leverages the
same submission model. It enables support for efficient, parallel
execution of multiple queues within a single shared context. The multi
queue group functionality is only supported with GuC submission backend.
All the queues of a group must use the same address space (VM).

The DRM_XE_EXEC_QUEUE_SET_PROPERTY_MULTI_QUEUE execution queue property
supports creating a multi queue group and adding queues to a queue group.

The XE_EXEC_QUEUE_CREATE ioctl call with above property with value field
set to DRM_XE_MULTI_GROUP_CREATE, will create a new multi queue group with
the queue being created as the primary queue (aka q0) of the group. To add
secondary queues to the group, they need to be created with the above
property with id of the primary queue as the value. The properties of
the primary queue (like priority, time slice) applies to the whole group.
So, these properties can't be set for secondary queues of a group.

The hardware does not support removing a queue from a multi-queue group.
However, queues can be dynamically added to the group. A group can have
up to 64 queues. To support this, XeKMD holds references to LRCs of the
queues even after the queues are destroyed by the user until the whole
group is destroyed. The secondary queues hold a reference to the primary
queue thus preventing the group from being destroyed when user destroys
the primary queue. Once the primary queue is destroyed, secondary queues
can't be added to the queue group and new job submissions on existing
secondary queues are not allowed.

The queues of a multi queue group can set their priority within the group
through the DRM_XE_EXEC_QUEUE_SET_PROPERTY_MULTI_QUEUE_PRIORITY property.
This multi queue priority can also be set dynamically through the
XE_EXEC_QUEUE_SET_PROPERTY ioctl. This is the only other property
supported by the secondary queues of a multi queue group, other than
DRM_XE_EXEC_QUEUE_SET_PROPERTY_MULTI_QUEUE.

When GuC reports an error on any of the queues of a multi queue group,
the queue cleanup mechanism is invoked for all the queues of the group
as hardware cannot make progress on the multi queue context.

Refer multi-queue-group-guc-interface for multi queue group GuC
interface.


<a id="rst-multi-queue-group-guc-interface-1"></a>
<a id="rst-multi-queue-group-guc-interface"></a>

## Multi Queue Group GuC interface


The multi queue group coordination between KMD and GuC is through a software
construct called Context Group Page (CGP). The CGP is a KMD managed 4KB page
allocated in the global GTT.

CGP format:

```text
+-----------+---------------------------+---------------------------------------------+
| DWORD     | Name                      | Description                                 |
+-----------+---------------------------+---------------------------------------------+
| 0         | Version                   | Bits [15:8]=Major ver, [7:0]=Minor ver      |
+-----------+---------------------------+---------------------------------------------+
| 1..15     | RESERVED                  | MBZ                                         |
+-----------+---------------------------+---------------------------------------------+
| 16        | KMD_QUEUE_UPDATE_MASK_DW0 | KMD queue mask for queues 31..0             |
+-----------+---------------------------+---------------------------------------------+
| 17        | KMD_QUEUE_UPDATE_MASK_DW1 | KMD queue mask for queues 63..32            |
+-----------+---------------------------+---------------------------------------------+
| 18..31    | RESERVED                  | MBZ                                         |
+-----------+---------------------------+---------------------------------------------+
| 32        | Q0CD_DW0                  | Queue 0 context LRC descriptor lower DWORD  |
+-----------+---------------------------+---------------------------------------------+
| 33        | Q0ContextIndex            | Context ID for Queue 0                      |
+-----------+---------------------------+---------------------------------------------+
| 34        | Q1CD_DW0                  | Queue 1 context LRC descriptor lower DWORD  |
+-----------+---------------------------+---------------------------------------------+
| 35        | Q1ContextIndex            | Context ID for Queue 1                      |
+-----------+---------------------------+---------------------------------------------+
| ...       |...                        | ...                                         |
+-----------+---------------------------+---------------------------------------------+
| 158       | Q63CD_DW0                 | Queue 63 context LRC descriptor lower DWORD |
+-----------+---------------------------+---------------------------------------------+
| 159       | Q63ContextIndex           | Context ID for Queue 63                     |
+-----------+---------------------------+---------------------------------------------+
| 160..1024 | RESERVED                  | MBZ                                         |
+-----------+---------------------------+---------------------------------------------+
```

While registering Q0 with GuC, CGP is updated with Q0 entry and GuC is notified
through XE_GUC_ACTION_REGISTER_CONTEXT_MULTI_QUEUE H2G message which specifies
the CGP address. When the secondary queues are added to the group, the CGP is
updated with entry for that queue and GuC is notified through the H2G interface
XE_GUC_ACTION_MULTI_QUEUE_CONTEXT_CGP_SYNC. GuC responds to these H2G messages
with a XE_GUC_ACTION_NOTIFY_MULTIQ_CONTEXT_CGP_SYNC_DONE G2H message. GuC also
sends a XE_GUC_ACTION_NOTIFY_MULTI_QUEUE_CGP_CONTEXT_ERROR notification for any
error in the CGP. Only one of these CGP update messages can be outstanding
(waiting for GuC response) at any time. The bits in KMD_QUEUE_UPDATE_MASK_DW*
fields indicate which queue entry is being updated in the CGP.

The primary queue (Q0) represents the multi queue group context in GuC and
submission on any queue of the group must be through Q0 GuC interface only.

As it is not required to register secondary queues with GuC, the secondary queue
context ids in the CGP are populated with Q0 context id.


<a id="rst-internal-api"></a>

## Internal API


#### <a id="c-enum-xe_multi_queue_priority"></a>`enum xe_multi_queue_priority`

Multi Queue priority values

**Constants**

- `XE_MULTI_QUEUE_PRIORITY_LOW`: Priority low
- `XE_MULTI_QUEUE_PRIORITY_NORMAL`: Priority normal
- `XE_MULTI_QUEUE_PRIORITY_HIGH`: Priority high

**Description**

The priority values of the queues within the multi queue group.

#### <a id="c-struct-xe_exec_queue_group"></a>`struct xe_exec_queue_group`

Execution multi queue group

**Definition**

```c
struct xe_exec_queue_group {
    struct xe_exec_queue *primary;
    struct xe_bo *cgp_bo;
    struct xarray xa;
    struct list_head list;
    struct mutex list_lock;
    bool sync_pending;
    bool banned;
};
```

**Members**

- `primary`: Primary queue of this group
- `cgp_bo`: BO for the Context Group Page
- `xa`: xarray to store LRCs
- `list`: List of all secondary queues in the group
- `list_lock`: Secondary queue list lock
- `sync_pending`: CGP_SYNC_DONE g2h response pending
- `banned`: Group banned

**Description**

Contains multi queue group information.

#### <a id="c-struct-xe_exec_queue"></a>`struct xe_exec_queue`

Execution queue

**Definition**

```c
struct xe_exec_queue {
        struct xe_file *xef;
        struct xe_gt *gt;
        struct xe_hw_engine *hwe;
        struct kref refcount;
        struct xe_vm *vm;
        struct xe_vm *user_vm;
        enum xe_engine_class class;
        u32 logical_mask;
        char name[MAX_FENCE_NAME_LEN];
        u16 width;
        u16 msix_vec;
        struct xe_hw_fence_irq *fence_irq;
        struct dma_fence *last_fence;
    #define EXEC_QUEUE_FLAG_KERNEL                  BIT(0);
    #define EXEC_QUEUE_FLAG_PERMANENT               BIT(1);
    #define EXEC_QUEUE_FLAG_VM                      BIT(2);
    #define EXEC_QUEUE_FLAG_BIND_ENGINE_CHILD       BIT(3);
    #define EXEC_QUEUE_FLAG_HIGH_PRIORITY           BIT(4);
    #define EXEC_QUEUE_FLAG_LOW_LATENCY             BIT(5);
    #define EXEC_QUEUE_FLAG_MIGRATE                 BIT(6);
        unsigned long flags;
        union {
            struct list_head multi_gt_list;
            struct list_head multi_gt_link;
        };
        union {
            struct xe_execlist_exec_queue *execlist;
            struct xe_guc_exec_queue *guc;
        };
        struct {
            struct xe_exec_queue_group *group;
            struct list_head link;
            enum xe_multi_queue_priority priority;
            u8 pos;
            u8 valid:1;
            u8 is_primary:1;
        } multi_queue;
        struct {
            u32 timeslice_us;
            u32 preempt_timeout_us;
            u32 job_timeout_ms;
            enum xe_exec_queue_priority priority;
        } sched_props;
        struct {
            struct dma_fence *pfence;
            u64 context;
            u32 seqno;
            struct list_head link;
        } lr;
    #define XE_EXEC_QUEUE_TLB_INVAL_PRIMARY_GT      0;
    #define XE_EXEC_QUEUE_TLB_INVAL_MEDIA_GT        1;
    #define XE_EXEC_QUEUE_TLB_INVAL_COUNT           (XE_EXEC_QUEUE_TLB_INVAL_MEDIA_GT  + 1);
        struct {
            struct xe_dep_scheduler *dep_scheduler;
            struct dma_fence *last_fence;
        } tlb_inval[XE_EXEC_QUEUE_TLB_INVAL_COUNT];
        struct {
            u8 type;
            struct list_head link;
        } pxp;
        struct drm_syncobj *ufence_syncobj;
        u64 ufence_timeline_value;
        void *replay_state;
        const struct xe_exec_queue_ops *ops;
        const struct xe_ring_ops *ring_ops;
        struct drm_sched_entity *entity;
    #define XE_MAX_JOB_COUNT_PER_EXEC_QUEUE 1000;
        atomic_t job_cnt;
        u64 tlb_flush_seqno;
        struct list_head hw_engine_group_link;
        struct xe_lrc *lrc[] ;
};
```

**Members**

- `xef`: Back pointer to xe file if this is user created exec queue
- `gt`: GT structure this exec queue can submit to
- `hwe`: A hardware of the same class. May (physical engine) or may not
  (virtual engine) be where jobs actual engine up running. Should never
  really be used for submissions.
- `refcount`: ref count of this exec queue
- `vm`: VM (address space) for this exec queue
- `user_vm`: User VM (address space) for this exec queue (bind queues
  only)
- `class`: class of this exec queue
- `logical_mask`: logical mask of where job submitted to exec queue can run
- `name`: name of this exec queue
- `width`: width (number BB submitted per exec) of this exec queue
- `msix_vec`: MSI-X vector (for platforms that support it)
- `fence_irq`: fence IRQ used to signal job completion
- `last_fence`: last fence for tlb invalidation, protected by
  vm->lock in write mode
- `flags`: flags for this exec queue, should statically setup aside from ban
  bit
- `{unnamed_union}`: anonymous
- `multi_gt_list`: list head for VM bind engines if multi-GT
- `multi_gt_link`: link for VM bind engines if multi-GT
- `{unnamed_union}`: anonymous
- `execlist`: execlist backend specific state for exec queue
- `guc`: GuC backend specific state for exec queue
- `multi_queue`: Multi queue information
- `multi_queue.group`: Queue group information
- `multi_queue.link`: Link into group's secondary queues list
- `multi_queue.priority`: Queue priority within the multi-queue group
- `multi_queue.pos`: Position of queue within the multi-queue group
- `multi_queue.valid`: Queue belongs to a multi queue group
- `multi_queue.is_primary`: Is primary queue (Q0) of the group
- `sched_props`: scheduling properties
- `sched_props.timeslice_us`: timeslice period in micro-seconds
- `sched_props.preempt_timeout_us`: preemption timeout in micro-seconds
- `sched_props.job_timeout_ms`: job timeout in milliseconds
- `sched_props.priority`: priority of this exec queue
- `lr`: long-running exec queue state
- `lr.pfence`: preemption fence
- `lr.context`: preemption fence context
- `lr.seqno`: preemption fence seqno
- `lr.link`: link into VM's list of exec queues
- `tlb_inval`: TLB invalidations exec queue state
- `tlb_inval.dep_scheduler`: The TLB invalidation
  dependency scheduler
- `pxp`: PXP info tracking
- `pxp.type`: PXP session type used by this queue
- `pxp.link`: link into the list of PXP exec queues
- `ufence_syncobj`: User fence syncobj
- `ufence_timeline_value`: User fence timeline value
- `replay_state`: GPU hang replay state
- `ops`: submission backend exec queue operations
- `ring_ops`: ring operations for this exec queue
- `entity`: DRM sched entity for this exec queue (1 to 1 relationship)
- `job_cnt`: number of drm jobs in this exec queue
- `tlb_flush_seqno`: The seqno of the last rebind tlb flush performed
  Protected by **vm**'s resv. Unused if **vm** == NULL.
- `hw_engine_group_link`: link into exec queues in the same hw engine group
- `lrc`: logical ring context for this exec queue

**Description**

Contains all state necessary for submissions. Can either be a user object or
a kernel object.

#### <a id="c-struct-xe_exec_queue_ops"></a>`struct xe_exec_queue_ops`

Submission backend exec queue operations

**Definition**

```c
struct xe_exec_queue_ops {
    int (*init)(struct xe_exec_queue *q);
    void (*kill)(struct xe_exec_queue *q);
    void (*fini)(struct xe_exec_queue *q);
    void (*destroy)(struct xe_exec_queue *q);
    int (*set_priority)(struct xe_exec_queue *q, enum xe_exec_queue_priority priority);
    int (*set_timeslice)(struct xe_exec_queue *q, u32 timeslice_us);
    int (*set_preempt_timeout)(struct xe_exec_queue *q, u32 preempt_timeout_us);
    int (*set_multi_queue_priority)(struct xe_exec_queue *q, enum xe_multi_queue_priority priority);
    int (*suspend)(struct xe_exec_queue *q);
    int (*suspend_wait)(struct xe_exec_queue *q);
    void (*resume)(struct xe_exec_queue *q);
    bool (*reset_status)(struct xe_exec_queue *q);
};
```

**Members**

- `init`: Initialize exec queue for submission backend
- `kill`: Kill inflight submissions for backend
- `fini`: Undoes the `init()` for submission backend
- `destroy`: Destroy exec queue for submission backend. The backend
  function must call `xe_exec_queue_fini()` (which will in turn call the
  `fini()` backend function) to ensure the queue is properly cleaned up.
- `set_priority`: Set priority for exec queue
- `set_timeslice`: Set timeslice for exec queue
- `set_preempt_timeout`: Set preemption timeout for exec queue
- `set_multi_queue_priority`: Set multi queue priority
- `suspend`: Suspend exec queue from executing, allowed to be called
  multiple times in a row before resume with the caveat that
  suspend_wait returns before calling suspend again.
- `suspend_wait`: Wait for an exec queue to suspend executing, should be
  call after suspend. In dma-fencing path thus must return within a
  reasonable amount of time. -ETIME return shall indicate an error
  waiting for suspend resulting in associated VM getting killed.
  -EAGAIN return indicates the wait should be tried again, if the wait
  is within a work item, the work item should be requeued as deadlock
  avoidance mechanism.
- `resume`: Resume exec queue execution, exec queue must be in a suspended
  state and dma fence returned from most recent suspend call must be
  signalled when this function is called.
- `reset_status`: check exec queue reset status



#### <a id="c-xe_exec_queue_is_multi_queue"></a>`xe_exec_queue_is_multi_queue()`

```c
bool xe_exec_queue_is_multi_queue(struct xe_exec_queue *q)
```

Whether an exec_queue is part of a queue group.

**Parameters**

- `struct xe_exec_queue *q`: The exec_queue

**Return**

True if the exec_queue is part of a queue group, false otherwise.

#### <a id="c-xe_exec_queue_is_multi_queue_primary"></a>`xe_exec_queue_is_multi_queue_primary()`

```c
bool xe_exec_queue_is_multi_queue_primary(struct xe_exec_queue *q)
```

Whether an exec_queue is primary queue of a multi queue group.

**Parameters**

- `struct xe_exec_queue *q`: The exec_queue

**Return**

True if **q** is primary queue of a queue group, false otherwise.

#### <a id="c-xe_exec_queue_is_multi_queue_secondary"></a>`xe_exec_queue_is_multi_queue_secondary()`

```c
bool xe_exec_queue_is_multi_queue_secondary(struct xe_exec_queue *q)
```

Whether an exec_queue is secondary queue of a multi queue group.

**Parameters**

- `struct xe_exec_queue *q`: The exec_queue

**Return**

True if **q** is secondary queue of a queue group, false otherwise.

#### <a id="c-xe_exec_queue_multi_queue_primary"></a>`xe_exec_queue_multi_queue_primary()`

```c
struct xe_exec_queue * xe_exec_queue_multi_queue_primary(struct xe_exec_queue *q)
```

Get multi queue group's primary queue

**Parameters**

- `struct xe_exec_queue *q`: The exec_queue

**Description**

If **q** belongs to a multi queue group, then the primary queue of the group will
be returned. Otherwise, **q** will be returned.

#### <a id="c-xe_exec_queue_idle_skip_suspend"></a>`xe_exec_queue_idle_skip_suspend()`

```c
bool xe_exec_queue_idle_skip_suspend(struct xe_exec_queue *q)
```

Can exec queue skip suspend

**Parameters**

- `struct xe_exec_queue *q`: The exec_queue

**Description**

If an exec queue is not parallel and is idle, the suspend steps can be
skipped in the submission backend immediatley signaling the suspend fence.
Parallel queues cannot skip this step due to limitations in the submission
backend.

**Return**

True if exec queue is idle and can skip suspend steps, False
otherwise



#### <a id="c-xe_exec_queue_create_bind"></a>`xe_exec_queue_create_bind()`

```c
struct xe_exec_queue * xe_exec_queue_create_bind(struct xe_device *xe, struct xe_tile *tile, struct xe_vm *user_vm, u32 flags, u64 extensions)
```

Create bind exec queue.

**Parameters**

- `struct xe_device *xe`: Xe device.
- `struct xe_tile *tile`: tile which bind exec queue belongs to.
- `struct xe_vm *user_vm`: The user VM which this exec queue belongs to
- `u32 flags`: exec queue creation flags
- `u64 extensions`: exec queue creation extensions

**Description**

Normalize bind exec queue creation. Bind exec queue is tied to migration VM
for access to physical memory required for page table programming. On a
faulting devices the reserved copy engine instance must be used to avoid
deadlocking (user binds cannot get stuck behind faults as kernel binds which
resolve faults depend on user binds). On non-faulting devices any copy engine
can be used.

Returns exec queue on success, ERR_PTR on failure

#### <a id="c-xe_exec_queue_lrc"></a>`xe_exec_queue_lrc()`

```c
struct xe_lrc * xe_exec_queue_lrc(struct xe_exec_queue *q)
```

Get the LRC from exec queue.

**Parameters**

- `struct xe_exec_queue *q`: The exec_queue.

**Description**

Retrieves the primary LRC for the exec queue. Note that this function
returns only the first LRC instance, even when multiple parallel LRCs
are configured.

**Return**

Pointer to LRC on success, error on failure

#### <a id="c-xe_exec_queue_is_lr"></a>`xe_exec_queue_is_lr()`

```c
bool xe_exec_queue_is_lr(struct xe_exec_queue *q)
```

Whether an exec_queue is long-running

**Parameters**

- `struct xe_exec_queue *q`: The exec_queue

**Return**

True if the exec_queue is long-running, false otherwise.

#### <a id="c-xe_exec_queue_is_idle"></a>`xe_exec_queue_is_idle()`

```c
bool xe_exec_queue_is_idle(struct xe_exec_queue *q)
```

Whether an exec_queue is idle.

**Parameters**

- `struct xe_exec_queue *q`: The exec_queue

**Description**

FIXME: Need to determine what to use as the short-lived
timeline lock for the exec_queues, so that the return value
of this function becomes more than just an advisory
snapshot in time. The timeline lock must protect the
seqno from racing submissions on the same exec_queue.
Typically vm->resv, but user-created timeline locks use the migrate vm
and never grabs the migrate vm->resv so we have a race there.

**Return**

True if the exec_queue is idle, false otherwise.

#### <a id="c-xe_exec_queue_update_run_ticks"></a>`xe_exec_queue_update_run_ticks()`

```c
void xe_exec_queue_update_run_ticks(struct xe_exec_queue *q)
```

Update run time in ticks for this exec queue from hw

**Parameters**

- `struct xe_exec_queue *q`: The exec queue

**Description**

Update the timestamp saved by HW for this exec queue and save run ticks
calculated by using the delta from last update.

#### <a id="c-xe_exec_queue_kill"></a>`xe_exec_queue_kill()`

```c
void xe_exec_queue_kill(struct xe_exec_queue *q)
```

permanently stop all execution from an exec queue

**Parameters**

- `struct xe_exec_queue *q`: The exec queue

**Description**

This function permanently stops all activity on an exec queue. If the queue
is actively executing on the HW, it will be kicked off the engine; any
pending jobs are discarded and all future submissions are rejected.
This function is safe to call multiple times.

#### <a id="c-xe_exec_queue_last_fence_put"></a>`xe_exec_queue_last_fence_put()`

```c
void xe_exec_queue_last_fence_put(struct xe_exec_queue *q, struct xe_vm *vm)
```

Drop ref to last fence

**Parameters**

- `struct xe_exec_queue *q`: The exec queue
- `struct xe_vm *vm`: The VM the engine does a bind or exec for

#### <a id="c-xe_exec_queue_last_fence_put_unlocked"></a>`xe_exec_queue_last_fence_put_unlocked()`

```c
void xe_exec_queue_last_fence_put_unlocked(struct xe_exec_queue *q)
```

Drop ref to last fence unlocked

**Parameters**

- `struct xe_exec_queue *q`: The exec queue

**Description**

Only safe to be called from `xe_exec_queue_destroy()`.

#### <a id="c-xe_exec_queue_last_fence_get"></a>`xe_exec_queue_last_fence_get()`

```c
struct dma_fence * xe_exec_queue_last_fence_get(struct xe_exec_queue *q, struct xe_vm *vm)
```

Get last fence

**Parameters**

- `struct xe_exec_queue *q`: The exec queue
- `struct xe_vm *vm`: The VM the engine does a bind or exec for

**Description**

Get last fence, takes a ref

**Return**

last fence if not signaled, dma fence stub if signaled

#### <a id="c-xe_exec_queue_last_fence_get_for_resume"></a>`xe_exec_queue_last_fence_get_for_resume()`

```c
struct dma_fence * xe_exec_queue_last_fence_get_for_resume(struct xe_exec_queue *q, struct xe_vm *vm)
```

Get last fence

**Parameters**

- `struct xe_exec_queue *q`: The exec queue
- `struct xe_vm *vm`: The VM the engine does a bind or exec for

**Description**

Get last fence, takes a ref. Only safe to be called in the context of
resuming the hw engine group's long-running exec queue, when the group
semaphore is held.

**Return**

last fence if not signaled, dma fence stub if signaled

#### <a id="c-xe_exec_queue_last_fence_set"></a>`xe_exec_queue_last_fence_set()`

```c
void xe_exec_queue_last_fence_set(struct xe_exec_queue *q, struct xe_vm *vm, struct dma_fence *fence)
```

Set last fence

**Parameters**

- `struct xe_exec_queue *q`: The exec queue
- `struct xe_vm *vm`: The VM the engine does a bind or exec for
- `struct dma_fence *fence`: The fence

**Description**

Set the last fence for the engine. Increases reference count for fence, when
closing engine xe_exec_queue_last_fence_put should be called.

#### <a id="c-xe_exec_queue_tlb_inval_last_fence_put"></a>`xe_exec_queue_tlb_inval_last_fence_put()`

```c
void xe_exec_queue_tlb_inval_last_fence_put(struct xe_exec_queue *q, struct xe_vm *vm, unsigned int type)
```

Drop ref to last TLB invalidation fence

**Parameters**

- `struct xe_exec_queue *q`: The exec queue
- `struct xe_vm *vm`: The VM the engine does a bind for
- `unsigned int type`: Either primary or media GT

#### <a id="c-xe_exec_queue_tlb_inval_last_fence_put_unlocked"></a>`xe_exec_queue_tlb_inval_last_fence_put_unlocked()`

```c
void xe_exec_queue_tlb_inval_last_fence_put_unlocked(struct xe_exec_queue *q, unsigned int type)
```

Drop ref to last TLB invalidation fence unlocked

**Parameters**

- `struct xe_exec_queue *q`: The exec queue
- `unsigned int type`: Either primary or media GT

**Description**

Only safe to be called from `xe_exec_queue_destroy()`.

#### <a id="c-xe_exec_queue_tlb_inval_last_fence_get"></a>`xe_exec_queue_tlb_inval_last_fence_get()`

```c
struct dma_fence * xe_exec_queue_tlb_inval_last_fence_get(struct xe_exec_queue *q, struct xe_vm *vm, unsigned int type)
```

Get last fence for TLB invalidation

**Parameters**

- `struct xe_exec_queue *q`: The exec queue
- `struct xe_vm *vm`: The VM the engine does a bind for
- `unsigned int type`: Either primary or media GT

**Description**

Get last fence, takes a ref

**Return**

last fence if not signaled, dma fence stub if signaled

#### <a id="c-xe_exec_queue_tlb_inval_last_fence_set"></a>`xe_exec_queue_tlb_inval_last_fence_set()`

```c
void xe_exec_queue_tlb_inval_last_fence_set(struct xe_exec_queue *q, struct xe_vm *vm, struct dma_fence *fence, unsigned int type)
```

Set last fence for TLB invalidation

**Parameters**

- `struct xe_exec_queue *q`: The exec queue
- `struct xe_vm *vm`: The VM the engine does a bind for
- `struct dma_fence *fence`: The fence
- `unsigned int type`: Either primary or media GT

**Description**

Set the last fence for the tlb invalidation type on the queue. Increases
reference count for fence, when closing queue
xe_exec_queue_tlb_inval_last_fence_put should be called.

#### <a id="c-xe_exec_queue_contexts_hwsp_rebase"></a>`xe_exec_queue_contexts_hwsp_rebase()`

```c
int xe_exec_queue_contexts_hwsp_rebase(struct xe_exec_queue *q, void *scratch)
```

Re-compute GGTT references within all LRCs of a queue.

**Parameters**

- `struct xe_exec_queue *q`: the [`xe_exec_queue`](#c-struct-xe_exec_queue) struct instance containing target LRCs
- `void *scratch`: scratch buffer to be used as temporary storage

**Return**

zero on success, negative error code on failure

---

# Firmware

_Peios Kernel / Hardware and drivers / Graphics / xe_

> TODO

<a id="rst-firmware"></a>

<!-- SPDX-License-Identifier: (GPL-2.0+ OR MIT) -->

<a id="rst-firmware-layout"></a>

## Firmware Layout


The CSS-based firmware structure is used for GuC releases on all platforms
and for HuC releases up to DG1. Starting from DG2/MTL the HuC uses the GSC
layout instead.
The CSS firmware layout looks like this:

```text
+======================================================================+
|  Firmware blob                                                       |
+===============+===============+============+============+============+
|  CSS header   |     uCode     |  RSA key   |  modulus   |  exponent  |
+===============+===============+============+============+============+
 <-header size->                 <---header size continued ----------->
 <--- size ----------------------------------------------------------->
                                 <-key size->
                                              <-mod size->
                                                           <-exp size->
```

The firmware may or may not have modulus key and exponent data. The header,
uCode and RSA signature are must-have components that will be used by driver.
Length of each components, which is all in dwords, can be found in header.
In the case that modulus and exponent are not present in fw, a.k.a truncated
image, the length value still appears in header.

Driver will do some basic fw size validation based on the following rules:

1. Header, uCode and RSA are must-have components.
2. All firmware components, if they present, are in the sequence illustrated
   in the layout table above.
3. Length info of each component can be found in header, in dwords.
4. Modulus and exponent key are not required by driver. They may not appear
   in fw. So driver will load a truncated firmware in this case.



The GSC-based firmware structure is used for GSC releases on all platforms
and for HuC releases starting from DG2/MTL. Older HuC releases use the
CSS-based layout instead. Differently from the CSS headers, the GSC headers
uses a directory + entries structure (i.e., there is array of addresses
pointing to specific header extensions identified by a name). Although the
header structures are the same, some of the entries are specific to GSC while
others are specific to HuC. The manifest header entry, which includes basic
information about the binary (like the version) is always present, but it is
named differently based on the binary type.

The HuC binary starts with a Code Partition Directory (CPD) header. The
entries we're interested in for use in the driver are:

1. "HUCP.man": points to the manifest header for the HuC.
2. "huc_fw": points to the FW code. On platforms that support load via DMA
   and 2-step HuC authentication (i.e. MTL+) this is a full CSS-based binary,
   while if the GSC is the one doing the load (which only happens on DG2)
   this section only contains the uCode.

The GSC-based HuC firmware layout looks like this:

```text
+================================================+
|  CPD Header                                    |
+================================================+
|  CPD entries[]                                 |
|      entry1                                    |
|      ...                                       |
|      entryX                                    |
|          "HUCP.man"                            |
|           ...                                  |
|           offset  >----------------------------|------o
|      ...                                       |      |
|      entryY                                    |      |
|          "huc_fw"                              |      |
|           ...                                  |      |
|           offset  >----------------------------|----------o
+================================================+      |   |
                                                        |   |
+================================================+      |   |
|  Manifest Header                               |<-----o   |
|      ...                                       |          |
|      FW version                                |          |
|      ...                                       |          |
+================================================+          |
                                                            |
+================================================+          |
|  FW binary                                     |<---------o
|      CSS (MTL+ only)                           |
|      uCode                                     |
|      RSA Key (MTL+ only)                       |
|      ...                                       |
+================================================+
```

The GSC binary starts instead with a layout header, which contains the
locations of the various partitions of the binary. The one we're interested
in is the boot1 partition, where we can find a BPDT header followed by
entries, one of which points to the RBE sub-section of the partition, which
contains the CPD. The GSC blob does not contain a CSS-based binary, so we
only need to look for the manifest, which is under the "RBEP.man" CPD entry.
Note that we have no need to find where the actual FW code is inside the
image because the GSC ROM will itself parse the headers to find it and load
it.
The GSC firmware header layout looks like this:

```text
+================================================+
|  Layout Pointers                               |
|      ...                                       |
|      Boot1 offset  >---------------------------|------o
|      ...                                       |      |
+================================================+      |
                                                        |
+================================================+      |
|  BPDT header                                   |<-----o
+================================================+
|  BPDT entries[]                                |
|      entry1                                    |
|      ...                                       |
|      entryX                                    |
|          type == GSC_RBE                       |
|          offset  >-----------------------------|------o
|      ...                                       |      |
+================================================+      |
                                                        |
+================================================+      |
|  CPD Header                                    |<-----o
+================================================+
|  CPD entries[]                                 |
|      entry1                                    |
|      ...                                       |
|      entryX                                    |
|          "RBEP.man"                            |
|           ...                                  |
|           offset  >----------------------------|------o
|      ...                                       |      |
+================================================+      |
                                                        |
+================================================+      |
| Manifest Header                                |<-----o
|  ...                                           |
|  FW version                                    |
|  ...                                           |
|  Security version                              |
|  ...                                           |
+================================================+
```


<a id="rst-write-once-protected-content-memory-wopcm-layout"></a>

## Write Once Protected Content Memory (WOPCM) Layout


The layout of the WOPCM will be fixed after writing to GuC WOPCM size and
offset registers whose values are calculated and determined by HuC/GuC
firmware size and set of hardware requirements/restrictions as shown below:

```text
  +=========> +====================+ <== WOPCM Top
  ^           |  HW contexts RSVD  |
  |     +===> +====================+ <== GuC WOPCM Top
  |     ^     |                    |
  |     |     |                    |
  |     |     |                    |
  |    GuC    |                    |
  |   WOPCM   |                    |
  |    Size   +--------------------+
WOPCM   |     |    GuC FW RSVD     |
  |     |     +--------------------+
  |     |     |   GuC Stack RSVD   |
  |     |     +------------------- +
  |     v     |   GuC WOPCM RSVD   |
  |     +===> +====================+ <== GuC WOPCM base
  |           |     WOPCM RSVD     |
  |           +------------------- + <== HuC Firmware Top
  v           |      HuC FW        |
  +=========> +====================+ <== WOPCM Base
```

GuC accessible WOPCM starts at GuC WOPCM base and ends at GuC WOPCM top.
The top part of the WOPCM is reserved for hardware contexts (e.g. RC6
context).


<a id="rst-guc-ctb-blob"></a>

## GuC CTB Blob


We allocate single blob to hold both CTB descriptors and buffers:

```text
+--------+-----------------------------------------------+------+
| offset | contents                                      | size |
+========+===============================================+======+
| 0x0000 | H2G CTB Descriptor (send)                     |      |
+--------+-----------------------------------------------+  4K  |
| 0x0800 | G2H CTB Descriptor (g2h)                      |      |
+--------+-----------------------------------------------+------+
| 0x1000 | H2G CT Buffer (send)                          | n*4K |
|        |                                               |      |
+--------+-----------------------------------------------+------+
| 0x1000 | G2H CT Buffer (g2h)                           | m*4K |
| + n*4K |                                               |      |
+--------+-----------------------------------------------+------+
```

Size of each `CT Buffer` must be multiple of 4K.
We don't expect too many messages in flight at any time, unless we are
using the GuC submission. In that case each request requires a minimum
2 dwords which gives us a maximum 256 queue'd requests. Hopefully this
enough space to avoid backpressure on the driver. We increase the size
of the receive buffer (relative to the send) to ensure a G2H response
CTB has a landing spot.

In addition to submissions, the G2H buffer needs to be able to hold
enough space for recoverable page fault notifications. The number of
page faults is interrupt driven and can be as much as the number of
compute resources available. However, most of the actual work for these
is in a separate page fault worker thread. Therefore we only need to
make sure the queue has enough space to handle all of the submissions
and responses and an extra buffer for incoming page faults.


<a id="rst-guc-power-conservation-pc"></a>

## GuC Power Conservation (PC)


GuC Power Conservation (PC) supports multiple features for the most
efficient and performing use of the GT when GuC submission is enabled,
including frequency management, Render-C states management, and various
algorithms for power balancing.

Single Loop Power Conservation (SLPC) is the name given to the suite of
connected power conservation features in the GuC firmware. The firmware
exposes a programming interface to the host for the control of SLPC.

**Frequency management:**

Xe driver enables SLPC with all of its defaults features and frequency
selection, which varies per platform.

Power profiles add another level of control to SLPC. When power saving
profile is chosen, SLPC will use conservative thresholds to ramp frequency,
thus saving power. Base profile is default and ensures balanced performance
for any workload.

**Render-C States:**

Render-C states is also a GuC PC feature that is now enabled in Xe for
all platforms.


<a id="rst-pcie-gen5-limitations"></a>

## PCIe Gen5 Limitations


Default link speed of discrete GPUs is determined by configuration parameters
stored in their flash memory, which are subject to override through user
initiated firmware updates. It has been observed that devices configured with
PCIe Gen5 as their default link speed can come across link quality issues due
to host or motherboard limitations and may have to auto-downgrade their link
to PCIe Gen4 speed when faced with unstable link at Gen5, which makes
firmware updates rather risky on such setups. It is required to ensure that
the device is capable of auto-downgrading its link to PCIe Gen4 speed before
pushing the firmware image with PCIe Gen5 as default configuration. This can
be done by reading `auto_link_downgrade_capable` sysfs entry, which will
denote if the device is capable of auto-downgrading its link to PCIe Gen4
speed with boolean output value of `0` or `1`, meaning `incapable` or
`capable` respectively.

```shell
$ cat /sys/bus/pci/devices/<bdf>/auto_link_downgrade_capable
```

Pushing the firmware image with PCIe Gen5 as default configuration on a auto
link downgrade incapable device and facing link instability due to host or
motherboard limitations can result in driver failing to bind to the device,
making further firmware updates impossible with RMA being the only last
resort.

Link downgrade status of auto link downgrade capable devices is available
through `auto_link_downgrade_status` sysfs entry with boolean output value
of `0` or `1`, where `0` means no auto-downgrading was required during
link training (which is the optimal scenario) and `1` means the device has
auto-downgraded its link to PCIe Gen4 speed due to unstable Gen5 link.

```shell
$ cat /sys/bus/pci/devices/<bdf>/auto_link_downgrade_status
```


<a id="rst-internal-api"></a>

## Internal API

TODO

---

# Xe GT Frequency Management

_Peios Kernel / Hardware and drivers / Graphics / xe_

> Reference for Xe GT Frequency Management.

<a id="rst-xe-gt-frequency-management"></a>

<!-- SPDX-License-Identifier: (GPL-2.0+ OR MIT) -->


This component is responsible for the raw GT frequency management, including
the sysfs API.

Underneath, Xe enables GuC SLPC automated frequency management. GuC is then
allowed to request PCODE any frequency between the Minimum and the Maximum
selected by this component. Furthermore, it is important to highlight that
PCODE is the ultimate decision maker of the actual running frequency, based
on thermal and other running conditions.

Xe's Freq provides a sysfs API for frequency management under
`<device>/tile#/gt#/freq0/` directory.

**Read-only** attributes:

- `act_freq`: The actual resolved frequency decided by PCODE.
- `cur_freq`: The current one requested by GuC PC to the PCODE.
- `rpn_freq`: The Render Performance (RP) N level, which is the minimal one.
- `rpa_freq`: The Render Performance (RP) A level, which is the achievable one.
  Calculated by PCODE at runtime based on multiple running conditions
- `rpe_freq`: The Render Performance (RP) E level, which is the efficient one.
  Calculated by PCODE at runtime based on multiple running conditions
- `rp0_freq`: The Render Performance (RP) 0 level, which is the maximum one.

**Read-write** attributes:

- `min_freq`: Min frequency request.
- `max_freq`: Max frequency request.
  If max \<= min, then freq_min becomes a fixed frequency
  request.



The GT frequency may be throttled by hardware/firmware for various reasons
that are provided through attributes under the `freq0/throttle/` directory.
Their availability depend on the platform and some may not be visible if that
reason is not available.

The `reasons` attribute can be used by sysadmin to monitor all possible
reasons for throttling and report them. It's preferred over monitoring
`status` and then reading the reason from individual attributes since that
is racy. If there's no throttling happening, "none" is returned.

The following attributes are available on Crescent Island platform:

- `status`: Overall throttle status (0: no throttling, 1: throttling)
- `reasons`: Array of reasons causing throttling separated by space
- `reason_pl1`: package PL1
- `reason_pl2`: package PL2
- `reason_pl4`: package PL4
- `reason_prochot`: prochot
- `reason_soc_thermal`: SoC thermal
- `reason_mem_thermal`: Memory thermal
- `reason_vr_thermal`: VR thermal
- `reason_iccmax`: ICCMAX
- `reason_ratl`: RATL thermal algorithm
- `reason_soc_avg_thermal`: SoC average temp
- `reason_fastvmode`: VR is hitting FastVMode
- `reason_psys_pl1`: PSYS PL1
- `reason_psys_pl2`: PSYS PL2
- `reason_p0_freq`: P0 frequency
- `reason_psys_crit`: PSYS critical

Other platforms support the following reasons:

- `status`: Overall throttle status (0: no throttling, 1: throttling)
- `reasons`: Array of reasons causing throttling separated by space
- `reason_pl1`: package PL1
- `reason_pl2`: package PL2
- `reason_pl4`: package PL4, Iccmax etc.
- `reason_thermal`: thermal
- `reason_prochot`: prochot
- `reason_ratl`: RATL hermal algorithm
- `reason_vr_thermalert`: VR THERMALERT
- `reason_vr_tdc`: VR TDC


<a id="rst-internal-api"></a>

## Internal API


#### <a id="c-xe_gt_freq_init"></a>`xe_gt_freq_init()`

```c
int xe_gt_freq_init(struct xe_gt *gt)
```

Initialize Xe Freq component

**Parameters**

- `struct xe_gt *gt`: Xe GT object

**Description**

It needs to be initialized after GT Sysfs and GuC PC components are ready.

**Return**

Returns error value for failure and 0 for success.

---

# GT Multicast/Replicated (MCR) Register Support

_Peios Kernel / Hardware and drivers / Graphics / xe_

> TODO

<a id="rst-gt-multicast-replicated-mcr-register-support"></a>

<!-- SPDX-License-Identifier: (GPL-2.0+ OR MIT) -->


Some GT registers are designed as "multicast" or "replicated" registers:
multiple instances of the same register share a single MMIO offset.  MCR
registers are generally used when the hardware needs to potentially track
independent values of a register per hardware unit (e.g., per-subslice,
per-L3bank, etc.).  The specific types of replication that exist vary
per-platform.

MMIO accesses to MCR registers are controlled according to the settings
programmed in the platform's MCR_SELECTOR register(s).  MMIO writes to MCR
registers can be done in either multicast (a single write updates all
instances of the register to the same value) or unicast (a write updates only
one specific instance) form.  Reads of MCR registers always operate in a
unicast manner regardless of how the multicast/unicast bit is set in
MCR_SELECTOR.  Selection of a specific MCR instance for unicast operations is
referred to as "steering."

If MCR register operations are steered toward a hardware unit that is
fused off or currently powered down due to power gating, the MMIO operation
is "terminated" by the hardware.  Terminated read operations will return a
value of zero and terminated unicast write operations will be silently
ignored. During device initialization, the goal of the various
`init_steering_*()` functions is to apply the platform-specific rules for
each MCR register type to identify a steering target that will select a
non-terminated instance.

MCR registers are not available on Virtual Function (VF).


<a id="rst-internal-api"></a>

## Internal API

TODO

---

# Map Layer

_Peios Kernel / Hardware and drivers / Graphics / xe_

> Reference for Map Layer.

<a id="rst-map-layer"></a>

<!-- SPDX-License-Identifier: (GPL-2.0+ OR MIT) -->


All access to any memory shared with a device (both sysmem and vram) in the
Xe driver should go through this layer (xe_map). This layer is built on top
of driver-api/device-io:Generalizing Access to System and I/O Memory
and with extra hooks into the Xe driver that allows adding asserts to memory
accesses (e.g. for blocking runtime_pm D3Cold on Discrete Graphics).

---

# Migrate Layer

_Peios Kernel / Hardware and drivers / Graphics / xe_

> Reference for Migrate Layer.

<a id="rst-migrate-layer"></a>

<!-- SPDX-License-Identifier: (GPL-2.0+ OR MIT) -->


The Xe migrate layer is used generate jobs which can copy memory (eviction),
clear memory, or program tables (binds). This layer exists in every GT, has
a migrate engine, and uses a special VM for all generated jobs.

**Special VM details**

The special VM is configured with a page structure where we can dynamically
map BOs which need to be copied and cleared, dynamically map other VM's page
table BOs for updates, and identity map the entire device's VRAM with 1 GB
pages.

Currently the page structure consists of 32 physical pages with 16 being
reserved for BO mapping during copies and clear, 1 reserved for kernel binds,
several pages are needed to setup the identity mappings (exact number based
on how many bits of address space the device has), and the rest are reserved
user bind operations.

TODO: Diagram of layout

**Bind jobs**

A bind job consist of two batches and runs either on the migrate engine
(kernel binds) or the bind engine passed in (user binds). In both cases the
VM of the engine is the migrate VM.

The first batch is used to update the migration VM page structure to point to
the bind VM page table BOs which need to be updated. A physical page is
required for this. If it is a user bind, the page is allocated from pool of
pages reserved user bind operations with drm_suballoc managing this pool. If
it is a kernel bind, the page reserved for kernel binds is used.

The first batch is only required for devices without VRAM as when the device
has VRAM the bind VM page table BOs are in VRAM and the identity mapping can
be used.

The second batch is used to program page table updated in the bind VM. Why
not just one batch? Well the TLBs need to be invalidated between these two
batches and that only can be done from the ring.

When the bind job complete, the page allocated is returned the pool of pages
reserved for user bind operations if a user bind. No need do this for kernel
binds as the reserved kernel page is serially used by each job.

**Copy / clear jobs**

A copy or clear job consist of two batches and runs on the migrate engine.

Like binds, the first batch is used update the migration VM page structure.
In copy jobs, we need to map the source and destination of the BO into page
the structure. In clear jobs, we just need to add 1 mapping of BO into the
page structure. We use the 16 reserved pages in migration VM for mappings,
this gives us a maximum copy size of 16 MB and maximum clear size of 32 MB.

The second batch is used do either do the copy or clear. Again similar to
binds, two batches are required as the TLBs need to be invalidated from the
ring between the batches.

More than one job will be generated if the BO is larger than maximum copy /
clear size.

**Future work**

Update copy and clear code to use identity mapped VRAM.

Can we rework the use of the pages async binds to use all the entries in each
page?

Using large pages for sysmem mappings.

Is it possible to identity map the sysmem? We should explore this.

---

# Memory Management

_Peios Kernel / Hardware and drivers / Graphics / xe_

> Reference for Memory Management.

<a id="rst-memory-management"></a>

<!-- SPDX-License-Identifier: (GPL-2.0+ OR MIT) -->


**BO management**

TTM manages (placement, eviction, etc...) all BOs in Xe.

**BO creation**

Create a chunk of memory which can be used by the GPU. Placement rules
(sysmem or vram region) passed in upon creation. TTM handles placement of BO
and can trigger eviction of other BOs to make space for the new BO.

**Kernel BOs**

A kernel BO is created as part of driver load (e.g. uC firmware images, GuC
ADS, etc...) or a BO created as part of a user operation which requires
a kernel BO (e.g. engine state, memory for page tables, etc...). These BOs
are typically mapped in the GGTT (any kernel BOs aside memory for page tables
are in the GGTT), are pinned (can't move or be evicted at runtime), have a
vmap (Xe can access the memory via xe_map layer) and have contiguous physical
memory.

More details of why kernel BOs are pinned and contiguous below.

**User BOs**

A user BO is created via the DRM_IOCTL_XE_GEM_CREATE IOCTL. Once it is
created the BO can be mmap'd (via DRM_IOCTL_XE_GEM_MMAP_OFFSET) for user
access and it can be bound for GPU access (via DRM_IOCTL_XE_VM_BIND). All
user BOs are evictable and user BOs are never pinned by Xe. The allocation of
the backing store can be deferred from creation time until first use which is
either mmap, bind, or pagefault.

**Private BOs**

A private BO is a user BO created with a valid VM argument passed into the
create IOCTL. If a BO is private it cannot be exported via prime FD and
mappings can only be created for the BO within the VM it is tied to. Lastly,
the BO dma-resv slots / lock point to the VM's dma-resv slots / lock (all
private BOs to a VM share common dma-resv slots / lock).

**External BOs**

An external BO is a user BO created with a NULL VM argument passed into the
create IOCTL. An external BO can be shared with different UMDs / devices via
prime FD and the BO can be mapped into multiple VMs. An external BO has its
own unique dma-resv slots / lock. An external BO will be in an array of all
VMs which has a mapping of the BO. This allows VMs to lookup and lock all
external BOs mapped in the VM as needed.

**BO placement**

When a user BO is created, a mask of valid placements is passed indicating
which memory regions are considered valid.

The memory region information is available via query uAPI (TODO: add link).

**BO validation**

BO validation (ttm_bo_validate) refers to ensuring a BO has a valid
placement. If a BO was swapped to temporary storage, a validation call will
trigger a move back to a valid (location where GPU can access BO) placement.
Validation of a BO may evict other BOs to make room for the BO being
validated.

**BO eviction / moving**

All eviction (or in other words, moving a BO from one memory location to
another) is routed through TTM with a callback into Xe.

**Runtime eviction**

Runtime evictions refers to during normal operations where TTM decides it
needs to move a BO. Typically this is because TTM needs to make room for
another BO and the evicted BO is first BO on LRU list that is not locked.

An example of this is a new BO which can only be placed in VRAM but there is
not space in VRAM. There could be multiple BOs which have sysmem and VRAM
placement rules which currently reside in VRAM, TTM trigger a will move of
one (or multiple) of these BO(s) until there is room in VRAM to place the new
BO. The evicted BO(s) are valid but still need new bindings before the BO
used again (exec or compute mode rebind worker).

Another example would be, TTM can't find a BO to evict which has another
valid placement. In this case TTM will evict one (or multiple) unlocked BO(s)
to a temporary unreachable (invalid) placement. The evicted BO(s) are invalid
and before next use need to be moved to a valid placement and rebound.

In both cases, moves of these BOs are scheduled behind the fences in the BO's
dma-resv slots.

WW locking tries to ensures if 2 VMs use 51% of the memory forward progress
is made on both VMs.

Runtime eviction uses per a GT migration engine (TODO: link to migration
engine doc) to do a GPU memcpy from one location to another.

**Rebinds after runtime eviction**

When BOs are moved, every mapping (VMA) of the BO needs to rebound before
the BO is used again. Every VMA is added to an evicted list of its VM when
the BO is moved. This is safe because of the VM locking structure (TODO: link
to VM locking doc). On the next use of a VM (exec or compute mode rebind
worker) the evicted VMA list is checked and rebinds are triggered. In the
case of faulting VM, the rebind is done in the page fault handler.

**Suspend / resume eviction of VRAM**

During device suspend / resume VRAM may lose power which means the contents
of VRAM's memory is blown away. Thus BOs present in VRAM at the time of
suspend must be moved to sysmem in order for their contents to be saved.

A simple TTM call (ttm_resource_manager_evict_all) can move all non-pinned
(user) BOs to sysmem. External BOs that are pinned need to be manually
evicted with a simple loop + xe_bo_evict call. It gets a little trickier
with kernel BOs.

Some kernel BOs are used by the GT migration engine to do moves, thus we
can't move all of the BOs via the GT migration engine. For simplity, use a
TTM memcpy (CPU) to move any kernel (pinned) BO on either suspend or resume.

Some kernel BOs need to be restored to the exact same physical location. TTM
makes this rather easy but the caveat is the memory must be contiguous. Again
for simplity, we enforce that all kernel (pinned) BOs are contiguous and
restored to the same physical location.

Pinned external BOs in VRAM are restored on resume via the GPU.

**Rebinds after suspend / resume**

Most kernel BOs have GGTT mappings which must be restored during the resume
process. All user BOs are rebound after validation on their next use.

**Future work**

Trim the list of BOs which is saved / restored via TTM memcpy on suspend /
resume. All we really need to save / restore via TTM memcpy is the memory
required for the GuC to load and the memory for the GT migrate engine to
operate.

Do not require kernel BOs to be contiguous in physical memory / restored to
the same physical address on resume. In all likelihood the only memory that
needs to be restored to the same physical address is memory used for page
tables. All of that memory is allocated 1 page at time so the contiguous
requirement isn't needed. Some work on the vmap code would need to be done if
kernel BOs are not contiguous too.

Make some kernel BO evictable rather than pinned. An example of this would be
engine state, in all likelihood if the dma-slots of these BOs where properly
used rather than pinning we could safely evict + rebind these BOs as needed.

Some kernel BOs do not need to be restored on resume (e.g. GuC ADS as that is
repopulated on resume), add flag to mark such objects as no save / restore.


<a id="rst-ggtt"></a>

## GGTT


Xe GGTT implements the support for a Global Virtual Address space that is used
for resources that are accessible to privileged (i.e. kernel-mode) processes,
and not tied to a specific user-level process. For example, the Graphics
micro-Controller (GuC) and Display Engine (if present) utilize this Global
address space.

The Global GTT (GGTT) translates from the Global virtual address to a physical
address that can be accessed by HW. The GGTT is a flat, single-level table.

Xe implements a simplified version of the GGTT specifically managing only a
certain range of it that goes from the Write Once Protected Content Memory (WOPCM)
Layout to a predefined GUC_GGTT_TOP. This approach avoids complications related to
the GuC (Graphics Microcontroller) hardware limitations. The GuC address space
is limited on both ends of the GGTT, because the GuC shim HW redirects
accesses to those addresses to other HW areas instead of going through the
GGTT. On the bottom end, the GuC can't access offsets below the WOPCM size,
while on the top side the limit is fixed at GUC_GGTT_TOP. To keep things
simple, instead of checking each object to see if they are accessed by GuC or
not, we just exclude those areas from the allocator. Additionally, to simplify
the driver load, we use the maximum WOPCM size in this logic instead of the
programmed one, so we don't need to wait until the actual size to be
programmed is determined (which requires FW fetch) before initializing the
GGTT. These simplifications might waste space in the GGTT (about 20-25 MBs
depending on the platform) but we can live with this. Another benefit of this
is the GuC bootrom can't access anything below the WOPCM max size so anything
the bootrom needs to access (e.g. a RSA key) needs to be placed in the GGTT
above the WOPCM max size. Starting the GGTT allocations above the WOPCM max
give us the correct placement for free.


<a id="rst-ggtt-internal-api"></a>

### GGTT Internal API


#### <a id="c-struct-xe_ggtt"></a>`struct xe_ggtt`

Main GGTT struct

**Definition**

```c
struct xe_ggtt {
        struct xe_tile *tile;
        u64 start;
        u64 size;
    #define XE_GGTT_FLAGS_64K       BIT(0);
    #define XE_GGTT_FLAGS_ONLINE    BIT(1);
        unsigned int flags;
        struct xe_bo *scratch;
        struct mutex lock;
        u64 __iomem *gsm;
        const struct xe_ggtt_pt_ops *pt_ops;
        struct drm_mm mm;
        unsigned int access_count;
        struct workqueue_struct *wq;
};
```

**Members**

- `tile`: Back pointer to tile where this GGTT belongs
- `start`: Start offset of GGTT
- `size`: Total usable size of this GGTT
- `flags`: Flags for this GGTT
  Acceptable flags:
  - `XE_GGTT_FLAGS_64K` - if PTE size is 64K. Otherwise, regular is 4K.
  - `XE_GGTT_FLAGS_ONLINE` - is GGTT online, protected by ggtt->lock
    after init
- `scratch`: Internal object allocation used as a scratch page
- `lock`: Mutex lock to protect GGTT data
- `gsm`: The iomem pointer to the actual location of the translation
  table located in the GSM for easy PTE manipulation
- `pt_ops`: Page Table operations per platform
- `mm`: The memory manager used to manage individual GGTT allocations
- `access_count`: counts GGTT writes
- `wq`: Dedicated unordered work queue to process node removals

**Description**

In general, each tile can contains its own Global Graphics Translation Table
(GGTT) instance.

#### <a id="c-struct-xe_ggtt_pt_ops"></a>`struct xe_ggtt_pt_ops`

GGTT Page table operations Which can vary from platform to platform.

**Definition**

```c
struct xe_ggtt_pt_ops {
    u64 (*pte_encode_flags)(struct xe_bo *bo, u16 pat_index);
    xe_ggtt_set_pte_fn ggtt_set_pte;
    u64 (*ggtt_get_pte)(struct xe_ggtt *ggtt, u64 addr);
};
```

**Members**

- `pte_encode_flags`: Encode PTE flags for a given BO
- `ggtt_set_pte`: Directly write into GGTT's PTE
- `ggtt_get_pte`: Directly read from GGTT's PTE



#### <a id="c-struct-xe_ggtt_node"></a>`struct xe_ggtt_node`

A node in GGTT.

**Definition**

```c
struct xe_ggtt_node {
    struct xe_ggtt *ggtt;
    struct drm_mm_node base;
    struct work_struct delayed_removal_work;
    bool invalidate_on_remove;
};
```

**Members**

- `ggtt`: Back pointer to xe_ggtt where this region will be inserted at
- `base`: A drm_mm_node
- `delayed_removal_work`: The work struct for the delayed removal
- `invalidate_on_remove`: If it needs invalidation upon removal

**Description**

This struct needs to be initialized (only-once) with [`xe_ggtt_node_init()`](#c-xe_ggtt_node_init) before any node
insertion, reservation, or 'ballooning'.
It will, then, be finalized by either [`xe_ggtt_node_remove()`](#c-xe_ggtt_node_remove) or `xe_ggtt_node_deballoon()`.

#### <a id="c-xe_ggtt_start"></a>`xe_ggtt_start()`

```c
u64 xe_ggtt_start(struct xe_ggtt *ggtt)
```

Get starting offset of GGTT.

**Parameters**

- `struct xe_ggtt *ggtt`: [`xe_ggtt`](#c-struct-xe_ggtt)

**Return**

Starting offset for this [`xe_ggtt`](#c-struct-xe_ggtt).

#### <a id="c-xe_ggtt_size"></a>`xe_ggtt_size()`

```c
u64 xe_ggtt_size(struct xe_ggtt *ggtt)
```

Get size of GGTT.

**Parameters**

- `struct xe_ggtt *ggtt`: [`xe_ggtt`](#c-struct-xe_ggtt)

**Return**

Total usable size of this [`xe_ggtt`](#c-struct-xe_ggtt).

#### <a id="c-xe_ggtt_alloc"></a>`xe_ggtt_alloc()`

```c
struct xe_ggtt * xe_ggtt_alloc(struct xe_tile *tile)
```

Allocate a GGTT for a given `xe_tile`

**Parameters**

- `struct xe_tile *tile`: `xe_tile`

**Description**

Allocates a [`xe_ggtt`](#c-struct-xe_ggtt) for a given tile.

**Return**

[`xe_ggtt`](#c-struct-xe_ggtt) on success, or NULL when out of memory.

#### <a id="c-xe_ggtt_init_early"></a>`xe_ggtt_init_early()`

```c
int xe_ggtt_init_early(struct xe_ggtt *ggtt)
```

Early GGTT initialization

**Parameters**

- `struct xe_ggtt *ggtt`: the [`xe_ggtt`](#c-struct-xe_ggtt) to be initialized

**Description**

It allows to create new mappings usable by the GuC.
Mappings are not usable by the HW engines, as it doesn't have scratch nor
initial clear done to it yet. That will happen in the regular, non-early
GGTT initialization.

**Return**

0 on success or a negative error code on failure.

#### <a id="c-xe_ggtt_node_remove"></a>`xe_ggtt_node_remove()`

```c
void xe_ggtt_node_remove(struct xe_ggtt_node *node, bool invalidate)
```

Remove a [`xe_ggtt_node`](#c-struct-xe_ggtt_node) from the GGTT

**Parameters**

- `struct xe_ggtt_node *node`: the [`xe_ggtt_node`](#c-struct-xe_ggtt_node) to be removed
- `bool invalidate`: if node needs invalidation upon removal

#### <a id="c-xe_ggtt_init"></a>`xe_ggtt_init()`

```c
int xe_ggtt_init(struct xe_ggtt *ggtt)
```

Regular non-early GGTT initialization

**Parameters**

- `struct xe_ggtt *ggtt`: the [`xe_ggtt`](#c-struct-xe_ggtt) to be initialized

**Return**

0 on success or a negative error code on failure.

#### <a id="c-xe_ggtt_node_insert_balloon_locked"></a>`xe_ggtt_node_insert_balloon_locked()`

```c
int xe_ggtt_node_insert_balloon_locked(struct xe_ggtt_node *node, u64 start, u64 end)
```

prevent allocation of specified GGTT addresses

**Parameters**

- `struct xe_ggtt_node *node`: the [`xe_ggtt_node`](#c-struct-xe_ggtt_node) to hold reserved GGTT node
- `u64 start`: the starting GGTT address of the reserved region
- `u64 end`: then end GGTT address of the reserved region

**Description**

To be used in cases where ggtt->lock is already taken.
Use [`xe_ggtt_node_remove_balloon_locked()`](#c-xe_ggtt_node_remove_balloon_locked) to release a reserved GGTT node.

**Return**

0 on success or a negative error code on failure.

#### <a id="c-xe_ggtt_node_remove_balloon_locked"></a>`xe_ggtt_node_remove_balloon_locked()`

```c
void xe_ggtt_node_remove_balloon_locked(struct xe_ggtt_node *node)
```

release a reserved GGTT region

**Parameters**

- `struct xe_ggtt_node *node`: the [`xe_ggtt_node`](#c-struct-xe_ggtt_node) with reserved GGTT region

**Description**

To be used in cases where ggtt->lock is already taken.
See [`xe_ggtt_node_insert_balloon_locked()`](#c-xe_ggtt_node_insert_balloon_locked) for details.

#### <a id="c-xe_ggtt_shift_nodes_locked"></a>`xe_ggtt_shift_nodes_locked()`

```c
void xe_ggtt_shift_nodes_locked(struct xe_ggtt *ggtt, s64 shift)
```

Shift GGTT nodes to adjust for a change in usable address range.

**Parameters**

- `struct xe_ggtt *ggtt`: the [`xe_ggtt`](#c-struct-xe_ggtt) struct instance
- `s64 shift`: change to the location of area provisioned for current VF

**Description**

This function moves all nodes from the GGTT VM, to a temp list. These nodes are expected
to represent allocations in range formerly assigned to current VF, before the range changed.
When the GGTT VM is completely clear of any nodes, they are re-added with shifted offsets.

The function has no ability of failing - because it shifts existing nodes, without
any additional processing. If the nodes were successfully existing at the old address,
they will do the same at the new one. A fail inside this function would indicate that
the list of nodes was either already damaged, or that the shift brings the address range
outside of valid bounds. Both cases justify an assert rather than error code.

#### <a id="c-xe_ggtt_node_insert"></a>`xe_ggtt_node_insert()`

```c
int xe_ggtt_node_insert(struct xe_ggtt_node *node, u32 size, u32 align)
```

Insert a [`xe_ggtt_node`](#c-struct-xe_ggtt_node) into the GGTT

**Parameters**

- `struct xe_ggtt_node *node`: the [`xe_ggtt_node`](#c-struct-xe_ggtt_node) to be inserted
- `u32 size`: size of the node
- `u32 align`: alignment constrain of the node

**Description**

It cannot be called without first having called [`xe_ggtt_init()`](#c-xe_ggtt_init) once.

**Return**

0 on success or a negative error code on failure.

#### <a id="c-xe_ggtt_node_init"></a>`xe_ggtt_node_init()`

```c
struct xe_ggtt_node * xe_ggtt_node_init(struct xe_ggtt *ggtt)
```

Initialize `xe_ggtt_node` struct

**Parameters**

- `struct xe_ggtt *ggtt`: the [`xe_ggtt`](#c-struct-xe_ggtt) where the new node will later be inserted/reserved.

**Description**

This function will allocate the struct `xe_ggtt_node` and return its pointer.
This struct will then be freed after the node removal upon [`xe_ggtt_node_remove()`](#c-xe_ggtt_node_remove)
or [`xe_ggtt_node_remove_balloon_locked()`](#c-xe_ggtt_node_remove_balloon_locked).

Having `xe_ggtt_node` struct allocated doesn't mean that the node is already
allocated in GGTT. Only [`xe_ggtt_node_insert()`](#c-xe_ggtt_node_insert), allocation through
[`xe_ggtt_node_insert_transform()`](#c-xe_ggtt_node_insert_transform), or [`xe_ggtt_node_insert_balloon_locked()`](#c-xe_ggtt_node_insert_balloon_locked) will ensure the node is inserted or reserved
in GGTT.

**Return**

A pointer to `xe_ggtt_node` struct on success. An ERR_PTR otherwise.

#### <a id="c-xe_ggtt_node_fini"></a>`xe_ggtt_node_fini()`

```c
void xe_ggtt_node_fini(struct xe_ggtt_node *node)
```

Forcebly finalize `xe_ggtt_node` struct

**Parameters**

- `struct xe_ggtt_node *node`: the [`xe_ggtt_node`](#c-struct-xe_ggtt_node) to be freed

**Description**

If anything went wrong with either [`xe_ggtt_node_insert()`](#c-xe_ggtt_node_insert), `xe_ggtt_node_insert_locked()`,
or [`xe_ggtt_node_insert_balloon_locked()`](#c-xe_ggtt_node_insert_balloon_locked); and this **node** is not going to be reused, then,
this function needs to be called to free the `xe_ggtt_node` struct

#### <a id="c-xe_ggtt_node_allocated"></a>`xe_ggtt_node_allocated()`

```c
bool xe_ggtt_node_allocated(const struct xe_ggtt_node *node)
```

Check if node is allocated in GGTT

**Parameters**

- `const struct xe_ggtt_node *node`: the [`xe_ggtt_node`](#c-struct-xe_ggtt_node) to be inspected

**Return**

True if allocated, False otherwise.

#### <a id="c-xe_ggtt_node_pt_size"></a>`xe_ggtt_node_pt_size()`

```c
size_t xe_ggtt_node_pt_size(const struct xe_ggtt_node *node)
```

Get the size of page table entries needed to map a GGTT node.

**Parameters**

- `const struct xe_ggtt_node *node`: the [`xe_ggtt_node`](#c-struct-xe_ggtt_node)

**Return**

GGTT node page table entries size in bytes.

#### <a id="c-xe_ggtt_map_bo"></a>`xe_ggtt_map_bo()`

```c
void xe_ggtt_map_bo(struct xe_ggtt *ggtt, struct xe_ggtt_node *node, struct xe_bo *bo, u64 pte)
```

Map the BO into GGTT

**Parameters**

- `struct xe_ggtt *ggtt`: the [`xe_ggtt`](#c-struct-xe_ggtt) where node will be mapped
- `struct xe_ggtt_node *node`: the [`xe_ggtt_node`](#c-struct-xe_ggtt_node) where this BO is mapped
- `struct xe_bo *bo`: the `xe_bo` to be mapped
- `u64 pte`: The pte flags to append.

#### <a id="c-xe_ggtt_map_bo_unlocked"></a>`xe_ggtt_map_bo_unlocked()`

```c
void xe_ggtt_map_bo_unlocked(struct xe_ggtt *ggtt, struct xe_bo *bo)
```

Restore a mapping of a BO into GGTT

**Parameters**

- `struct xe_ggtt *ggtt`: the [`xe_ggtt`](#c-struct-xe_ggtt) where node will be mapped
- `struct xe_bo *bo`: the `xe_bo` to be mapped

**Description**

This is used to restore a GGTT mapping after suspend.

#### <a id="c-xe_ggtt_node_insert_transform"></a>`xe_ggtt_node_insert_transform()`

```c
struct xe_ggtt_node * xe_ggtt_node_insert_transform(struct xe_ggtt *ggtt, struct xe_bo *bo, u64 pte_flags, u64 size, u32 align, xe_ggtt_transform_cb transform, void *arg)
```

Insert a newly allocated [`xe_ggtt_node`](#c-struct-xe_ggtt_node) into the GGTT

**Parameters**

- `struct xe_ggtt *ggtt`: the [`xe_ggtt`](#c-struct-xe_ggtt) where the node will inserted/reserved.
- `struct xe_bo *bo`: The bo to be transformed
- `u64 pte_flags`: The extra GGTT flags to add to mapping.
- `u64 size`: size of the node
- `u32 align`: required alignment for node
- `xe_ggtt_transform_cb transform`: transformation function that will populate the GGTT node, or NULL for linear mapping.
- `void *arg`: Extra argument to pass to the transformation function.

**Description**

This function allows inserting a GGTT node with a custom transformation function.
This is useful for display to allow inserting rotated framebuffers to GGTT.

**Return**

A pointer to `xe_ggtt_node` struct on success. An ERR_PTR otherwise.

#### <a id="c-xe_ggtt_insert_bo_at"></a>`xe_ggtt_insert_bo_at()`

```c
int xe_ggtt_insert_bo_at(struct xe_ggtt *ggtt, struct xe_bo *bo, u64 start, u64 end, struct drm_exec *exec)
```

Insert BO at a specific GGTT space

**Parameters**

- `struct xe_ggtt *ggtt`: the [`xe_ggtt`](#c-struct-xe_ggtt) where bo will be inserted
- `struct xe_bo *bo`: the `xe_bo` to be inserted
- `u64 start`: address where it will be inserted
- `u64 end`: end of the range where it will be inserted
- `struct drm_exec *exec`: The drm_exec transaction to use for exhaustive eviction.

**Return**

0 on success or a negative error code on failure.

#### <a id="c-xe_ggtt_insert_bo"></a>`xe_ggtt_insert_bo()`

```c
int xe_ggtt_insert_bo(struct xe_ggtt *ggtt, struct xe_bo *bo, struct drm_exec *exec)
```

Insert BO into GGTT

**Parameters**

- `struct xe_ggtt *ggtt`: the [`xe_ggtt`](#c-struct-xe_ggtt) where bo will be inserted
- `struct xe_bo *bo`: the `xe_bo` to be inserted
- `struct drm_exec *exec`: The drm_exec transaction to use for exhaustive eviction.

**Return**

0 on success or a negative error code on failure.

#### <a id="c-xe_ggtt_remove_bo"></a>`xe_ggtt_remove_bo()`

```c
void xe_ggtt_remove_bo(struct xe_ggtt *ggtt, struct xe_bo *bo)
```

Remove a BO from the GGTT

**Parameters**

- `struct xe_ggtt *ggtt`: the [`xe_ggtt`](#c-struct-xe_ggtt) where node will be removed
- `struct xe_bo *bo`: the `xe_bo` to be removed

#### <a id="c-xe_ggtt_largest_hole"></a>`xe_ggtt_largest_hole()`

```c
u64 xe_ggtt_largest_hole(struct xe_ggtt *ggtt, u64 alignment, u64 *spare)
```

Largest GGTT hole

**Parameters**

- `struct xe_ggtt *ggtt`: the [`xe_ggtt`](#c-struct-xe_ggtt) that will be inspected
- `u64 alignment`: minimum alignment
- `u64 *spare`: If not NULL: in: desired memory size to be spared / out: Adjusted possible spare

**Return**

size of the largest continuous GGTT region

#### <a id="c-xe_ggtt_assign"></a>`xe_ggtt_assign()`

```c
void xe_ggtt_assign(const struct xe_ggtt_node *node, u16 vfid)
```

assign a GGTT region to the VF

**Parameters**

- `const struct xe_ggtt_node *node`: the [`xe_ggtt_node`](#c-struct-xe_ggtt_node) to update
- `u16 vfid`: the VF identifier

**Description**

This function is used by the PF driver to assign a GGTT region to the VF.
In addition to PTE's VFID bits 11:2 also PRESENT bit 0 is set as on some
platforms VFs can't modify that either.

#### <a id="c-xe_ggtt_node_save"></a>`xe_ggtt_node_save()`

```c
int xe_ggtt_node_save(struct xe_ggtt_node *node, void *dst, size_t size, u16 vfid)
```

Save a [`xe_ggtt_node`](#c-struct-xe_ggtt_node) to a buffer.

**Parameters**

- `struct xe_ggtt_node *node`: the [`xe_ggtt_node`](#c-struct-xe_ggtt_node) to be saved
- `void *dst`: destination buffer
- `size_t size`: destination buffer size in bytes
- `u16 vfid`: VF identifier

**Return**

0 on success or a negative error code on failure.

#### <a id="c-xe_ggtt_node_load"></a>`xe_ggtt_node_load()`

```c
int xe_ggtt_node_load(struct xe_ggtt_node *node, const void *src, size_t size, u16 vfid)
```

Load a [`xe_ggtt_node`](#c-struct-xe_ggtt_node) from a buffer.

**Parameters**

- `struct xe_ggtt_node *node`: the [`xe_ggtt_node`](#c-struct-xe_ggtt_node) to be loaded
- `const void *src`: source buffer
- `size_t size`: source buffer size in bytes
- `u16 vfid`: VF identifier

**Return**

0 on success or a negative error code on failure.

#### <a id="c-xe_ggtt_dump"></a>`xe_ggtt_dump()`

```c
int xe_ggtt_dump(struct xe_ggtt *ggtt, struct drm_printer *p)
```

Dump GGTT for debug

**Parameters**

- `struct xe_ggtt *ggtt`: the [`xe_ggtt`](#c-struct-xe_ggtt) to be dumped
- `struct drm_printer *p`: the `drm_mm_printer` helper handle to be used to dump the information

**Return**

0 on success or a negative error code on failure.

#### <a id="c-xe_ggtt_print_holes"></a>`xe_ggtt_print_holes()`

```c
u64 xe_ggtt_print_holes(struct xe_ggtt *ggtt, u64 alignment, struct drm_printer *p)
```

Print holes

**Parameters**

- `struct xe_ggtt *ggtt`: the [`xe_ggtt`](#c-struct-xe_ggtt) to be inspected
- `u64 alignment`: min alignment
- `struct drm_printer *p`: the [`drm_printer`](/kernel/hardware/gpu/drm-internals.md#c-struct-drm_printer)

**Description**

Print GGTT ranges that are available and return total size available.

**Return**

Total available size.

#### <a id="c-xe_ggtt_encode_pte_flags"></a>`xe_ggtt_encode_pte_flags()`

```c
u64 xe_ggtt_encode_pte_flags(struct xe_ggtt *ggtt, struct xe_bo *bo, u16 pat_index)
```

Get PTE encoding flags for BO

**Parameters**

- `struct xe_ggtt *ggtt`: [`xe_ggtt`](#c-struct-xe_ggtt)
- `struct xe_bo *bo`: `xe_bo`
- `u16 pat_index`: The pat_index for the PTE.

**Description**

This function returns the pte_flags for a given BO, without  address.
It's used for DPT to fill a GGTT mapped BO with a linear lookup table.

#### <a id="c-xe_ggtt_read_pte"></a>`xe_ggtt_read_pte()`

```c
u64 xe_ggtt_read_pte(struct xe_ggtt *ggtt, u64 offset)
```

Read a PTE from the GGTT

**Parameters**

- `struct xe_ggtt *ggtt`: [`xe_ggtt`](#c-struct-xe_ggtt)
- `u64 offset`: the offset for which the mapping should be read.

**Description**

Used by testcases, and by display reading out an inherited bios FB.

#### <a id="c-xe_ggtt_node_addr"></a>`xe_ggtt_node_addr()`

```c
u64 xe_ggtt_node_addr(const struct xe_ggtt_node *node)
```

Get **node** offset in GGTT.

**Parameters**

- `const struct xe_ggtt_node *node`: [`xe_ggtt_node`](#c-struct-xe_ggtt_node)

**Description**

Get the GGTT offset for allocated node.

#### <a id="c-xe_ggtt_node_size"></a>`xe_ggtt_node_size()`

```c
u64 xe_ggtt_node_size(const struct xe_ggtt_node *node)
```

Get **node** allocation size.

**Parameters**

- `const struct xe_ggtt_node *node`: [`xe_ggtt_node`](#c-struct-xe_ggtt_node)

**Description**

Get the allocated node's size.


<a id="rst-pagetable-building"></a>

## Pagetable building


Below we use the term "page-table" for both page-directories, containing
pointers to lower level page-directories or page-tables, and level 0
page-tables that contain only page-table-entries pointing to memory pages.

When inserting an address range in an already existing page-table tree
there will typically be a set of page-tables that are shared with other
address ranges, and a set that are private to this address range.
The set of shared page-tables can be at most two per level,
and those can't be updated immediately because the entries of those
page-tables may still be in use by the gpu for other mappings. Therefore
when inserting entries into those, we instead stage those insertions by
adding insertion data into struct xe_vm_pgtable_update structures. This
data, (subtrees for the cpu and page-table-entries for the gpu) is then
added in a separate commit step. CPU-data is committed while still under the
vm lock, the object lock and for userptr, the notifier lock in read mode.
The GPU async data is committed either by the GPU or CPU after fulfilling
relevant dependencies.
For non-shared page-tables (and, in fact, for shared ones that aren't
existing at the time of staging), we add the data in-place without the
special update structures. This private part of the page-table tree will
remain disconnected from the vm page-table tree until data is committed to
the shared page tables of the vm tree in the commit phase.

---

# Pcode

_Peios Kernel / Hardware and drivers / Graphics / xe_

> Reference for Pcode.

<!-- SPDX-License-Identifier: (GPL-2.0+ OR MIT) -->

<a id="rst-pcode"></a>

## Pcode


Xe PCODE is the component responsible for interfacing with the PCODE
firmware.
It shall provide a very simple ABI to other Xe components, but be the
single and consolidated place that will communicate with PCODE. All read
and write operations to PCODE will be internal and private to this component.

What's next:
- PCODE hw metrics
- PCODE for display operations


<a id="rst-internal-api"></a>

### Internal API


#### <a id="c-xe_pcode_request"></a>`xe_pcode_request()`

```c
int xe_pcode_request(struct xe_tile *tile, u32 mbox, u32 request, u32 reply_mask, u32 reply, int timeout_base_ms)
```

send PCODE request until acknowledgment

**Parameters**

- `struct xe_tile *tile`: tile
- `u32 mbox`: PCODE mailbox ID the request is targeted for
- `u32 request`: request ID
- `u32 reply_mask`: mask used to check for request acknowledgment
- `u32 reply`: value used to check for request acknowledgment
- `int timeout_base_ms`: timeout for polling with preemption enabled

**Description**

Keep resending the **request** to **mbox** until PCODE acknowledges it, PCODE
reports an error or an overall timeout of **timeout_base_ms**+50 ms expires.
The request is acknowledged once the PCODE reply dword equals **reply** after
applying **reply_mask**. Polling is first attempted with preemption enabled
for **timeout_base_ms** and if this times out for another 50 ms with
preemption disabled.

Returns 0 on success, `-ETIMEDOUT` in case of a timeout, \<0 in case of some
other error as reported by PCODE.

#### <a id="c-xe_pcode_init_min_freq_table"></a>`xe_pcode_init_min_freq_table()`

```c
int xe_pcode_init_min_freq_table(struct xe_tile *tile, u32 min_gt_freq, u32 max_gt_freq)
```

Initialize PCODE's QOS frequency table

**Parameters**

- `struct xe_tile *tile`: tile instance
- `u32 min_gt_freq`: Minimal (RPn) GT frequency in units of 50MHz.
- `u32 max_gt_freq`: Maximal (RP0) GT frequency in units of 50MHz.

**Description**

This function initialize PCODE's QOS frequency table for a proper minimal
frequency/power steering decision, depending on the current requested GT
frequency. For older platforms this was a more complete table including
the IA freq. However for the latest platforms this table become a simple
1-1 Ring vs GT frequency. Even though, without setting it, PCODE might
not take the right decisions for some memory frequencies and affect latency.

It returns 0 on success, and -ERROR number on failure, -EINVAL if max
frequency is higher then the minimal, and other errors directly translated
from the PCODE Error returns:
- -ENXIO: "Illegal Command"
- -ETIMEDOUT: "Timed out"
- -EINVAL: "Illegal Data"
- -ENXIO, "Illegal Subcommand"
- -EBUSY: "PCODE Locked"
- -EOVERFLOW, "GT ratio out of range"
- -EACCES, "PCODE Rejected"
- -EPROTO, "Unknown"

#### <a id="c-xe_pcode_ready"></a>`xe_pcode_ready()`

```c
int xe_pcode_ready(struct xe_device *xe, bool locked)
```

Ensure PCODE is initialized

**Parameters**

- `struct xe_device *xe`: xe instance
- `bool locked`: true if lock held, false otherwise

**Description**

PCODE init mailbox is polled only on root gt of root tile
as the root tile provides the initialization is complete only
after all the tiles have completed the initialization.
Called only on early probe without locks and with locks in
resume path.

Returns 0 on success, and -error number on failure.

#### <a id="c-xe_pcode_init"></a>`xe_pcode_init()`

```c
void xe_pcode_init(struct xe_tile *tile)
```

initialize components of PCODE

**Parameters**

- `struct xe_tile *tile`: tile instance

**Description**

This function initializes the xe_pcode component.
To be called once only during probe.

#### <a id="c-xe_pcode_probe_early"></a>`xe_pcode_probe_early()`

```c
int xe_pcode_probe_early(struct xe_device *xe)
```

initializes PCODE

**Parameters**

- `struct xe_device *xe`: xe instance

**Description**

This function checks the initialization status of PCODE
To be called once only during early probe without locks.

Returns 0 on success, error code otherwise


<a id="rst-survivability-mode"></a>
<a id="rst-xe-survivability-mode"></a>

## Survivability Mode


Survivability Mode is a software based workflow for recovering a system in a failed boot state
Here system recoverability is concerned with recovering the firmware responsible for boot.

**Boot Survivability**

Boot Survivability is implemented by loading the driver with bare minimum (no drm card) to allow
the firmware to be flashed through mei driver and collect telemetry. The driver's probe flow is
modified such that it enters survivability mode when pcode initialization is incomplete and boot
status denotes a failure.

Survivability mode can also be entered manually using the survivability mode attribute available
through configfs which is beneficial in several usecases. It can be used to address scenarios
where pcode does not detect failure or for validation purposes. It can also be used in
In-Field-Repair (IFR) to repair a single card without impacting the other cards in a node.

Use below command enable survivability mode manually:

```text
# echo 1 > /sys/kernel/config/xe/0000:03:00.0/survivability_mode
```

It is the responsibility of the user to clear the mode once firmware flash is complete.

Refer xe_configfs for more details on how to use configfs

Survivability mode is indicated by the below admin-only readable sysfs entry. It
provides information about the type of survivability mode (Boot/Runtime).

```shell
# cat /sys/bus/pci/devices/<device>/survivability_mode
  Boot
```

Any additional debug information if present will be visible under the directory
`survivability_info`:

```text
/sys/bus/pci/devices/<device>/survivability_info/
├── aux_info0
├── aux_info1
├── aux_info2
├── aux_info3
├── aux_info4
├── capability_info
├── fdo_mode
├── postcode_trace
└── postcode_trace_overflow
```

This directory has the following attributes

- `capability_info` : Indicates Boot status and support for additional information

- `postcode_trace`, `postcode_trace_overflow` : Each postcode is a 8bit value and
  represents a boot failure event. When a new failure event is logged by PCODE the
  existing postcodes are shifted left. These entries provide a history of 8 postcodes.

- `aux_info<n>` : Some failures have additional debug information

- `fdo_mode` : To allow recovery in scenarios where MEI itself fails, a new SPI Flash
  Descriptor Override (FDO) mode is added in v2 survivability breadcrumbs. This mode is enabled
  by PCODE and provides the ability to directly update the firmware via SPI Driver without
  any dependency on MEI. Xe KMD initializes the nvm aux driver if FDO mode is enabled.

**Runtime Survivability**

Certain runtime firmware errors can cause the device to enter a wedged state
(xe-device-wedging) requiring a firmware flash to restore normal operation.
Runtime Survivability Mode indicates that a firmware flash is necessary to recover the device and
is indicated by the presence of survivability mode sysfs.
Survivability mode sysfs provides information about the type of survivability mode.

```shell
# cat /sys/bus/pci/devices/<device>/survivability_mode
  Runtime
```

When such errors occur, userspace is notified with the drm device wedged uevent and runtime
survivability mode. User can then initiate a firmware flash using userspace tools like fwupd
to restore device to normal operation.

---

# Runtime Power Management

_Peios Kernel / Hardware and drivers / Graphics / xe_

> Reference for Runtime Power Management.

<a id="rst-runtime-power-management"></a>

<!-- SPDX-License-Identifier: (GPL-2.0+ OR MIT) -->


Xe PM implements the main routines for both system level suspend states and
for the opportunistic runtime suspend states.

System Level Suspend (S-States) - In general this is OS initiated suspend
driven by ACPI for achieving S0ix (a.k.a. S2idle, freeze), S3 (suspend to ram),
S4 (disk). The main functions here are `xe_pm_suspend` and `xe_pm_resume`. They
are the main point for the suspend to and resume from these states.

PCI Device Suspend (D-States) - This is the opportunistic PCIe device low power
state D3, controlled by the PCI subsystem and ACPI with the help from the
runtime_pm infrastructure.
PCI D3 is special and can mean D3hot, where Vcc power is on for keeping memory
alive and quicker low latency resume or D3Cold where Vcc power is off for
better power savings.
The Vcc control of PCI hierarchy can only be controlled at the PCI root port
level, while the device driver can be behind multiple bridges/switches and
paired with other devices. For this reason, the PCI subsystem cannot perform
the transition towards D3Cold. The lowest runtime PM possible from the PCI
subsystem is D3hot. Then, if all these paired devices in the same root port
are in D3hot, ACPI will assist here and run its own methods (_PR3 and _OFF)
to perform the transition from D3hot to D3cold. Xe may disallow this
transition by calling pci_d3cold_disable(root_pdev) before going to runtime
suspend. It will be based on runtime conditions such as VRAM usage for a
quick and low latency resume for instance.

Runtime PM - This infrastructure provided by the Linux kernel allows the
device drivers to indicate when the can be runtime suspended, so the device
could be put at D3 (if supported), or allow deeper package sleep states
(PC-states), and/or other low level power states. Xe PM component provides
`xe_pm_runtime_suspend` and `xe_pm_runtime_resume` functions that PCI
subsystem will call before transition to/from runtime suspend.

Also, Xe PM provides get and put functions that Xe driver will use to
indicate activity. In order to avoid locking complications with the memory
management, whenever possible, these get and put functions needs to be called
from the higher/outer levels.
The main cases that need to be protected from the outer levels are: IOCTL,
sysfs, debugfs, dma-buf sharing, GPU execution.

This component is not responsible for GT idleness (RC6) nor GT frequency
management (RPS).


<a id="rst-internal-api"></a>

## Internal API


#### <a id="c-xe_pm_might_block_on_suspend"></a>`xe_pm_might_block_on_suspend()`

```c
void xe_pm_might_block_on_suspend(void)
```

Annotate that the code might block on suspend

**Parameters**

- `void`: no arguments

**Description**

Annotation to use where the code might block or seize to make
progress pending resume completion.

#### <a id="c-xe_pm_block_on_suspend"></a>`xe_pm_block_on_suspend()`

```c
int xe_pm_block_on_suspend(struct xe_device *xe)
```

Block pending suspend.

**Parameters**

- `struct xe_device *xe`: The xe device about to be suspended.

**Description**

Block if the pm notifier has start evicting bos, to avoid
racing and validating those bos back. The function is
annotated to ensure no locks are held that are also grabbed
in the pm notifier or the device suspend / resume.
This is intended to be used by freezable tasks only.
(Not freezable workqueues), with the intention that the function
returns `-ERESTARTSYS` when tasks are frozen during suspend,
and allows the task to freeze. The caller must be able to
handle the `-ERESTARTSYS`.

**Return**

`0` on success, `-ERESTARTSYS` on signal pending or
if freezing requested.

#### <a id="c-xe_rpm_reclaim_safe"></a>`xe_rpm_reclaim_safe()`

```c
bool xe_rpm_reclaim_safe(const struct xe_device *xe)
```

Whether runtime resume can be done from reclaim context

**Parameters**

- `const struct xe_device *xe`: The xe device.

**Return**

true if it is safe to runtime resume from reclaim context.
false otherwise.

#### <a id="c-xe_pm_suspend"></a>`xe_pm_suspend()`

```c
int xe_pm_suspend(struct xe_device *xe)
```

Helper for System suspend, i.e. S0->S3 / S0->S2idle

**Parameters**

- `struct xe_device *xe`: xe device instance

**Return**

0 on success

#### <a id="c-xe_pm_resume"></a>`xe_pm_resume()`

```c
int xe_pm_resume(struct xe_device *xe)
```

Helper for System resume S3->S0 / S2idle->S0

**Parameters**

- `struct xe_device *xe`: xe device instance

**Return**

0 on success

#### <a id="c-xe_pm_init"></a>`xe_pm_init()`

```c
int xe_pm_init(struct xe_device *xe)
```

Initialize Xe Power Management

**Parameters**

- `struct xe_device *xe`: xe device instance

**Description**

This component is responsible for System and Device sleep states.

Returns 0 for success, negative error code otherwise.

#### <a id="c-xe_pm_fini"></a>`xe_pm_fini()`

```c
void xe_pm_fini(struct xe_device *xe)
```

Finalize PM

**Parameters**

- `struct xe_device *xe`: xe device instance

#### <a id="c-xe_pm_runtime_suspended"></a>`xe_pm_runtime_suspended()`

```c
bool xe_pm_runtime_suspended(struct xe_device *xe)
```

Check if runtime_pm state is suspended

**Parameters**

- `struct xe_device *xe`: xe device instance

**Description**

This does not provide any guarantee that the device is going to remain
suspended as it might be racing with the runtime state transitions.
It can be used only as a non-reliable assertion, to ensure that we are not in
the sleep state while trying to access some memory for instance.

Returns true if PCI device is suspended, false otherwise.

#### <a id="c-xe_pm_runtime_suspend"></a>`xe_pm_runtime_suspend()`

```c
int xe_pm_runtime_suspend(struct xe_device *xe)
```

Prepare our device for D3hot/D3Cold

**Parameters**

- `struct xe_device *xe`: xe device instance

**Description**

Returns 0 for success, negative error code otherwise.

#### <a id="c-xe_pm_runtime_resume"></a>`xe_pm_runtime_resume()`

```c
int xe_pm_runtime_resume(struct xe_device *xe)
```

Waking up from D3hot/D3Cold

**Parameters**

- `struct xe_device *xe`: xe device instance

**Description**

Returns 0 for success, negative error code otherwise.

#### <a id="c-xe_pm_runtime_get"></a>`xe_pm_runtime_get()`

```c
void xe_pm_runtime_get(struct xe_device *xe)
```

Get a runtime_pm reference and resume synchronously

**Parameters**

- `struct xe_device *xe`: xe device instance

**Description**

When possible, scope-based runtime PM (through guard(xe_pm_runtime)) is
be preferred over direct usage of this function.  Manual get/put handling
should only be used when the function contains goto-based logic which
can break scope-based handling, or when the lifetime of the runtime PM
reference does not match a specific scope (e.g., runtime PM obtained in one
function and released in a different one).

#### <a id="c-xe_pm_runtime_put"></a>`xe_pm_runtime_put()`

```c
void xe_pm_runtime_put(struct xe_device *xe)
```

Put the runtime_pm reference back and mark as idle

**Parameters**

- `struct xe_device *xe`: xe device instance

#### <a id="c-xe_pm_runtime_get_ioctl"></a>`xe_pm_runtime_get_ioctl()`

```c
int xe_pm_runtime_get_ioctl(struct xe_device *xe)
```

Get a runtime_pm reference before ioctl

**Parameters**

- `struct xe_device *xe`: xe device instance

**Description**

When possible, scope-based runtime PM (through
ACQUIRE(xe_pm_runtime_ioctl, ...)) is be preferred over direct usage of this
function.  Manual get/put handling should only be used when the function
contains goto-based logic which can break scope-based handling, or when the
lifetime of the runtime PM reference does not match a specific scope (e.g.,
runtime PM obtained in one function and released in a different one).

**Return**

Any number greater than or equal to 0 for success, negative error
code otherwise.

#### <a id="c-xe_pm_runtime_get_if_active"></a>`xe_pm_runtime_get_if_active()`

```c
bool xe_pm_runtime_get_if_active(struct xe_device *xe)
```

Get a runtime_pm reference if device active

**Parameters**

- `struct xe_device *xe`: xe device instance

**Return**

True if device is awake (regardless the previous number of references)
and a new reference was taken, false otherwise.

#### <a id="c-xe_pm_runtime_get_if_in_use"></a>`xe_pm_runtime_get_if_in_use()`

```c
bool xe_pm_runtime_get_if_in_use(struct xe_device *xe)
```

Get a new reference if device is active with previous ref taken

**Parameters**

- `struct xe_device *xe`: xe device instance

**Return**

True if device is awake, a previous reference had been already taken,
and a new reference was now taken, false otherwise.

#### <a id="c-xe_pm_runtime_get_noresume"></a>`xe_pm_runtime_get_noresume()`

```c
void xe_pm_runtime_get_noresume(struct xe_device *xe)
```

Bump runtime PM usage counter without resuming

**Parameters**

- `struct xe_device *xe`: xe device instance

**Description**

This function should be used in inner places where it is surely already
protected by outer-bound callers of `xe_pm_runtime_get`.
It will warn if not protected.
The reference should be put back after this function regardless, since it
will always bump the usage counter, regardless.

When possible, scope-based runtime PM (through guard(xe_pm_runtime_noresume))
is be preferred over direct usage of this function.  Manual get/put handling
should only be used when the function contains goto-based logic which can
break scope-based handling, or when the lifetime of the runtime PM reference
does not match a specific scope (e.g., runtime PM obtained in one function
and released in a different one).

#### <a id="c-xe_pm_runtime_resume_and_get"></a>`xe_pm_runtime_resume_and_get()`

```c
bool xe_pm_runtime_resume_and_get(struct xe_device *xe)
```

Resume, then get a runtime_pm ref if awake.

**Parameters**

- `struct xe_device *xe`: xe device instance

**Return**

True if device is awake and the reference was taken, false otherwise.

#### <a id="c-xe_pm_assert_unbounded_bridge"></a>`xe_pm_assert_unbounded_bridge()`

```c
void xe_pm_assert_unbounded_bridge(struct xe_device *xe)
```

Disable PM on unbounded pcie parent bridge

**Parameters**

- `struct xe_device *xe`: xe device instance

#### <a id="c-xe_pm_set_vram_threshold"></a>`xe_pm_set_vram_threshold()`

```c
int xe_pm_set_vram_threshold(struct xe_device *xe, u32 threshold)
```

Set a VRAM threshold for allowing/blocking D3Cold

**Parameters**

- `struct xe_device *xe`: xe device instance
- `u32 threshold`: VRAM size in MiB for the D3cold threshold

**Return**

* 0          - success
* -EINVAL    - invalid argument

#### <a id="c-xe_pm_d3cold_allowed_toggle"></a>`xe_pm_d3cold_allowed_toggle()`

```c
void xe_pm_d3cold_allowed_toggle(struct xe_device *xe)
```

Check conditions to toggle d3cold.allowed

**Parameters**

- `struct xe_device *xe`: xe device instance

**Description**

To be called during runtime_pm idle callback.
Check for all the D3Cold conditions ahead of runtime suspend.

#### <a id="c-xe_pm_module_init"></a>`xe_pm_module_init()`

```c
int xe_pm_module_init(void)
```

Perform xe_pm specific module initialization.

**Parameters**

- `void`: no arguments

**Return**

0 on success. Currently doesn't fail.

---

# Register Table Processing

_Peios Kernel / Hardware and drivers / Graphics / xe_

> Reference for Register Table Processing.

<a id="rst-register-table-processing"></a>

<!-- SPDX-License-Identifier: (GPL-2.0+ OR MIT) -->


Internal infrastructure to define how registers should be updated based on
rules and actions. This can be used to define tables with multiple entries
(one per register) that will be walked over at some point in time to apply
the values to the registers that have matching rules.


<a id="rst-internal-api"></a>

## Internal API


#### <a id="c-struct-xe_rtp_action"></a>`struct xe_rtp_action`

action to take for any matching rule

**Definition**

```c
struct xe_rtp_action {
        struct xe_reg           reg;
        u32 clr_bits;
        u32 set_bits;
    #define XE_RTP_NOCHECK          .read_mask = 0;
        u32 read_mask;
    #define XE_RTP_ACTION_FLAG_ENGINE_BASE          BIT(0);
        u8 flags;
};
```

**Members**

- `reg`: Register
- `clr_bits`: bits to clear when updating register. It's always a
  superset of bits being modified
- `set_bits`: bits to set when updating register
- `read_mask`: mask for bits to consider when reading value back
- `flags`: flags to apply on rule evaluation or action

**Description**

This struct records what action should be taken in a register that has a
matching rule. Example of actions: set/clear bits.



#### <a id="c-XE_RTP_RULE_PLATFORM"></a>`XE_RTP_RULE_PLATFORM()`

```c
XE_RTP_RULE_PLATFORM(plat_)
```

Create rule matching platform

**Parameters**

- `plat_`: platform to match

**Description**

Refer to [`XE_RTP_RULES()`](#c-XE_RTP_RULES) for expected usage.

#### <a id="c-XE_RTP_RULE_SUBPLATFORM"></a>`XE_RTP_RULE_SUBPLATFORM()`

```c
XE_RTP_RULE_SUBPLATFORM(plat_, sub_)
```

Create rule matching platform and sub-platform

**Parameters**

- `plat_`: platform to match
- `sub_`: sub-platform to match

**Description**

Refer to [`XE_RTP_RULES()`](#c-XE_RTP_RULES) for expected usage.

#### <a id="c-XE_RTP_RULE_GRAPHICS_STEP"></a>`XE_RTP_RULE_GRAPHICS_STEP()`

```c
XE_RTP_RULE_GRAPHICS_STEP(start_, end_)
```

Create rule matching graphics stepping

**Parameters**

- `start_`: First stepping matching the rule
- `end_`: First stepping that does not match the rule

**Description**

Note that the range matching this rule is \[ **start_**, **end_** ), i.e. inclusive
on the left, exclusive on the right.

Refer to [`XE_RTP_RULES()`](#c-XE_RTP_RULES) for expected usage.

#### <a id="c-XE_RTP_RULE_MEDIA_STEP"></a>`XE_RTP_RULE_MEDIA_STEP()`

```c
XE_RTP_RULE_MEDIA_STEP(start_, end_)
```

Create rule matching media stepping

**Parameters**

- `start_`: First stepping matching the rule
- `end_`: First stepping that does not match the rule

**Description**

Note that the range matching this rule is \[ **start_**, **end_** ), i.e. inclusive
on the left, exclusive on the right.

Refer to [`XE_RTP_RULES()`](#c-XE_RTP_RULES) for expected usage.

#### <a id="c-XE_RTP_RULE_ENGINE_CLASS"></a>`XE_RTP_RULE_ENGINE_CLASS()`

```c
XE_RTP_RULE_ENGINE_CLASS(cls_)
```

Create rule matching an engine class

**Parameters**

- `cls_`: Engine class to match

**Description**

Refer to [`XE_RTP_RULES()`](#c-XE_RTP_RULES) for expected usage.

#### <a id="c-XE_RTP_RULE_FUNC"></a>`XE_RTP_RULE_FUNC()`

```c
XE_RTP_RULE_FUNC(func__)
```

Create rule using callback function for match

**Parameters**

- `func__`: Function to call to decide if rule matches

**Description**

This allows more complex checks to be performed. The `XE_RTP`
infrastructure will simply call the function **func_** passed to decide if this
rule matches the device.

Refer to [`XE_RTP_RULES()`](#c-XE_RTP_RULES) for expected usage.

#### <a id="c-XE_RTP_RULE_GRAPHICS_VERSION"></a>`XE_RTP_RULE_GRAPHICS_VERSION()`

```c
XE_RTP_RULE_GRAPHICS_VERSION(ver__)
```

Create rule matching graphics version

**Parameters**

- `ver__`: Graphics IP version to match

**Description**

Refer to [`XE_RTP_RULES()`](#c-XE_RTP_RULES) for expected usage.

#### <a id="c-XE_RTP_RULE_GRAPHICS_VERSION_RANGE"></a>`XE_RTP_RULE_GRAPHICS_VERSION_RANGE()`

```c
XE_RTP_RULE_GRAPHICS_VERSION_RANGE(ver_start__, ver_end__)
```

Create rule matching a range of graphics version

**Parameters**

- `ver_start__`: First graphics IP version to match
- `ver_end__`: Last graphics IP version to match

**Description**

Note that the range matching this rule is \[ **ver_start__**, **ver_end__** \], i.e.
inclusive on both sides

Refer to [`XE_RTP_RULES()`](#c-XE_RTP_RULES) for expected usage.

#### <a id="c-XE_RTP_RULE_GRAPHICS_VERSION_ANY_GT"></a>`XE_RTP_RULE_GRAPHICS_VERSION_ANY_GT()`

```c
XE_RTP_RULE_GRAPHICS_VERSION_ANY_GT(ver__)
```

Create rule matching graphics version on any GT

**Parameters**

- `ver__`: Graphics IP version to match

**Description**

Like XE_RTP_RULE_GRAPHICS_VERSION, but it matches even if the current GT
being checked is not of the graphics type. It allows to add RTP entries to
another GT when the device contains a Graphics IP with that version.

Refer to [`XE_RTP_RULES()`](#c-XE_RTP_RULES) for expected usage.

#### <a id="c-XE_RTP_RULE_MEDIA_VERSION"></a>`XE_RTP_RULE_MEDIA_VERSION()`

```c
XE_RTP_RULE_MEDIA_VERSION(ver__)
```

Create rule matching media version

**Parameters**

- `ver__`: Media IP version to match

**Description**

Refer to [`XE_RTP_RULES()`](#c-XE_RTP_RULES) for expected usage.

#### <a id="c-XE_RTP_RULE_MEDIA_VERSION_RANGE"></a>`XE_RTP_RULE_MEDIA_VERSION_RANGE()`

```c
XE_RTP_RULE_MEDIA_VERSION_RANGE(ver_start__, ver_end__)
```

Create rule matching a range of media version

**Parameters**

- `ver_start__`: First media IP version to match
- `ver_end__`: Last media IP version to match

**Description**

Note that the range matching this rule is \[ **ver_start__**, **ver_end__** \], i.e.
inclusive on both sides

Refer to [`XE_RTP_RULES()`](#c-XE_RTP_RULES) for expected usage.

#### <a id="c-XE_RTP_RULE_MEDIA_VERSION_ANY_GT"></a>`XE_RTP_RULE_MEDIA_VERSION_ANY_GT()`

```c
XE_RTP_RULE_MEDIA_VERSION_ANY_GT(ver__)
```

Create rule matching media version on any GT

**Parameters**

- `ver__`: Media IP version to match

**Description**

Like XE_RTP_RULE_MEDIA_VERSION, but it matches even if the current GT being
checked is not of the media type. It allows to add RTP entries to another
GT when the device contains a Media IP with that version.

Refer to [`XE_RTP_RULES()`](#c-XE_RTP_RULES) for expected usage.

#### <a id="c-XE_RTP_RULE_IS_INTEGRATED"></a>`XE_RTP_RULE_IS_INTEGRATED`

```c
XE_RTP_RULE_IS_INTEGRATED
```

Create a rule matching integrated graphics devices

**Description**

Refer to [`XE_RTP_RULES()`](#c-XE_RTP_RULES) for expected usage.

#### <a id="c-XE_RTP_RULE_IS_DISCRETE"></a>`XE_RTP_RULE_IS_DISCRETE`

```c
XE_RTP_RULE_IS_DISCRETE
```

Create a rule matching discrete graphics devices

**Description**

Refer to [`XE_RTP_RULES()`](#c-XE_RTP_RULES) for expected usage.

#### <a id="c-XE_RTP_RULE_OR"></a>`XE_RTP_RULE_OR`

```c
XE_RTP_RULE_OR
```

Create an OR condition for rtp rules

**Description**

RTP rules are AND'ed when evaluated and all of them need to match.
XE_RTP_RULE_OR allows to create set of rules where any of them matching is
sufficient for the action to trigger. Example:

```c
const struct xe_rtp_entry_sr entries[] = {
        ...
        { XE_RTP_NAME("test-entry"),
          XE_RTP_RULES(PLATFORM(DG2), OR, PLATFORM(TIGERLAKE)),
          ...
        },
        ...
};
```

#### <a id="c-XE_RTP_ACTION_WR"></a>`XE_RTP_ACTION_WR()`

```c
XE_RTP_ACTION_WR(reg_, val_, ...)
```

Helper to write a value to the register, overriding all the bits

**Parameters**

- `reg_`: Register
- `val_`: Value to set
- `...`: Additional fields to override in the struct xe_rtp_action entry

**Description**

The correspondent notation in bspec is:

REGNAME = VALUE

#### <a id="c-XE_RTP_ACTION_SET"></a>`XE_RTP_ACTION_SET()`

```c
XE_RTP_ACTION_SET(reg_, val_, ...)
```

Set bits from **val_** in the register.

**Parameters**

- `reg_`: Register
- `val_`: Bits to set in the register
- `...`: Additional fields to override in the struct xe_rtp_action entry

**Description**

For masked registers this translates to a single write, while for other
registers it's a RMW. The correspondent bspec notation is (example for bits 2
and 5, but could be any):

REGNAME\[2\] = 1
REGNAME\[5\] = 1

#### <a id="c-XE_RTP_ACTION_CLR"></a>`XE_RTP_ACTION_CLR()`

```c
XE_RTP_ACTION_CLR(reg_, val_, ...)
```

Clear bits from **val_** in the register.

**Parameters**

- `reg_`: Register
- `val_`: Bits to clear in the register
- `...`: Additional fields to override in the struct xe_rtp_action entry

**Description**

For masked registers this translates to a single write, while for other
registers it's a RMW. The correspondent bspec notation is (example for bits 2
and 5, but could be any):

REGNAME\[2\] = 0
REGNAME\[5\] = 0

#### <a id="c-XE_RTP_ACTION_FIELD_SET"></a>`XE_RTP_ACTION_FIELD_SET()`

```c
XE_RTP_ACTION_FIELD_SET(reg_, mask_bits_, val_, ...)
```

Set a bit range

**Parameters**

- `reg_`: Register
- `mask_bits_`: Mask of bits to be changed in the register, forming a field
- `val_`: Value to set in the field denoted by **mask_bits_**
- `...`: Additional fields to override in the struct xe_rtp_action entry

**Description**

For masked registers this translates to a single write, while for other
registers it's a RMW. The correspondent bspec notation is:

REGNAME\[\<end>:\<start>\] = VALUE

#### <a id="c-XE_RTP_ACTION_WHITELIST"></a>`XE_RTP_ACTION_WHITELIST()`

```c
XE_RTP_ACTION_WHITELIST(reg_, val_, ...)
```

Add register to userspace whitelist

**Parameters**

- `reg_`: Register
- `val_`: Whitelist-specific flags to set
- `...`: Additional fields to override in the struct xe_rtp_action entry

**Description**

Add a register to the whitelist, allowing userspace to modify the ster with
regular user privileges.

#### <a id="c-XE_RTP_NAME"></a>`XE_RTP_NAME()`

```c
XE_RTP_NAME(s_)
```

Helper to set the name in xe_rtp_entry

**Parameters**

- `s_`: Name describing this rule, often a HW-specific number

**Description**

TODO: maybe move this behind a debug config?

#### <a id="c-XE_RTP_ENTRY_FLAG"></a>`XE_RTP_ENTRY_FLAG()`

```c
XE_RTP_ENTRY_FLAG(...)
```

Helper to add multiple flags to a struct xe_rtp_entry_sr

**Parameters**

- `...`: Entry flags, without the `XE_RTP_ENTRY_FLAG_` prefix

**Description**

Helper to automatically add a `XE_RTP_ENTRY_FLAG_` prefix to the flags
when defining struct xe_rtp_entry entries. Example:

```c
const struct xe_rtp_entry_sr wa_entries[] = {
        ...
        { XE_RTP_NAME("test-entry"),
          ...
          XE_RTP_ENTRY_FLAG(FOREACH_ENGINE),
          ...
        },
        ...
};
```

#### <a id="c-XE_RTP_ACTION_FLAG"></a>`XE_RTP_ACTION_FLAG()`

```c
XE_RTP_ACTION_FLAG(...)
```

Helper to add multiple flags to a struct xe_rtp_action

**Parameters**

- `...`: Action flags, without the `XE_RTP_ACTION_FLAG_` prefix

**Description**

Helper to automatically add a `XE_RTP_ACTION_FLAG_` prefix to the flags
when defining struct xe_rtp_action entries. Example:

```c
const struct xe_rtp_entry_sr wa_entries[] = {
        ...
        { XE_RTP_NAME("test-entry"),
          ...
          XE_RTP_ACTION_SET(..., XE_RTP_ACTION_FLAG(FOREACH_ENGINE)),
          ...
        },
        ...
};
```

#### <a id="c-XE_RTP_RULES"></a>`XE_RTP_RULES()`

```c
XE_RTP_RULES(...)
```

Helper to set multiple rules to a struct xe_rtp_entry_sr entry

**Parameters**

- `...`: Rules

**Description**

At least one rule is needed and up to 12 are supported. Multiple rules are
AND'ed together, i.e. all the rules must evaluate to true for the entry to
be processed. See XE_RTP_MATCH_* for the possible match rules. Example:

```c
const struct xe_rtp_entry_sr wa_entries[] = {
        ...
        { XE_RTP_NAME("test-entry"),
          XE_RTP_RULES(SUBPLATFORM(DG2, G10), GRAPHICS_STEP(A0, B0)),
          ...
        },
        ...
};
```

#### <a id="c-XE_RTP_ACTIONS"></a>`XE_RTP_ACTIONS()`

```c
XE_RTP_ACTIONS(...)
```

Helper to set multiple actions to a struct xe_rtp_entry_sr

**Parameters**

- `...`: Actions to be taken

**Description**

At least one action is needed and up to 12 are supported. See XE_RTP_ACTION_*
for the possible actions. Example:

```c
const struct xe_rtp_entry_sr wa_entries[] = {
        ...
        { XE_RTP_NAME("test-entry"),
          XE_RTP_RULES(...),
          XE_RTP_ACTIONS(SET(..), SET(...), CLR(...)),
          ...
        },
        ...
};
```

#### <a id="c-xe_rtp_match_even_instance"></a>`xe_rtp_match_even_instance()`

```c
bool xe_rtp_match_even_instance(const struct xe_device *xe, const struct xe_gt *gt, const struct xe_hw_engine *hwe)
```

Match if engine instance is even

**Parameters**

- `const struct xe_device *xe`: Device structure
- `const struct xe_gt *gt`: GT structure
- `const struct xe_hw_engine *hwe`: Engine instance

**Return**

true if engine instance is even, false otherwise

#### <a id="c-xe_rtp_match_has_flat_ccs"></a>`xe_rtp_match_has_flat_ccs()`

```c
bool xe_rtp_match_has_flat_ccs(const struct xe_device *xe, const struct xe_gt *gt, const struct xe_hw_engine *hwe)
```

Match when platform has FlatCCS compression

**Parameters**

- `const struct xe_device *xe`: Device structure
- `const struct xe_gt *gt`: GT structure
- `const struct xe_hw_engine *hwe`: Engine instance

**Return**

true if platform has FlatCCS compression, false otherwise



#### <a id="c-xe_rtp_process_ctx_enable_active_tracking"></a>`xe_rtp_process_ctx_enable_active_tracking()`

```c
void xe_rtp_process_ctx_enable_active_tracking(struct xe_rtp_process_ctx *ctx, unsigned long *active_entries, size_t n_entries)
```

Enable tracking of active entries

**Parameters**

- `struct xe_rtp_process_ctx *ctx`: The context for processing the table
- `unsigned long *active_entries`: bitmap to store the active entries
- `size_t n_entries`: number of entries to be processed

**Description**

Set additional metadata to track what entries are considered "active", i.e.
their rules match the condition. Bits are never cleared: entries with
matching rules set the corresponding bit in the bitmap.

#### <a id="c-xe_rtp_process_to_sr"></a>`xe_rtp_process_to_sr()`

```c
void xe_rtp_process_to_sr(struct xe_rtp_process_ctx *ctx, const struct xe_rtp_entry_sr *entries, size_t n_entries, struct xe_reg_sr *sr)
```

Process all rtp **entries**, adding the matching ones to the save-restore argument.

**Parameters**

- `struct xe_rtp_process_ctx *ctx`: The context for processing the table, with one of device, gt or hwe
- `const struct xe_rtp_entry_sr *entries`: Table with RTP definitions
- `size_t n_entries`: Number of entries to process, usually ARRAY_SIZE(entries)
- `struct xe_reg_sr *sr`: Save-restore struct where matching rules execute the action. This can be
  viewed as the "coalesced view" of multiple the tables. The bits for each
  register set are expected not to collide with previously added entries

**Description**

Walk the table pointed by **entries** (with an empty sentinel) and add all
entries with matching rules to **sr**. If **hwe** is not NULL, its mmio_base is
used to calculate the right register offset

#### <a id="c-xe_rtp_process"></a>`xe_rtp_process()`

```c
void xe_rtp_process(struct xe_rtp_process_ctx *ctx, const struct xe_rtp_entry *entries)
```

Process all rtp **entries**, without running any action

**Parameters**

- `struct xe_rtp_process_ctx *ctx`: The context for processing the table, with one of device, gt or hwe
- `const struct xe_rtp_entry *entries`: Table with RTP definitions

**Description**

Walk the table pointed by **entries** (with an empty sentinel), executing the
rules. One difference from [`xe_rtp_process_to_sr()`](#c-xe_rtp_process_to_sr): there is no action
associated with each entry since this uses struct xe_rtp_entry. Its main use
is for marking active workarounds via
[`xe_rtp_process_ctx_enable_active_tracking()`](#c-xe_rtp_process_ctx_enable_active_tracking).

---

# Multi-tile Devices

_Peios Kernel / Hardware and drivers / Graphics / xe_

> Reference for Multi-tile Devices.

<a id="rst-multi-tile-devices"></a>

<!-- SPDX-License-Identifier: (GPL-2.0+ OR MIT) -->


Different vendors use the term "tile" a bit differently, but in the Intel
world, a 'tile' is pretty close to what most people would think of as being
a complete GPU.  When multiple GPUs are placed behind a single PCI device,
that's what is referred to as a "multi-tile device."  In such cases, pretty
much all hardware is replicated per-tile, although certain responsibilities
like PCI communication, reporting of interrupts to the OS, etc. are handled
solely by the "root tile."  A multi-tile platform takes care of tying the
tiles together in a way such that interrupt notifications from remote tiles
are forwarded to the root tile, the per-tile vram is combined into a single
address space, etc.

In contrast, a "GT" (which officially stands for "Graphics Technology") is
the subset of a GPU/tile that is responsible for implementing graphics
and/or media operations.  The GT is where a lot of the driver implementation
happens since it's where the hardware engines, the execution units, and the
GuC all reside.

Historically most Intel devices were single-tile devices that contained a
single GT.  PVC is an example of an Intel platform built on a multi-tile
design (i.e., multiple GPUs behind a single PCI device); each PVC tile only
has a single GT.  In contrast, platforms like MTL that have separate chips
for render and media IP are still only a single logical GPU, but the
graphics and media IP blocks are each exposed as a separate GT within that
single GPU.  This is important from a software perspective because multi-GT
platforms like MTL only replicate a subset of the GPU hardware and behave
differently than multi-tile platforms like PVC where nearly everything is
replicated.

- Per-tile functionality (shared by all GTs within the tile):
  - Complete 4MB MMIO space (containing SGunit/SoC registers, GT
    registers, display registers, etc.)
  - Global GTT
  - VRAM (if discrete)
  - Interrupt flows
  - Migration context
  - kernel batchbuffer pool
  - Primary GT
  - Media GT (if media version >= 13)

- Per-GT functionality:
  - GuC
  - Hardware engines
  - Programmable hardware units (subslices, EUs)
  - GSI subset of registers (multiple copies of these registers reside
    within the complete MMIO space provided by the tile, but at different
    offsets --- 0 for render, 0x380000 for media)
  - Multicast register steering
  - TLBs to cache page table translations
  - Reset capability
  - Low-level power management (e.g., C6)
  - Clock frequency
  - MOCS and PAT programming


<a id="rst-internal-api"></a>

## Internal API


#### <a id="c-xe_tile_alloc"></a>`xe_tile_alloc()`

```c
int xe_tile_alloc(struct xe_tile *tile)
```

Perform per-tile memory allocation

**Parameters**

- `struct xe_tile *tile`: Tile to perform allocations for

**Description**

Allocates various per-tile data structures using DRM-managed allocations.
Does not touch the hardware.

Returns -ENOMEM if allocations fail, otherwise 0.

#### <a id="c-xe_tile_alloc_vram"></a>`xe_tile_alloc_vram()`

```c
int xe_tile_alloc_vram(struct xe_tile *tile)
```

Perform per-tile VRAM structs allocation

**Parameters**

- `struct xe_tile *tile`: Tile to perform allocations for

**Description**

Allocates VRAM per-tile data structures using DRM-managed allocations.
Does not touch the hardware.

Returns -ENOMEM if allocations fail, otherwise 0.

#### <a id="c-xe_tile_init_early"></a>`xe_tile_init_early()`

```c
int xe_tile_init_early(struct xe_tile *tile, struct xe_device *xe, u8 id)
```

Initialize the tile and primary GT

**Parameters**

- `struct xe_tile *tile`: Tile to initialize
- `struct xe_device *xe`: Parent Xe device
- `u8 id`: Tile ID

**Description**

Initializes per-tile resources that don't require any interactions with the
hardware or any knowledge about the Graphics/Media IP version.

**Return**

0 on success, negative error code on error.

#### <a id="c-xe_tile_init_noalloc"></a>`xe_tile_init_noalloc()`

```c
int xe_tile_init_noalloc(struct xe_tile *tile)
```

Init tile up to the point where allocations can happen.

**Parameters**

- `struct xe_tile *tile`: The tile to initialize.

**Description**

This function prepares the tile to allow memory allocations to VRAM, but is
not allowed to allocate memory itself. This state is useful for display
readout, because the inherited display framebuffer will otherwise be
overwritten as it is usually put at the start of VRAM.

Note that since this is tile initialization, it should not perform any
GT-specific operations, and thus does not need to hold GT forcewake.

**Return**

0 on success, negative error code on error.

#### <a id="c-xe_tile_local_pagemap"></a>`xe_tile_local_pagemap()`

```c
struct drm_pagemap * xe_tile_local_pagemap(struct xe_tile *tile)
```

Return a pointer to the tile's local drm_pagemap if any

**Parameters**

- `struct xe_tile *tile`: The tile.

**Return**

A pointer to the tile's local drm_pagemap, or NULL if local pagemap
support has been compiled out.

---

# Hardware workarounds

_Peios Kernel / Hardware and drivers / Graphics / xe_

> Reference for Hardware workarounds.

<a id="rst-hardware-workarounds"></a>

<!-- SPDX-License-Identifier: (GPL-2.0+ OR MIT) -->


Hardware workarounds are register programming documented to be executed in
the driver that fall outside of the normal programming sequences for a
platform. There are some basic categories of workarounds, depending on
how/when they are applied:

- LRC workarounds: workarounds that touch registers that are
  saved/restored to/from the HW context image. The list is emitted (via Load
  Register Immediate commands) once when initializing the device and saved in
  the default context. That default context is then used on every context
  creation to have a "primed golden context", i.e. a context image that
  already contains the changes needed to all the registers. See
  drivers/gpu/drm/xe/xe_lrc.c for default context handling.

- Engine workarounds: the list of these WAs is applied whenever the specific
  engine is reset. It's also possible that a set of engine classes share a
  common power domain and they are reset together. This happens on some
  platforms with render and compute engines. In this case (at least) one of
  them need to keeep the workaround programming: the approach taken in the
  driver is to tie those workarounds to the first compute/render engine that
  is registered.  When executing with GuC submission, engine resets are
  outside of kernel driver control, hence the list of registers involved is
  written once, on engine initialization, and then passed to GuC, that
  saves/restores their values before/after the reset takes place. See
  drivers/gpu/drm/xe/xe_guc_ads.c for reference.

- GT workarounds: the list of these WAs is applied whenever these registers
  revert to their default values: on GPU reset, suspend/resume \[1\]_, etc.

- Register whitelist: some workarounds need to be implemented in userspace,
  but need to touch privileged registers. The whitelist in the kernel
  instructs the hardware to allow the access to happen. From the kernel side,
  this is just a special case of a MMIO workaround (as we write the list of
  these to/be-whitelisted registers to some special HW registers).

- Workaround batchbuffers: buffers that get executed automatically by the
  hardware on every HW context restore. These buffers are created and
  programmed in the default context so the hardware always go through those
  programming sequences when switching contexts. The support for workaround
  batchbuffers is enabled via these hardware mechanisms:

  1. INDIRECT_CTX (also known as **mid context restore bb**): A batchbuffer
     and an offset are provided in the default context, pointing the hardware
     to jump to that location when that offset is reached in the context
     restore.  When a context is being restored, this is executed after the
     ring context, in the middle (or beginning) of the engine context image.

  1. BB_PER_CTX_PTR (also known as **post context restore bb**): A
     batchbuffer is provided in the default context, pointing the hardware to
     a buffer to continue executing after the engine registers are restored
     in a context restore sequence.

  Below is the timeline for a context restore sequence:

```text
                  INDIRECT_CTX_OFFSET
             |----------->|
.------------.------------.-------------.------------.--------------.-----------.
|Ring        | Engine     | Mid-context | Engine     | Post-context | Ring      |
|Restore     | Restore (1)| BB Restore  | Restore (2)| BB Restore   | Execution |
`------------'------------'-------------'------------'--------------'-----------'
```

- Other/OOB:  There are WAs that, due to their nature, cannot be applied from
  a central place. Those are peppered around the rest of the code, as needed.
  There's a central place to control which workarounds are enabled:
  drivers/gpu/drm/xe/xe_wa_oob.rules for GT workarounds and
  drivers/gpu/drm/xe/xe_device_wa_oob.rules for device/SoC workarounds.
  These files only record which workarounds are enabled: during early device
  initialization those rules are evaluated and recorded by the driver. Then
  later the driver checks with `XE_GT_WA()` and `XE_DEVICE_WA()` to
  implement them.

> [!NOTE]
> Hardware workarounds in xe work the same way as in i915, with the
> difference of how they are maintained in the code. In xe it uses the
> xe_rtp infrastructure so the workarounds can be kept in tables, following
> a more declarative approach rather than procedural.


<a id="rst-internal-api"></a>

## Internal API


#### <a id="c-xe_wa_process_device_oob"></a>`xe_wa_process_device_oob()`

```c
void xe_wa_process_device_oob(struct xe_device *xe)
```

process OOB workaround table

**Parameters**

- `struct xe_device *xe`: device instance to process workarounds for

**Description**

process OOB workaround table for this device, marking in **xe** the
workarounds that are active.

#### <a id="c-xe_wa_process_gt_oob"></a>`xe_wa_process_gt_oob()`

```c
void xe_wa_process_gt_oob(struct xe_gt *gt)
```

process GT OOB workaround table

**Parameters**

- `struct xe_gt *gt`: GT instance to process workarounds for

**Description**

Process OOB workaround table for this platform, marking in **gt** the
workarounds that are active.

#### <a id="c-xe_wa_process_gt"></a>`xe_wa_process_gt()`

```c
void xe_wa_process_gt(struct xe_gt *gt)
```

process GT workaround table

**Parameters**

- `struct xe_gt *gt`: GT instance to process workarounds for

**Description**

Process GT workaround table for this platform, saving in **gt** all the
workarounds that need to be applied at the GT level.

#### <a id="c-xe_wa_process_engine"></a>`xe_wa_process_engine()`

```c
void xe_wa_process_engine(struct xe_hw_engine *hwe)
```

process engine workaround table

**Parameters**

- `struct xe_hw_engine *hwe`: engine instance to process workarounds for

**Description**

Process engine workaround table for this platform, saving in **hwe** all the
workarounds that need to be applied at the engine level that match this
engine.

#### <a id="c-xe_wa_process_lrc"></a>`xe_wa_process_lrc()`

```c
void xe_wa_process_lrc(struct xe_hw_engine *hwe)
```

process context workaround table

**Parameters**

- `struct xe_hw_engine *hwe`: engine instance to process workarounds for

**Description**

Process context workaround table for this platform, saving in **hwe** all the
workarounds that need to be applied on context restore. These are workarounds
touching registers that are part of the HW context image.

#### <a id="c-xe_wa_device_init"></a>`xe_wa_device_init()`

```c
int xe_wa_device_init(struct xe_device *xe)
```

initialize device with workaround oob bookkeeping

**Parameters**

- `struct xe_device *xe`: Xe device instance to initialize

**Description**

Returns 0 for success, negative with error code otherwise

#### <a id="c-xe_wa_gt_init"></a>`xe_wa_gt_init()`

```c
int xe_wa_gt_init(struct xe_gt *gt)
```

initialize gt with workaround bookkeeping

**Parameters**

- `struct xe_gt *gt`: GT instance to initialize

**Description**

Returns 0 for success, negative error code otherwise.

#### <a id="c-xe_wa_gt_dump"></a>`xe_wa_gt_dump()`

```c
int xe_wa_gt_dump(struct xe_gt *gt, struct drm_printer *p)
```

Dump GT workarounds into a drm printer.

**Parameters**

- `struct xe_gt *gt`: the `xe_gt`
- `struct drm_printer *p`: the [`drm_printer`](/kernel/hardware/gpu/drm-internals.md#c-struct-drm_printer)

**Return**

always 0.
