# Device I/O and shared memory

---

# Bus-Independent Device Accesses

_Peios Kernel / Hardware and drivers / Driver development / Device I/O and shared memory_

> Linux provides an API which abstracts performing IO across all buses and devices, allowing device drivers to be written independently of bus type.

<a id="rst-bus-independent-device-accesses"></a>

<!-- Copyright 2001 Matthew Wilcox -->

<!--  -->

<!-- This documentation is free software; you can redistribute -->

<!-- it and/or modify it under the terms of the GNU General Public -->

<!-- License as published by the Free Software Foundation; either -->

<!-- version 2 of the License, or (at your option) any later -->

<!-- version. -->

**Author:** Matthew Wilcox

**Author:** Alan Cox

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

## Introduction

Linux provides an API which abstracts performing IO across all buses and devices, allowing device drivers to be written independently of bus type.

<a id="rst-memory-mapped-io"></a>

## Memory Mapped IO

<a id="rst-getting-access-to-the-device"></a>

### Getting Access to the Device

The most widely supported form of IO is memory mapped IO. That is, a part of the CPU's address space is interpreted not as accesses to memory, but as accesses to a device. Some architectures define devices to be at a fixed address, but most have some method of discovering devices. The PCI bus walk is a good example of such a scheme. This document does not cover how to receive such an address, but assumes you are starting with one. Physical addresses are of type unsigned long.

This address should not be used directly. Instead, to get an address suitable for passing to the accessor functions described below, you should call ioremap(). An address suitable for accessing the device will be returned to you.

After you've finished using the device (say, in your module's exit routine), call iounmap() in order to return the address space to the kernel. Most architectures allocate new address space each time you call ioremap(), and they can run out unless you call iounmap().

<a id="rst-accessing-the-device"></a>

### Accessing the device

The part of the interface most used by drivers is reading and writing memory-mapped registers on the device. Linux provides interfaces to read and write 8-bit, 16-bit, 32-bit and 64-bit quantities. Due to a historical accident, these are named byte, word, long and quad accesses. Both read and write accesses are supported; there is no prefetch support at this time.

The functions are named readb(), readw(), readl(), readq(), readb_relaxed(), readw_relaxed(), readl_relaxed(), readq_relaxed(), writeb(), writew(), writel() and writeq().

Some devices (such as framebuffers) would like to use larger transfers than 8 bytes at a time. For these devices, the memcpy_toio(), memcpy_fromio() and memset_io() functions are provided. Do not use memset or memcpy on IO addresses; they are not guaranteed to copy data in order.

The read and write functions are defined to be ordered. That is the compiler is not permitted to reorder the I/O sequence. When the ordering can be compiler optimised, you can use \__readb() and friends to indicate the relaxed ordering. Use this with care.

While the basic functions are defined to be synchronous with respect to each other and ordered with respect to each other the buses the devices sit on may themselves have asynchronicity. In particular many authors are burned by the fact that PCI bus writes are posted asynchronously. A driver author must issue a read from the same device to ensure that writes have occurred in the specific cases the author cares. This kind of property cannot be hidden from driver writers in the API. In some cases, the read used to flush the device may be expected to fail (if the card is resetting, for example). In that case, the read should be done from config space, which is guaranteed to soft-fail if the card doesn't respond.

The following is an example of flushing a write to a device when the driver would like to ensure the write's effects are visible prior to continuing execution:



```text
static inline void
qla1280_disable_intrs(struct scsi_qla_host *ha)
{
    struct device_reg *reg;

    reg = ha->iobase;
    /* disable risc and host interrupts */
    WRT_REG_WORD(&reg->ictrl, 0);
    /*
     * The following read will ensure that the above write
     * has been received by the device before we return from this
     * function.
     */
    RD_REG_WORD(&reg->ictrl);
    ha->flags.ints_enabled = 0;
}
```

PCI ordering rules also guarantee that PIO read responses arrive after any outstanding DMA writes from that bus, since for some devices the result of a readb() call may signal to the driver that a DMA transaction is complete. In many cases, however, the driver may want to indicate that the next readb() call has no relation to any previous DMA writes performed by the device. The driver can use readb_relaxed() for these cases, although only some platforms will honor the relaxed semantics. Using the relaxed read functions will provide significant performance benefits on platforms that support it. The qla2xxx driver provides examples of how to use readX_relaxed(). In many cases, a majority of the driver's readX() calls can safely be converted to readX_relaxed() calls, since only a few will indicate or depend on DMA completion.

<a id="rst-port-space-accesses"></a>

## Port Space Accesses

<a id="rst-port-space-explained"></a>

### Port Space Explained

Another form of IO commonly supported is Port Space. This is a range of addresses separate to the normal memory address space. Access to these addresses is generally not as fast as accesses to the memory mapped addresses, and it also has a potentially smaller address space.

Unlike memory mapped IO, no preparation is required to access port space.

<a id="rst-accessing-port-space"></a>

### Accessing Port Space

Accesses to this space are provided through a set of functions which allow 8-bit, 16-bit and 32-bit accesses; also known as byte, word and long. These functions are inb(), inw(), inl(), outb(), outw() and outl().

Some variants are provided for these functions. Some devices require that accesses to their ports are slowed down. This functionality is provided by appending a `_p` to the end of the function. There are also equivalents to memcpy. The ins() and outs() functions copy bytes, words or longs to the given port.

<a id="rst-iomem-pointer-tokens"></a>

## \__iomem pointer tokens

The data type for an MMIO address is an `__iomem` qualified pointer, such as `void __iomem *reg`. On most architectures it is a regular pointer that points to a virtual memory address and can be offset or dereferenced, but in portable code, it must only be passed from and to functions that explicitly operated on an `__iomem` token, in particular the ioremap() and readl()/writel() functions. The 'sparse' semantic code checker can be used to verify that this is done correctly.

While on most architectures, ioremap() creates a page table entry for an uncached virtual address pointing to the physical MMIO address, some architectures require special instructions for MMIO, and the `__iomem` pointer just encodes the physical address or an offsettable cookie that is interpreted by readl()/writel().

<a id="rst-differences-between-i-o-access-functions"></a>

## Differences between I/O access functions

readq(), readl(), readw(), readb(), writeq(), writel(), writew(), writeb()

> These are the most generic accessors, providing serialization against other MMIO accesses and DMA accesses as well as fixed endianness for accessing little-endian PCI devices and on-chip peripherals. Portable device drivers should generally use these for any access to `__iomem` pointers.
>
> Note that posted writes are not strictly ordered against a spinlock, see [Documentation/driver-api/io_ordering.rst](/kernel/hardware/driver-api/io-and-dma/io-ordering.md).

readq_relaxed(), readl_relaxed(), readw_relaxed(), readb_relaxed(), writeq_relaxed(), writel_relaxed(), writew_relaxed(), writeb_relaxed()

> On architectures that require an expensive barrier for serializing against DMA, these "relaxed" versions of the MMIO accessors only serialize against each other, but contain a less expensive barrier operation. A device driver might use these in a particularly performance sensitive fast path, with a comment that explains why the usage in a specific location is safe without the extra barriers.
>
> See memory-barriers.txt for a more detailed discussion on the precise ordering guarantees of the non-relaxed and relaxed versions.

ioread64(), ioread32(), ioread16(), ioread8(), iowrite64(), iowrite32(), iowrite16(), iowrite8()

> These are an alternative to the normal readl()/writel() functions, with almost identical behavior, but they can also operate on `__iomem` tokens returned for mapping PCI I/O space with pci_iomap() or ioport_map(). On architectures that require special instructions for I/O port access, this adds a small overhead for an indirect function call implemented in lib/iomap.c, while on other architectures, these are simply aliases.

ioread64be(), ioread32be(), ioread16be() iowrite64be(), iowrite32be(), iowrite16be()

> These behave in the same way as the ioread32()/iowrite32() family, but with reversed byte order, for accessing devices with big-endian MMIO registers. Device drivers that can operate on either big-endian or little-endian registers may have to implement a custom wrapper function that picks one or the other depending on which device was found.
>
> Note: On some architectures, the normal readl()/writel() functions traditionally assume that devices are the same endianness as the CPU, while using a hardware byte-reverse on the PCI bus when running a big-endian kernel. Drivers that use readl()/writel() this way are generally not portable, but tend to be limited to a particular SoC.

hi_lo_readq(), lo_hi_readq(), hi_lo_readq_relaxed(), lo_hi_readq_relaxed(), ioread64_lo_hi(), ioread64_hi_lo(), ioread64be_lo_hi(), ioread64be_hi_lo(), hi_lo_writeq(), lo_hi_writeq(), hi_lo_writeq_relaxed(), lo_hi_writeq_relaxed(), iowrite64_lo_hi(), iowrite64_hi_lo(), iowrite64be_lo_hi(), iowrite64be_hi_lo()

> Some device drivers have 64-bit registers that cannot be accessed atomically on 32-bit architectures but allow two consecutive 32-bit accesses instead. Since it depends on the particular device which of the two halves has to be accessed first, a helper is provided for each combination of 64-bit accessors with either low/high or high/low word ordering. A device driver must include either &lt;linux/io-64-nonatomic-lo-hi.h&gt; or &lt;linux/io-64-nonatomic-hi-lo.h&gt; to get the function definitions along with helpers that redirect the normal readq()/writeq() to them on architectures that do not provide 64-bit access natively.

\__raw_readq(), \__raw_readl(), \__raw_readw(), \__raw_readb(), \__raw_writeq(), \__raw_writel(), \__raw_writew(), \__raw_writeb()

> These are low-level MMIO accessors without barriers or byteorder changes and architecture specific behavior. Accesses are usually atomic in the sense that a four-byte \__raw_readl() does not get split into individual byte loads, but multiple consecutive accesses can be combined on the bus. In portable code, it is only safe to use these to access memory behind a device bus but not MMIO registers, as there are no ordering guarantees with regard to other MMIO accesses or even spinlocks. The byte order is generally the same as for normal memory, so unlike the other functions, these can be used to copy data between kernel memory and device memory.

inl(), inw(), inb(), outl(), outw(), outb()

> PCI I/O port resources traditionally require separate helpers as they are implemented using special instructions on the x86 architecture. On most other architectures, these are mapped to readl()/writel() style accessors internally, usually pointing to a fixed area in virtual memory. Instead of an `__iomem` pointer, the address is a 32-bit integer token to identify a port number. PCI requires I/O port access to be non-posted, meaning that an outb() must complete before the following code executes, while a normal writeb() may still be in progress. On architectures that correctly implement this, I/O port access is therefore ordered against spinlocks. Many non-x86 PCI host bridge implementations and CPU architectures however fail to implement non-posted I/O space on PCI, so they can end up being posted on such hardware.
>
> In some architectures, the I/O port number space has a 1:1 mapping to `__iomem` pointers, but this is not recommended and device drivers should not rely on that for portability. Similarly, an I/O port number as described in a PCI base address register may not correspond to the port number as seen by a device driver. Portable drivers need to read the port number for the resource provided by the kernel.
>
> There are no direct 64-bit I/O port accessors, but pci_iomap() in combination with ioread64/iowrite64 can be used instead.

inl_p(), inw_p(), inb_p(), outl_p(), outw_p(), outb_p()

> On ISA devices that require specific timing, the \_p versions of the I/O accessors add a small delay. On architectures that do not have ISA buses, these are aliases to the normal inb/outb helpers.

readsq, readsl, readsw, readsb writesq, writesl, writesw, writesb ioread64_rep, ioread32_rep, ioread16_rep, ioread8_rep iowrite64_rep, iowrite32_rep, iowrite16_rep, iowrite8_rep insl, insw, insb, outsl, outsw, outsb

> These are helpers that access the same address multiple times, usually to copy data between kernel memory byte stream and a FIFO buffer. Unlike the normal MMIO accessors, these do not perform a byteswap on big-endian kernels, so the first byte in the FIFO register corresponds to the first byte in the memory buffer regardless of the architecture.

<a id="rst-device-memory-mapping-modes"></a>

## Device memory mapping modes

Some architectures support multiple modes for mapping device memory. ioremap\_\*() variants provide a common abstraction around these architecture-specific modes, with a shared set of semantics.

ioremap() is the most common mapping type, and is applicable to typical device memory (e.g. I/O registers). Other modes can offer weaker or stronger guarantees, if supported by the architecture. From most to least common, they are as follows:

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

### ioremap()

The default mode, suitable for most memory-mapped devices, e.g. control registers. Memory mapped using ioremap() has the following characteristics:

- Uncached - CPU-side caches are bypassed, and all reads and writes are handled directly by the device

- No speculative operations - the CPU may not issue a read or write to this memory, unless the instruction that does so has been reached in committed program flow.

- No reordering - The CPU may not reorder accesses to this memory mapping with respect to each other. On some architectures, this relies on barriers in readl_relaxed()/writel_relaxed().

- No repetition - The CPU may not issue multiple reads or writes for a single program instruction.

- No write-combining - Each I/O operation results in one discrete read or write being issued to the device, and multiple writes are not combined into larger writes. This may or may not be enforced when using \__raw I/O accessors or pointer dereferences.

- Non-executable - The CPU is not allowed to speculate instruction execution from this memory (it probably goes without saying, but you're also not allowed to jump into device memory).

On many platforms and buses (e.g. PCI), writes issued through ioremap() mappings are posted, which means that the CPU does not wait for the write to actually reach the target device before retiring the write instruction.

On many platforms, I/O accesses must be aligned with respect to the access size; failure to do so will result in an exception or unpredictable results.

<a id="rst-ioremap-wc"></a>

### ioremap_wc()

Maps I/O memory as normal memory with write combining. Unlike ioremap(),

- The CPU may speculatively issue reads from the device that the program didn't actually execute, and may choose to basically read whatever it wants.

- The CPU may reorder operations as long as the result is consistent from the program's point of view.

- The CPU may write to the same location multiple times, even when the program issued a single write.

- The CPU may combine several writes into a single larger write.

This mode is typically used for video framebuffers, where it can increase performance of writes. It can also be used for other blocks of memory in devices (e.g. buffers or shared memory), but care must be taken as accesses are not guaranteed to be ordered with respect to normal ioremap() MMIO register accesses without explicit barriers.

On a PCI bus, it is usually safe to use ioremap_wc() on MMIO areas marked as `IORESOURCE_PREFETCH`, but it may not be used on those without the flag. For on-chip devices, there is no corresponding flag, but a driver can use ioremap_wc() on a device that is known to be safe.

<a id="rst-ioremap-wt"></a>

### ioremap_wt()

Maps I/O memory as normal memory with write-through caching. Like ioremap_wc(), but also,

- The CPU may cache writes issued to and reads from the device, and serve reads from that cache.

This mode is sometimes used for video framebuffers, where drivers still expect writes to reach the device in a timely manner (and not be stuck in the CPU cache), but reads may be served from the cache for efficiency. However, it is rarely useful these days, as framebuffer drivers usually perform writes only, for which ioremap_wc() is more efficient (as it doesn't needlessly trash the cache). Most drivers should not use this.

<a id="rst-ioremap-np"></a>

### ioremap_np()

Like ioremap(), but explicitly requests non-posted write semantics. On some architectures and buses, ioremap() mappings have posted write semantics, which means that writes can appear to "complete" from the point of view of the CPU before the written data actually arrives at the target device. Writes are still ordered with respect to other writes and reads from the same device, but due to the posted write semantics, this is not the case with respect to other devices. ioremap_np() explicitly requests non-posted semantics, which means that the write instruction will not appear to complete until the device has received (and to some platform-specific extent acknowledged) the written data.

This mapping mode primarily exists to cater for platforms with bus fabrics that require this particular mapping mode to work correctly. These platforms set the `IORESOURCE_MEM_NONPOSTED` flag for a resource that requires ioremap_np() semantics and portable drivers should use an abstraction that automatically selects it where appropriate (see the [Higher-level ioremap abstractions](<#rst-higher-level-ioremap-abstractions>) section below).

The bare ioremap_np() is only available on some architectures; on others, it always returns NULL. Drivers should not normally use it, unless they are platform-specific or they derive benefit from non-posted writes where supported, and can fall back to ioremap() otherwise. The normal approach to ensure posted write completion is to do a dummy read after a write as explained in [Accessing the device](<#rst-accessing-the-device>), which works with ioremap() on all platforms.

ioremap_np() should never be used for PCI drivers. PCI memory space writes are always posted, even on architectures that otherwise implement ioremap_np(). Using ioremap_np() for PCI BARs will at best result in posted write semantics, and at worst result in complete breakage.

Note that non-posted write semantics are orthogonal to CPU-side ordering guarantees. A CPU may still choose to issue other reads or writes before a non-posted write instruction retires. See the previous section on MMIO access functions for details on the CPU side of things.

<a id="rst-ioremap-uc"></a>

### ioremap_uc()

ioremap_uc() is only meaningful on old x86-32 systems with the PAT extension, and on ia64 with its slightly unconventional ioremap() behavior, everywhere elss ioremap_uc() defaults to return NULL.

Portable drivers should avoid the use of ioremap_uc(), use ioremap() instead.

<a id="rst-ioremap-cache"></a>

### ioremap_cache()

ioremap_cache() effectively maps I/O memory as normal RAM. CPU write-back caches can be used, and the CPU is free to treat the device as if it were a block of RAM. This should never be used for device memory which has side effects of any kind, or which does not return the data previously written on read.

It should also not be used for actual RAM, as the returned pointer is an `__iomem` token. memremap() can be used for mapping normal RAM that is outside of the linear kernel memory area to a regular pointer.

Portable drivers should avoid the use of ioremap_cache().

<a id="rst-architecture-example"></a>

### Architecture example

Here is how the above modes map to memory attribute settings on the ARM64 architecture:


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


API

</td>
<td>


Memory region type and cacheability

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


ioremap_np()

</td>
<td>


Device-nGnRnE

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


ioremap()

</td>
<td>


Device-nGnRE

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


ioremap_uc()

</td>
<td>


(not implemented)

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


ioremap_wc()

</td>
<td>


Normal-Non Cacheable

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


ioremap_wt()

</td>
<td>


(not implemented; fallback to ioremap)

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


ioremap_cache()

</td>
<td>


Normal-Write-Back Cacheable

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

<a id="rst-higher-level-ioremap-abstractions"></a>

## Higher-level ioremap abstractions

Instead of using the above raw ioremap() modes, drivers are encouraged to use higher-level APIs. These APIs may implement platform-specific logic to automatically choose an appropriate ioremap mode on any given bus, allowing for a platform-agnostic driver to work on those platforms without any special cases. At the time of this writing, the following ioremap() wrappers have such logic:

devm_ioremap_resource()

> Can automatically select ioremap_np() over ioremap() according to platform requirements, if the `IORESOURCE_MEM_NONPOSTED` flag is set on the struct resource. Uses devres to automatically unmap the resource when the driver probe() function fails or a device in unbound from its driver.
>
> Documented in [Documentation/driver-api/driver-model/devres.rst](/kernel/hardware/driver-api/driver-model/devres.md).

of_address_to_resource()

> Automatically sets the `IORESOURCE_MEM_NONPOSTED` flag for platforms that require non-posted writes for certain buses (see the nonposted-mmio and posted-mmio device tree properties).

of_iomap()

> Maps the resource described in a `reg` property in the device tree, doing all required translations. Automatically selects ioremap_np() according to platform requirements, as above.

pci_ioremap_bar(), pci_ioremap_wc_bar()

> Maps the resource described in a PCI base address without having to extract the physical address first.

pci_iomap(), pci_iomap_wc()

> Like pci_ioremap_bar()/pci_ioremap_bar(), but also works on I/O space when used together with ioread32()/iowrite32() and similar accessors

pcim_iomap()

> Like pci_iomap(), but uses devres to automatically unmap the resource when the driver probe() function fails or a device in unbound from its driver
>
> Documented in [Documentation/driver-api/driver-model/devres.rst](/kernel/hardware/driver-api/driver-model/devres.md).

Not using these wrappers may make drivers unusable on certain platforms with stricter rules for mapping I/O memory.

<a id="rst-generalizing-access-to-system-and-i-o-memory"></a>

## Generalizing Access to System and I/O Memory


When accessing a memory region, depending on its location, users may have to
access it with I/O operations or memory load/store operations. For example,
copying to system memory could be done with [`memcpy()`](/kernel/internals/core-api/kernel-api.md#c-memcpy), copying to I/O memory
would be done with `memcpy_toio()`.

```c
void *vaddr = ...; // pointer to system memory
memcpy(vaddr, src, len);

void *vaddr_iomem = ...; // pointer to I/O memory
memcpy_toio(vaddr_iomem, src, len);
```

The user of such pointer may not have information about the mapping of that
region or may want to have a single code path to handle operations on that
buffer, regardless if it's located in system or IO memory. The type
[`struct iosys_map`](#c-struct-iosys_map) and its helpers abstract that so the
buffer can be passed around to other drivers or have separate duties inside
the same driver for allocation, read and write operations.

Open-coding access to [`struct iosys_map`](#c-struct-iosys_map) is considered
bad style. Rather than accessing its fields directly, use one of the provided
helper functions, or implement your own. For example, instances of
[`struct iosys_map`](#c-struct-iosys_map) can be initialized statically with
[`IOSYS_MAP_INIT_VADDR()`](#c-IOSYS_MAP_INIT_VADDR), or at runtime with [`iosys_map_set_vaddr()`](#c-iosys_map_set_vaddr). These
helpers will set an address in system memory.

```c
struct iosys_map map = IOSYS_MAP_INIT_VADDR(0xdeadbeaf);

iosys_map_set_vaddr(&map, 0xdeadbeaf);
```

To set an address in I/O memory, use [`IOSYS_MAP_INIT_VADDR_IOMEM()`](#c-IOSYS_MAP_INIT_VADDR_IOMEM) or
[`iosys_map_set_vaddr_iomem()`](#c-iosys_map_set_vaddr_iomem).

```c
struct iosys_map map = IOSYS_MAP_INIT_VADDR_IOMEM(0xdeadbeaf);

iosys_map_set_vaddr_iomem(&map, 0xdeadbeaf);
```

Instances of struct iosys_map do not have to be cleaned up, but
can be cleared to NULL with [`iosys_map_clear()`](#c-iosys_map_clear). Cleared mappings
always refer to system memory.

```c
iosys_map_clear(&map);
```

Test if a mapping is valid with either [`iosys_map_is_set()`](#c-iosys_map_is_set) or
[`iosys_map_is_null()`](#c-iosys_map_is_null).

```c
if (iosys_map_is_set(&map) != iosys_map_is_null(&map))
        // always true
```

Instances of [`struct iosys_map`](#c-struct-iosys_map) can be compared for
equality with [`iosys_map_is_equal()`](#c-iosys_map_is_equal). Mappings that point to different memory
spaces, system or I/O, are never equal. That's even true if both spaces are
located in the same address space, both mappings contain the same address
value, or both mappings refer to NULL.

```c
struct iosys_map sys_map; // refers to system memory
struct iosys_map io_map; // refers to I/O memory

if (iosys_map_is_equal(&sys_map, &io_map))
        // always false
```

A set up instance of struct iosys_map can be used to access or manipulate the
buffer memory. Depending on the location of the memory, the provided helpers
will pick the correct operations. Data can be copied into the memory with
[`iosys_map_memcpy_to()`](#c-iosys_map_memcpy_to). The address can be manipulated with [`iosys_map_incr()`](#c-iosys_map_incr).

```c
const void *src = ...; // source buffer
size_t len = ...; // length of src

iosys_map_memcpy_to(&map, src, len);
iosys_map_incr(&map, len); // go to first byte after the memcpy
```



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

Pointer to IO/system memory

**Definition**

```c
struct iosys_map {
    union {
        void __iomem *vaddr_iomem;
        void *vaddr;
    };
    bool is_iomem;
};
```

**Members**

- `{unnamed_union}`: anonymous
- `vaddr_iomem`: The buffer's address if in I/O memory
- `vaddr`: The buffer's address if in system memory
- `is_iomem`: True if the buffer is located in I/O memory, or false
  otherwise.

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

```c
IOSYS_MAP_INIT_VADDR(vaddr_)
```

Initializes struct iosys_map to an address in system memory

**Parameters**

- `vaddr_`: A system-memory address

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

```c
IOSYS_MAP_INIT_VADDR_IOMEM(vaddr_iomem_)
```

Initializes struct iosys_map to an address in I/O memory

**Parameters**

- `vaddr_iomem_`: An I/O-memory address

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

```c
IOSYS_MAP_INIT_OFFSET(map_, offset_)
```

Initializes struct iosys_map from another iosys_map

**Parameters**

- `map_`: The dma-buf mapping structure to copy from
- `offset_`: Offset to add to the other mapping

**Description**

Initializes a new iosys_map struct based on another passed as argument. It
does a shallow copy of the struct so it's possible to update the back storage
without changing where the original map points to. It is the equivalent of
doing:

```c
iosys_map map = other_map;
iosys_map_incr(&map, &offset);
```

Example usage:

```c
void foo(struct device *dev, struct iosys_map *base_map)
{
        ...
        struct iosys_map map = IOSYS_MAP_INIT_OFFSET(base_map, FIELD_OFFSET);
        ...
}
```

The advantage of using the initializer over just increasing the offset with
[`iosys_map_incr()`](#c-iosys_map_incr) like above is that the new map will always point to the
right place of the buffer during its scope. It reduces the risk of updating
the wrong part of the buffer and having no compiler warning about that. If
the assignment to [`IOSYS_MAP_INIT_OFFSET()`](#c-IOSYS_MAP_INIT_OFFSET) is forgotten, the compiler can warn
about the use of uninitialized variable.

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

```c
void iosys_map_set_vaddr(struct iosys_map *map, void *vaddr)
```

Sets a iosys mapping structure to an address in system memory

**Parameters**

- `struct iosys_map *map`: The iosys_map structure
- `void *vaddr`: A system-memory address

**Description**

Sets the address and clears the I/O-memory flag.

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

```c
void iosys_map_set_vaddr_iomem(struct iosys_map *map, void __iomem *vaddr_iomem)
```

Sets a iosys mapping structure to an address in I/O memory

**Parameters**

- `struct iosys_map *map`: The iosys_map structure
- `void __iomem *vaddr_iomem`: An I/O-memory address

**Description**

Sets the address and the I/O-memory flag.

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

```c
bool iosys_map_is_equal(const struct iosys_map *lhs, const struct iosys_map *rhs)
```

Compares two iosys mapping structures for equality

**Parameters**

- `const struct iosys_map *lhs`: The iosys_map structure
- `const struct iosys_map *rhs`: A iosys_map structure to compare with

**Description**

Two iosys mapping structures are equal if they both refer to the same type of memory
and to the same address within that memory.

**Return**

True is both structures are equal, or false otherwise.

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

```c
bool iosys_map_is_null(const struct iosys_map *map)
```

Tests for a iosys mapping to be NULL

**Parameters**

- `const struct iosys_map *map`: The iosys_map structure

**Description**

Depending on the state of struct iosys_map.is_iomem, tests if the
mapping is NULL.

**Return**

True if the mapping is NULL, or false otherwise.

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

```c
bool iosys_map_is_set(const struct iosys_map *map)
```

Tests if the iosys mapping has been set

**Parameters**

- `const struct iosys_map *map`: The iosys_map structure

**Description**

Depending on the state of struct iosys_map.is_iomem, tests if the
mapping has been set.

**Return**

True if the mapping is been set, or false otherwise.

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

```c
void iosys_map_clear(struct iosys_map *map)
```

Clears a iosys mapping structure

**Parameters**

- `struct iosys_map *map`: The iosys_map structure

**Description**

Clears all fields to zero, including struct iosys_map.is_iomem, so
mapping structures that were set to point to I/O memory are reset for
system memory. Pointers are cleared to NULL. This is the default.

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

```c
void iosys_map_memcpy_to(struct iosys_map *dst, size_t dst_offset, const void *src, size_t len)
```

Memcpy into offset of iosys_map

**Parameters**

- `struct iosys_map *dst`: The iosys_map structure
- `size_t dst_offset`: The offset from which to copy
- `const void *src`: The source buffer
- `size_t len`: The number of byte in src

**Description**

Copies data into a iosys_map with an offset. The source buffer is in
system memory. Depending on the buffer's location, the helper picks the
correct method of accessing the memory.

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

```c
void iosys_map_memcpy_from(void *dst, const struct iosys_map *src, size_t src_offset, size_t len)
```

Memcpy from iosys_map into system memory

**Parameters**

- `void *dst`: Destination in system memory
- `const struct iosys_map *src`: The iosys_map structure
- `size_t src_offset`: The offset from which to copy
- `size_t len`: The number of byte in src

**Description**

Copies data from a iosys_map with an offset. The dest buffer is in
system memory. Depending on the mapping location, the helper picks the
correct method of accessing the memory.

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

```c
void iosys_map_incr(struct iosys_map *map, size_t incr)
```

Increments the address stored in a iosys mapping

**Parameters**

- `struct iosys_map *map`: The iosys_map structure
- `size_t incr`: The number of bytes to increment

**Description**

Increments the address stored in a iosys mapping. Depending on the
buffer's location, the correct value will be updated.

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

```c
void iosys_map_memset(struct iosys_map *dst, size_t offset, int value, size_t len)
```

Memset iosys_map

**Parameters**

- `struct iosys_map *dst`: The iosys_map structure
- `size_t offset`: Offset from dst where to start setting value
- `int value`: The value to set
- `size_t len`: The number of bytes to set in dst

**Description**

Set value in iosys_map. Depending on the buffer's location, the helper
picks the correct method of accessing the memory.

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

```c
iosys_map_rd(map__, offset__, type__)
```

Read a C-type value from the iosys_map

**Parameters**

- `map__`: The iosys_map structure
- `offset__`: The offset from which to read
- `type__`: Type of the value being read

**Description**

Read a C type value (u8, u16, u32 and u64) from iosys_map. For other types or
if pointer may be unaligned (and problematic for the architecture supported),
use [`iosys_map_memcpy_from()`](#c-iosys_map_memcpy_from).

**Return**

The value read from the mapping.

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

```c
iosys_map_wr(map__, offset__, type__, val__)
```

Write a C-type value to the iosys_map

**Parameters**

- `map__`: The iosys_map structure
- `offset__`: The offset from the mapping to write to
- `type__`: Type of the value being written
- `val__`: Value to write

**Description**

Write a C type value (u8, u16, u32 and u64) to the iosys_map. For other types
or if pointer may be unaligned (and problematic for the architecture
supported), use [`iosys_map_memcpy_to()`](#c-iosys_map_memcpy_to)

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

```c
iosys_map_rd_field(map__, struct_offset__, struct_type__, field__)
```

Read a member from a struct in the iosys_map

**Parameters**

- `map__`: The iosys_map structure
- `struct_offset__`: Offset from the beginning of the map, where the struct
  is located
- `struct_type__`: The struct describing the layout of the mapping
- `field__`: Member of the struct to read

**Description**

Read a value from iosys_map considering its layout is described by a C struct
starting at **struct_offset__**. The field offset and size is calculated and its
value read. If the field access would incur in un-aligned access, then either
[`iosys_map_memcpy_from()`](#c-iosys_map_memcpy_from) needs to be used or the architecture must support it.
For example: suppose there is a **struct** foo defined as below and the value
`foo.field2.inner2` needs to be read from the iosys_map:

```c
struct foo {
        int field1;
        struct {
                int inner1;
                int inner2;
        } field2;
        int field3;
} __packed;
```

This is the expected memory layout of a buffer using [`iosys_map_rd_field()`](#c-iosys_map_rd_field):

```text
+------------------------------+--------------------------+
| Address                      | Content                  |
+==============================+==========================+
| buffer + 0000                | start of mmapped buffer  |
|                              | pointed by iosys_map     |
+------------------------------+--------------------------+
| ...                          | ...                      |
+------------------------------+--------------------------+
| buffer + ``struct_offset__`` | start of ``struct foo``  |
+------------------------------+--------------------------+
| ...                          | ...                      |
+------------------------------+--------------------------+
| buffer + wwww                | ``foo.field2.inner2``    |
+------------------------------+--------------------------+
| ...                          | ...                      |
+------------------------------+--------------------------+
| buffer + yyyy                | end of ``struct foo``    |
+------------------------------+--------------------------+
| ...                          | ...                      |
+------------------------------+--------------------------+
| buffer + zzzz                | end of mmaped buffer     |
+------------------------------+--------------------------+
```

Values automatically calculated by this macro or not needed are denoted by
wwww, yyyy and zzzz. This is the code to read that value:

```c
x = iosys_map_rd_field(&map, offset, struct foo, field2.inner2);
```

**Return**

The value read from the mapping.

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

```c
iosys_map_wr_field(map__, struct_offset__, struct_type__, field__, val__)
```

Write to a member of a struct in the iosys_map

**Parameters**

- `map__`: The iosys_map structure
- `struct_offset__`: Offset from the beginning of the map, where the struct
  is located
- `struct_type__`: The struct describing the layout of the mapping
- `field__`: Member of the struct to read
- `val__`: Value to write

**Description**

Write a value to the iosys_map considering its layout is described by a C
struct starting at **struct_offset__**. The field offset and size is calculated
and the **val__** is written. If the field access would incur in un-aligned
access, then either [`iosys_map_memcpy_to()`](#c-iosys_map_memcpy_to) needs to be used or the
architecture must support it. Refer to [`iosys_map_rd_field()`](#c-iosys_map_rd_field) for expected
usage and memory layout.


<a id="rst-public-functions-provided"></a>

## Public Functions Provided


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

```c
phys_addr_t virt_to_phys(volatile void *address)
```

map virtual addresses to physical

**Parameters**

- `volatile void *address`: address to remap

**Description**

The returned physical address is the physical (CPU) mapping for
the memory address given. It is only valid to use this function on
addresses directly mapped or allocated via kmalloc.

This function does not give bus mappings for DMA transfers. In
almost all conceivable cases a device driver should not be using
this function

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

```c
void * phys_to_virt(phys_addr_t address)
```

map physical address to virtual

**Parameters**

- `phys_addr_t address`: address to remap

**Description**

The returned virtual address is a current CPU mapping for
the memory address given. It is only valid to use this function on
addresses that have a kernel mapping

This function does not handle bus mappings for DMA transfers. In
almost all conceivable cases a device driver should not be using
this function

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

```c
void __iomem * ioremap(resource_size_t offset, unsigned long size)
```

map bus memory into CPU space

**Parameters**

- `resource_size_t offset`: bus address of the memory
- `unsigned long size`: size of the resource to map

**Description**

ioremap performs a platform specific sequence of operations to
make bus memory CPU accessible via the readb/readw/readl/writeb/
writew/writel functions and the other mmio helpers. The returned
address is not guaranteed to be usable directly as a virtual
address.

If the area you are trying to map is a PCI BAR you should have a
look at [`pci_iomap()`](/kernel/hardware/driver-api/pci/pci.md#c-pci_iomap).

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

```c
void iosubmit_cmds512(void __iomem *dst, const void *src, size_t count)
```

copy data to single MMIO location, in 512-bit units

**Parameters**

- `void __iomem *dst`: destination, in MMIO space (must be 512-bit aligned)
- `const void *src`: source
- `size_t count`: number of 512 bits quantities to submit

**Description**

Submit data from kernel space to MMIO space, in units of 512 bits at a
time.  Order of access is not guaranteed, nor is a memory barrier
performed afterwards.

Warning: Do not use this helper unless your driver has checked that the CPU
instruction is supported on the platform.

---

# Buffer Sharing and Synchronization (dma-buf)

_Peios Kernel / Hardware and drivers / Driver development / Device I/O and shared memory_

> The dma-buf subsystem provides the framework for sharing buffers for hardware (DMA) access across multiple device drivers and subsystems, and for synchronizing asynchronous hardware access.

<a id="rst-buffer-sharing-and-synchronization-dma-buf"></a>

The dma-buf subsystem provides the framework for sharing buffers for hardware (DMA) access across multiple device drivers and subsystems, and for synchronizing asynchronous hardware access.

As an example, it is used extensively by the DRM subsystem to exchange buffers between processes, contexts, library APIs within the same process, and also to exchange buffers with other subsystems such as V4L2.

This document describes the way in which kernel subsystems can use and interact with the three main primitives offered by dma-buf:

> - dma-buf, representing a sg_table and exposed to userspace as a file descriptor to allow passing between processes, subsystems, devices, etc;
>
> - dma-fence, providing a mechanism to signal when an asynchronous hardware operation has completed; and
>
> - dma-resv, which manages a set of dma-fences for a particular dma-buf allowing implicit (kernel-ordered) synchronization of work to preserve the illusion of coherent access

<a id="rst-userspace-api-principles-and-use"></a>

## Userspace API principles and use

For more details on how to design your subsystem's API for dma-buf use, 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).

<a id="rst-shared-dma-buffers"></a>

## Shared DMA Buffers

This document serves as a guide to device-driver writers on what is the dma-buf buffer sharing API, how to use it for exporting and using shared buffers.

Any device driver which wishes to be a part of DMA buffer sharing, can do so as either the 'exporter' of buffers, or the 'user' or 'importer' of buffers.

Say a driver A wants to use buffers created by driver B, then we call B as the exporter, and A as buffer-user/importer.

The exporter

> - implements and manages operations in `struct dma_buf_ops <dma_buf_ops>` for the buffer,
>
> - allows other users to share the buffer by using dma_buf sharing APIs,
>
> - manages the details of buffer allocation, wrapped in a `struct dma_buf <dma_buf>`,
>
> - decides about the actual backing storage where this allocation happens,
>
> - and takes care of any migration of scatterlist - for all (shared) users of this buffer.

The buffer-user

> - is one of (many) sharing users of the buffer.
>
> - doesn't need to worry about how the buffer is allocated, or where.
>
> - and needs a mechanism to get access to the scatterlist that makes up this buffer in memory, mapped into its own address space, so it can access the same area of memory. This interface is provided by `struct dma_buf_attachment <dma_buf_attachment>`.

Any exporters or users of the dma-buf buffer sharing framework must have a 'select DMA_SHARED_BUFFER' in their respective Kconfigs.

<a id="rst-userspace-interface-notes"></a>

### Userspace Interface Notes

Mostly a DMA buffer file descriptor is simply an opaque object for userspace, and hence the generic interface exposed is very minimal. There's a few things to consider though:

- Since kernel 3.12 the dma-buf FD supports the llseek system call, but only with offset=0 and whence=SEEK_END\|SEEK_SET. SEEK_SET is supported to allow the usual size discover pattern size = SEEK_END(0); SEEK_SET(0). Every other llseek operation will report -EINVAL.

  If llseek on dma-buf FDs isn't supported the kernel will report -ESPIPE for all cases. Userspace can use this to detect support for discovering the dma-buf size using llseek.

- In order to avoid fd leaks on exec, the FD_CLOEXEC flag must be set on the file descriptor.  This is not just a resource leak, but a potential security hole.  It could give the newly exec'd application access to buffers, via the leaked fd, to which it should otherwise not be permitted access.

  The problem with doing this via a separate fcntl() call, versus doing it atomically when the fd is created, is that this is inherently racy in a multi-threaded app\[3\].  The issue is made worse when it is library code opening/creating the file descriptor, as the application may not even be aware of the fd's.

  To avoid this problem, userspace must have a way to request O_CLOEXEC flag be set when the dma-buf fd is created.  So any API provided by the exporting driver to create a dmabuf fd must provide a way to let userspace control setting of O_CLOEXEC flag passed in to dma_buf_fd().

- Memory mapping the contents of the DMA buffer is also supported. See the discussion below on [CPU Access to DMA Buffer Objects](<#rst-cpu-access-to-dma-buffer-objects>) for the full details.

- The DMA buffer FD is also pollable, see [Implicit Fence Poll Support](<#rst-implicit-fence-poll-support>) below for details.

- The DMA buffer FD also supports a few dma-buf-specific ioctls, see [DMA Buffer ioctls](<#rst-dma-buffer-ioctls>) below for details.

<a id="rst-basic-operation-and-device-dma-access"></a>

### Basic Operation and Device DMA Access


For device DMA access to a shared DMA buffer the usual sequence of operations
is fairly simple:

1. The exporter defines his exporter instance using
   [`DEFINE_DMA_BUF_EXPORT_INFO()`](#c-DEFINE_DMA_BUF_EXPORT_INFO) and calls [`dma_buf_export()`](#c-dma_buf_export) to wrap a private
   buffer object into a [`dma_buf`](#c-struct-dma_buf). It then exports that [`dma_buf`](#c-struct-dma_buf) to userspace
   as a file descriptor by calling [`dma_buf_fd()`](#c-dma_buf_fd).

2. Userspace passes this file-descriptors to all drivers it wants this buffer
   to share with: First the file descriptor is converted to a [`dma_buf`](#c-struct-dma_buf) using
   [`dma_buf_get()`](#c-dma_buf_get). Then the buffer is attached to the device using
   [`dma_buf_attach()`](#c-dma_buf_attach).

   Up to this stage the exporter is still free to migrate or reallocate the
   backing storage.

3. Once the buffer is attached to all devices userspace can initiate DMA
   access to the shared buffer. In the kernel this is done by calling
   [`dma_buf_map_attachment()`](#c-dma_buf_map_attachment) and [`dma_buf_unmap_attachment()`](#c-dma_buf_unmap_attachment).

4. Once a driver is done with a shared buffer it needs to call
   [`dma_buf_detach()`](#c-dma_buf_detach) (after cleaning up any mappings) and then release the
   reference acquired with [`dma_buf_get()`](#c-dma_buf_get) by calling [`dma_buf_put()`](#c-dma_buf_put).

For the detailed semantics exporters are expected to implement see
[`dma_buf_ops`](#c-struct-dma_buf_ops).


<a id="rst-cpu-access-to-dma-buffer-objects"></a>

### CPU Access to DMA Buffer Objects


There are multiple reasons for supporting CPU access to a dma buffer object:

- Fallback operations in the kernel, for example when a device is connected
  over USB and the kernel needs to shuffle the data around first before
  sending it away. Cache coherency is handled by bracketing any transactions
  with calls to [`dma_buf_begin_cpu_access()`](#c-dma_buf_begin_cpu_access) and [`dma_buf_end_cpu_access()`](#c-dma_buf_end_cpu_access)
  access.

  Since for most kernel internal dma-buf accesses need the entire buffer, a
  vmap interface is introduced. Note that on very old 32-bit architectures
  vmalloc space might be limited and result in vmap calls failing.

  Interfaces:

```c
void *dma_buf_vmap(struct dma_buf *dmabuf, struct iosys_map *map)
void dma_buf_vunmap(struct dma_buf *dmabuf, struct iosys_map *map)
```

The vmap call can fail if there is no vmap support in the exporter, or if
it runs out of vmalloc space. Note that the dma-buf layer keeps a reference
count for all vmap access and calls down into the exporter's vmap function
only when no vmapping exists, and only unmaps it once. Protection against
concurrent vmap/vunmap calls is provided by taking the [`dma_buf.lock`](#c-struct-dma_buf) mutex.

- For full compatibility on the importer side with existing userspace
  interfaces, which might already support mmap'ing buffers. This is needed in
  many processing pipelines (e.g. feeding a software rendered image into a
  hardware pipeline, thumbnail creation, snapshots, ...). Also, Android's ION
  framework already supported this and for DMA buffer file descriptors to
  replace ION buffers mmap support was needed.

  There is no special interfaces, userspace simply calls mmap on the dma-buf
  fd. But like for CPU access there's a need to bracket the actual access,
  which is handled by the ioctl (DMA_BUF_IOCTL_SYNC). Note that
  DMA_BUF_IOCTL_SYNC can fail with -EAGAIN or -EINTR, in which case it must
  be restarted.

  Some systems might need some sort of cache coherency management e.g. when
  CPU and GPU domains are being accessed through dma-buf at the same time.
  To circumvent this problem there are begin/end coherency markers, that
  forward directly to existing dma-buf device drivers vfunc hooks. Userspace
  can make use of those markers through the DMA_BUF_IOCTL_SYNC ioctl. The
  sequence would be used like following:

  - mmap dma-buf fd
  - for each drawing/upload cycle in CPU 1. SYNC_START ioctl, 2. read/write
    to mmap area 3. SYNC_END ioctl. This can be repeated as often as you
    want (with the new data being consumed by say the GPU or the scanout
    device)
  - munmap once you don't need the buffer any more

  For correctness and optimal performance, it is always required to use
  SYNC_START and SYNC_END before and after, respectively, when accessing the
  mapped address. Userspace cannot rely on coherent access, even when there
  are systems where it just works without calling these ioctls.

- And as a CPU fallback in userspace processing pipelines.

  Similar to the motivation for kernel cpu access it is again important that
  the userspace code of a given importing subsystem can use the same
  interfaces with a imported dma-buf buffer object as with a native buffer
  object. This is especially important for drm where the userspace part of
  contemporary OpenGL, X, and other drivers is huge, and reworking them to
  use a different way to mmap a buffer rather invasive.

  The assumption in the current dma-buf interfaces is that redirecting the
  initial mmap is all that's needed. A survey of some of the existing
  subsystems shows that no driver seems to do any nefarious thing like
  syncing up with outstanding asynchronous processing on the device or
  allocating special resources at fault time. So hopefully this is good
  enough, since adding interfaces to intercept pagefaults and allow pte
  shootdowns would increase the complexity quite a bit.

  Interface:

```c
int dma_buf_mmap(struct dma_buf *, struct vm_area_struct *, unsigned long);
```

If the importing subsystem simply provides a special-purpose mmap call to
set up a mapping in userspace, calling do_mmap with [`dma_buf.file`](#c-struct-dma_buf) will
equally achieve that for a dma-buf object.


<a id="rst-implicit-fence-poll-support"></a>

### Implicit Fence Poll Support


To support cross-device and cross-driver synchronization of buffer access
implicit fences (represented internally in the kernel with [`struct dma_fence`](#c-struct-dma_fence))
can be attached to a [`dma_buf`](#c-struct-dma_buf). The glue for that and a few related things are
provided in the [`dma_resv`](#c-struct-dma_resv) structure.

Userspace can query the state of these implicitly tracked fences using `poll()`
and related system calls:

- Checking for EPOLLIN, i.e. read access, can be use to query the state of the
  most recent write or exclusive fence.

- Checking for EPOLLOUT, i.e. write access, can be used to query the state of
  all attached fences, shared and exclusive ones.

Note that this only signals the completion of the respective fences, i.e. the
DMA transfers are complete. Cache flushing and any other necessary
preparations before CPU access can begin still need to happen.

As an alternative to `poll()`, the set of fences on DMA buffer can be
exported as a [`sync_file`](#c-struct-sync_file) using `dma_buf_sync_file_export`.


<a id="rst-dma-buffer-ioctls"></a>

### DMA Buffer ioctls


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

Synchronize with CPU access.

**Definition**

```c
struct dma_buf_sync {
    __u64 flags;
};
```

**Members**

- `flags`: Set of access flags

  - DMA_BUF_SYNC_START:
    Indicates the start of a map access session.

  - DMA_BUF_SYNC_END:
    Indicates the end of a map access session.

  - DMA_BUF_SYNC_READ:
    Indicates that the mapped DMA buffer will be read by the
    client via the CPU map.

  - DMA_BUF_SYNC_WRITE:
    Indicates that the mapped DMA buffer will be written by the
    client via the CPU map.

  - DMA_BUF_SYNC_RW:
    An alias for DMA_BUF_SYNC_READ | DMA_BUF_SYNC_WRITE.

**Description**

When a DMA buffer is accessed from the CPU via mmap, it is not always
possible to guarantee coherency between the CPU-visible map and underlying
memory.  To manage coherency, DMA_BUF_IOCTL_SYNC must be used to bracket
any CPU access to give the kernel the chance to shuffle memory around if
needed.

Prior to accessing the map, the client must call DMA_BUF_IOCTL_SYNC
with DMA_BUF_SYNC_START and the appropriate read/write flags.  Once the
access is complete, the client should call DMA_BUF_IOCTL_SYNC with
DMA_BUF_SYNC_END and the same read/write flags.

The synchronization provided via DMA_BUF_IOCTL_SYNC only provides cache
coherency.  It does not prevent other processes or devices from
accessing the memory at the same time.  If synchronization with a GPU or
other device driver is required, it is the client's responsibility to
wait for buffer to be ready for reading or writing before calling this
ioctl with DMA_BUF_SYNC_START.  Likewise, the client must ensure that
follow-up work is not submitted to GPU or other device driver until
after this ioctl has been called with DMA_BUF_SYNC_END?

If the driver or API with which the client is interacting uses implicit
synchronization, waiting for prior work to complete can be done via
`poll()` on the DMA buffer file descriptor.  If the driver or API requires
explicit synchronization, the client may have to wait on a sync_file or
other synchronization primitive outside the scope of the DMA buffer API.

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

Get a sync_file from a dma-buf

**Definition**

```c
struct dma_buf_export_sync_file {
    __u32 flags;
    __s32 fd;
};
```

**Members**

- `flags`: Read/write flags

  Must be DMA_BUF_SYNC_READ, DMA_BUF_SYNC_WRITE, or both.

  If DMA_BUF_SYNC_READ is set and DMA_BUF_SYNC_WRITE is not set,
  the returned sync file waits on any writers of the dma-buf to
  complete.  Waiting on the returned sync file is equivalent to
  `poll()` with POLLIN.

  If DMA_BUF_SYNC_WRITE is set, the returned sync file waits on
  any users of the dma-buf (read or write) to complete.  Waiting
  on the returned sync file is equivalent to `poll()` with POLLOUT.
  If both DMA_BUF_SYNC_WRITE and DMA_BUF_SYNC_READ are set, this
  is equivalent to just DMA_BUF_SYNC_WRITE.
- `fd`: Returned sync file descriptor

**Description**

Userspace can perform a DMA_BUF_IOCTL_EXPORT_SYNC_FILE to retrieve the
current set of fences on a dma-buf file descriptor as a sync_file.  CPU
waits via `poll()` or other driver-specific mechanisms typically wait on
whatever fences are on the dma-buf at the time the wait begins.  This
is similar except that it takes a snapshot of the current fences on the
dma-buf for waiting later instead of waiting immediately.  This is
useful for modern graphics APIs such as Vulkan which assume an explicit
synchronization model but still need to inter-operate with dma-buf.

The intended usage pattern is the following:

1. Export a sync_file with flags corresponding to the expected GPU usage
   via DMA_BUF_IOCTL_EXPORT_SYNC_FILE.

2. Submit rendering work which uses the dma-buf.  The work should wait on
   the exported sync file before rendering and produce another sync_file
   when complete.

3. Import the rendering-complete sync_file into the dma-buf with flags
   corresponding to the GPU usage via DMA_BUF_IOCTL_IMPORT_SYNC_FILE.

Unlike doing implicit synchronization via a GPU kernel driver's exec ioctl,
the above is not a single atomic operation.  If userspace wants to ensure
ordering via these fences, it is the respnosibility of userspace to use
locks or other mechanisms to ensure that no other context adds fences or
submits work between steps 1 and 3 above.

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

Insert a sync_file into a dma-buf

**Definition**

```c
struct dma_buf_import_sync_file {
    __u32 flags;
    __s32 fd;
};
```

**Members**

- `flags`: Read/write flags

  Must be DMA_BUF_SYNC_READ, DMA_BUF_SYNC_WRITE, or both.

  If DMA_BUF_SYNC_READ is set and DMA_BUF_SYNC_WRITE is not set,
  this inserts the sync_file as a read-only fence.  Any subsequent
  implicitly synchronized writes to this dma-buf will wait on this
  fence but reads will not.

  If DMA_BUF_SYNC_WRITE is set, this inserts the sync_file as a
  write fence.  All subsequent implicitly synchronized access to
  this dma-buf will wait on this fence.
- `fd`: Sync file descriptor

**Description**

Userspace can perform a DMA_BUF_IOCTL_IMPORT_SYNC_FILE to insert a
sync_file into a dma-buf for the purposes of implicit synchronization
with other dma-buf consumers.  This allows clients using explicitly
synchronized APIs such as Vulkan to inter-op with dma-buf consumers
which expect implicit synchronization such as OpenGL or most media
drivers/video.


<a id="rst-dma-buf-locking-convention"></a>

### DMA-BUF locking convention


In order to avoid deadlock situations between dma-buf exports and importers,
all dma-buf API users must follow the common dma-buf locking convention.

Convention for importers

1. Importers must hold the dma-buf reservation lock when calling these
   functions:

   - [`dma_buf_pin()`](#c-dma_buf_pin)
   - [`dma_buf_unpin()`](#c-dma_buf_unpin)
   - [`dma_buf_map_attachment()`](#c-dma_buf_map_attachment)
   - [`dma_buf_unmap_attachment()`](#c-dma_buf_unmap_attachment)
   - [`dma_buf_vmap()`](#c-dma_buf_vmap)
   - [`dma_buf_vunmap()`](#c-dma_buf_vunmap)

2. Importers must not hold the dma-buf reservation lock when calling these
   functions:

   - [`dma_buf_attach()`](#c-dma_buf_attach)
   - [`dma_buf_dynamic_attach()`](#c-dma_buf_dynamic_attach)
   - [`dma_buf_detach()`](#c-dma_buf_detach)
   - [`dma_buf_export()`](#c-dma_buf_export)
   - [`dma_buf_fd()`](#c-dma_buf_fd)
   - [`dma_buf_get()`](#c-dma_buf_get)
   - [`dma_buf_put()`](#c-dma_buf_put)
   - [`dma_buf_mmap()`](#c-dma_buf_mmap)
   - [`dma_buf_begin_cpu_access()`](#c-dma_buf_begin_cpu_access)
   - [`dma_buf_end_cpu_access()`](#c-dma_buf_end_cpu_access)
   - [`dma_buf_map_attachment_unlocked()`](#c-dma_buf_map_attachment_unlocked)
   - [`dma_buf_unmap_attachment_unlocked()`](#c-dma_buf_unmap_attachment_unlocked)
   - [`dma_buf_vmap_unlocked()`](#c-dma_buf_vmap_unlocked)
   - [`dma_buf_vunmap_unlocked()`](#c-dma_buf_vunmap_unlocked)

Convention for exporters

1. These [`dma_buf_ops`](#c-struct-dma_buf_ops) callbacks are invoked with unlocked dma-buf
   reservation and exporter can take the lock:

   - [`dma_buf_ops.attach()`](#c-struct-dma_buf_ops)
   - [`dma_buf_ops.detach()`](#c-struct-dma_buf_ops)
   - [`dma_buf_ops.release()`](#c-struct-dma_buf_ops)
   - [`dma_buf_ops.begin_cpu_access()`](#c-struct-dma_buf_ops)
   - [`dma_buf_ops.end_cpu_access()`](#c-struct-dma_buf_ops)
   - [`dma_buf_ops.mmap()`](#c-struct-dma_buf_ops)

2. These [`dma_buf_ops`](#c-struct-dma_buf_ops) callbacks are invoked with locked dma-buf
   reservation and exporter can't take the lock:

   - [`dma_buf_ops.pin()`](#c-struct-dma_buf_ops)
   - [`dma_buf_ops.unpin()`](#c-struct-dma_buf_ops)
   - [`dma_buf_ops.map_dma_buf()`](#c-struct-dma_buf_ops)
   - [`dma_buf_ops.unmap_dma_buf()`](#c-struct-dma_buf_ops)
   - [`dma_buf_ops.vmap()`](#c-struct-dma_buf_ops)
   - [`dma_buf_ops.vunmap()`](#c-struct-dma_buf_ops)

3. Exporters must hold the dma-buf reservation lock when calling these
   functions:

   - [`dma_buf_move_notify()`](#c-dma_buf_move_notify)


<a id="rst-kernel-functions-and-structures-reference"></a>

### Kernel Functions and Structures Reference


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

```c
struct dma_buf * dma_buf_export(const struct dma_buf_export_info *exp_info)
```

Creates a new dma_buf, and associates an anon file with this buffer, so it can be exported. Also connect the allocator specific data and ops to the buffer. Additionally, provide a name string for exporter; useful in debugging.

**Parameters**

- `const struct dma_buf_export_info *exp_info`: \[in\]    holds all the export related information provided
  by the exporter. see [`struct dma_buf_export_info`](#c-struct-dma_buf_export_info)
  for further details.

**Description**

Returns, on success, a newly created struct dma_buf object, which wraps the
supplied private data and operations for struct dma_buf_ops. On either
missing ops, or error in allocating struct dma_buf, will return negative
error.

For most cases the easiest way to create **exp_info** is through the
`DEFINE_DMA_BUF_EXPORT_INFO` macro.

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

```c
int dma_buf_fd(struct dma_buf *dmabuf, int flags)
```

returns a file descriptor for the given struct dma_buf

**Parameters**

- `struct dma_buf *dmabuf`: \[in\]    pointer to dma_buf for which fd is required.
- `int flags`: \[in\]    flags to give to fd

**Description**

On success, returns an associated 'fd'. Else, returns error.

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

```c
struct dma_buf * dma_buf_get(int fd)
```

returns the struct dma_buf related to an fd

**Parameters**

- `int fd`: \[in\]    fd associated with the struct dma_buf to be returned

**Description**

On success, returns the struct dma_buf associated with an fd; uses
file's refcounting done by fget to increase refcount. returns ERR_PTR
otherwise.

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

```c
void dma_buf_put(struct dma_buf *dmabuf)
```

decreases refcount of the buffer

**Parameters**

- `struct dma_buf *dmabuf`: \[in\]    buffer to reduce refcount of

**Description**

Uses file's refcounting done implicitly by `fput()`.

If, as a result of this call, the refcount becomes 0, the 'release' file
operation related to this fd is called. It calls [`dma_buf_ops.release`](#c-struct-dma_buf_ops) vfunc
in turn, and frees the memory allocated for dmabuf when exported.

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

```c
struct dma_buf_attachment * dma_buf_dynamic_attach(struct dma_buf *dmabuf, struct device *dev, const struct dma_buf_attach_ops *importer_ops, void *importer_priv)
```

Add the device to dma_buf's attachments list

**Parameters**

- `struct dma_buf *dmabuf`: \[in\]    buffer to attach device to.
- `struct device *dev`: \[in\]    device to be attached.
- `const struct dma_buf_attach_ops *importer_ops`: \[in\]    importer operations for the attachment
- `void *importer_priv`: \[in\]    importer private pointer for the attachment

**Description**

Returns struct dma_buf_attachment pointer for this attachment. Attachments
must be cleaned up by calling [`dma_buf_detach()`](#c-dma_buf_detach).

Optionally this calls [`dma_buf_ops.attach`](#c-struct-dma_buf_ops) to allow device-specific attach
functionality.

A pointer to newly created [`dma_buf_attachment`](#c-struct-dma_buf_attachment) on success, or a negative
error code wrapped into a pointer on failure.

Note that this can fail if the backing storage of **dmabuf** is in a place not
accessible to **dev**, and cannot be moved to a more suitable place. This is
indicated with the error code -EBUSY.

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

```c
struct dma_buf_attachment * dma_buf_attach(struct dma_buf *dmabuf, struct device *dev)
```

Wrapper for dma_buf_dynamic_attach

**Parameters**

- `struct dma_buf *dmabuf`: \[in\]    buffer to attach device to.
- `struct device *dev`: \[in\]    device to be attached.

**Description**

Wrapper to call [`dma_buf_dynamic_attach()`](#c-dma_buf_dynamic_attach) for drivers which still use a static
mapping.

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

```c
void dma_buf_detach(struct dma_buf *dmabuf, struct dma_buf_attachment *attach)
```

Remove the given attachment from dmabuf's attachments list

**Parameters**

- `struct dma_buf *dmabuf`: \[in\]    buffer to detach from.
- `struct dma_buf_attachment *attach`: \[in\]    attachment to be detached; is free'd after this call.

**Description**

Clean up a device attachment obtained by calling [`dma_buf_attach()`](#c-dma_buf_attach).

Optionally this calls [`dma_buf_ops.detach`](#c-struct-dma_buf_ops) for device-specific detach.

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

```c
int dma_buf_pin(struct dma_buf_attachment *attach)
```

Lock down the DMA-buf

**Parameters**

- `struct dma_buf_attachment *attach`: \[in\]    attachment which should be pinned

**Description**

Only dynamic importers (who set up **attach** with [`dma_buf_dynamic_attach()`](#c-dma_buf_dynamic_attach)) may
call this, and only for limited use cases like scanout and not for temporary
pin operations. It is not permitted to allow userspace to pin arbitrary
amounts of buffers through this interface.

Buffers must be unpinned by calling [`dma_buf_unpin()`](#c-dma_buf_unpin).

**Return**

0 on success, negative error code on failure.

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

```c
void dma_buf_unpin(struct dma_buf_attachment *attach)
```

Unpin a DMA-buf

**Parameters**

- `struct dma_buf_attachment *attach`: \[in\]    attachment which should be unpinned

**Description**

This unpins a buffer pinned by [`dma_buf_pin()`](#c-dma_buf_pin) and allows the exporter to move
any mapping of **attach** again and inform the importer through
[`dma_buf_attach_ops.move_notify`](#c-struct-dma_buf_attach_ops).

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

```c
struct sg_table * dma_buf_map_attachment(struct dma_buf_attachment *attach, enum dma_data_direction direction)
```

Returns the scatterlist table of the attachment; mapped into _device_ address space. Is a wrapper for `map_dma_buf()` of the dma_buf_ops.

**Parameters**

- `struct dma_buf_attachment *attach`: \[in\]    attachment whose scatterlist is to be returned
- `enum dma_data_direction direction`: \[in\]    direction of DMA transfer

**Description**

Returns sg_table containing the scatterlist to be returned; returns ERR_PTR
on error. May return -EINTR if it is interrupted by a signal.

On success, the DMA addresses and lengths in the returned scatterlist are
PAGE_SIZE aligned.

A mapping must be unmapped by using [`dma_buf_unmap_attachment()`](#c-dma_buf_unmap_attachment). Note that
the underlying backing storage is pinned for as long as a mapping exists,
therefore users/importers should not hold onto a mapping for undue amounts of
time.

Important: Dynamic importers must wait for the exclusive fence of the struct
dma_resv attached to the DMA-BUF first.

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

```c
struct sg_table * dma_buf_map_attachment_unlocked(struct dma_buf_attachment *attach, enum dma_data_direction direction)
```

Returns the scatterlist table of the attachment; mapped into _device_ address space. Is a wrapper for `map_dma_buf()` of the dma_buf_ops.

**Parameters**

- `struct dma_buf_attachment *attach`: \[in\]    attachment whose scatterlist is to be returned
- `enum dma_data_direction direction`: \[in\]    direction of DMA transfer

**Description**

Unlocked variant of [`dma_buf_map_attachment()`](#c-dma_buf_map_attachment).

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

```c
void dma_buf_unmap_attachment(struct dma_buf_attachment *attach, struct sg_table *sg_table, enum dma_data_direction direction)
```

unmaps and decreases usecount of the buffer;might deallocate the scatterlist associated. Is a wrapper for `unmap_dma_buf()` of dma_buf_ops.

**Parameters**

- `struct dma_buf_attachment *attach`: \[in\]    attachment to unmap buffer from
- `struct sg_table *sg_table`: \[in\]    scatterlist info of the buffer to unmap
- `enum dma_data_direction direction`: \[in\]    direction of DMA transfer

**Description**

This unmaps a DMA mapping for **attached** obtained by [`dma_buf_map_attachment()`](#c-dma_buf_map_attachment).

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

```c
void dma_buf_unmap_attachment_unlocked(struct dma_buf_attachment *attach, struct sg_table *sg_table, enum dma_data_direction direction)
```

unmaps and decreases usecount of the buffer;might deallocate the scatterlist associated. Is a wrapper for `unmap_dma_buf()` of dma_buf_ops.

**Parameters**

- `struct dma_buf_attachment *attach`: \[in\]    attachment to unmap buffer from
- `struct sg_table *sg_table`: \[in\]    scatterlist info of the buffer to unmap
- `enum dma_data_direction direction`: \[in\]    direction of DMA transfer

**Description**

Unlocked variant of [`dma_buf_unmap_attachment()`](#c-dma_buf_unmap_attachment).

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

```c
void dma_buf_move_notify(struct dma_buf *dmabuf)
```

notify attachments that DMA-buf is moving

**Parameters**

- `struct dma_buf *dmabuf`: \[in\]    buffer which is moving

**Description**

Informs all attachments that they need to destroy and recreate all their
mappings.

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

```c
int dma_buf_begin_cpu_access(struct dma_buf *dmabuf, enum dma_data_direction direction)
```

Must be called before accessing a dma_buf from the cpu in the kernel context. Calls begin_cpu_access to allow exporter-specific preparations. Coherency is only guaranteed in the specified range for the specified access direction.

**Parameters**

- `struct dma_buf *dmabuf`: \[in\]    buffer to prepare cpu access for.
- `enum dma_data_direction direction`: \[in\]    direction of access.

**Description**

After the cpu access is complete the caller should call
[`dma_buf_end_cpu_access()`](#c-dma_buf_end_cpu_access). Only when cpu access is bracketed by both calls is
it guaranteed to be coherent with other DMA access.

This function will also wait for any DMA transactions tracked through
implicit synchronization in [`dma_buf.resv`](#c-struct-dma_buf). For DMA transactions with explicit
synchronization this function will only ensure cache coherency, callers must
ensure synchronization with such DMA transactions on their own.

Can return negative error values, returns 0 on success.

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

```c
int dma_buf_end_cpu_access(struct dma_buf *dmabuf, enum dma_data_direction direction)
```

Must be called after accessing a dma_buf from the cpu in the kernel context. Calls end_cpu_access to allow exporter-specific actions. Coherency is only guaranteed in the specified range for the specified access direction.

**Parameters**

- `struct dma_buf *dmabuf`: \[in\]    buffer to complete cpu access for.
- `enum dma_data_direction direction`: \[in\]    direction of access.

**Description**

This terminates CPU access started with [`dma_buf_begin_cpu_access()`](#c-dma_buf_begin_cpu_access).

Can return negative error values, returns 0 on success.

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

```c
int dma_buf_mmap(struct dma_buf *dmabuf, struct vm_area_struct *vma, unsigned long pgoff)
```

Setup up a userspace mmap with the given vma

**Parameters**

- `struct dma_buf *dmabuf`: \[in\]    buffer that should back the vma
- `struct vm_area_struct *vma`: \[in\]    vma for the mmap
- `unsigned long pgoff`: \[in\]    offset in pages where this mmap should start within the
  dma-buf buffer.

**Description**

This function adjusts the passed in vma so that it points at the file of the
dma_buf operation. It also adjusts the starting pgoff and does bounds
checking on the size of the vma. Then it calls the exporters mmap function to
set up the mapping.

Can return negative error values, returns 0 on success.

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

```c
int dma_buf_vmap(struct dma_buf *dmabuf, struct iosys_map *map)
```

Create virtual mapping for the buffer object into kernel address space. Same restrictions as for vmap and friends apply.

**Parameters**

- `struct dma_buf *dmabuf`: \[in\]    buffer to vmap
- `struct iosys_map *map`: \[out\]   returns the vmap pointer

**Description**

This call may fail due to lack of virtual mapping address space.
These calls are optional in drivers. The intended use for them
is for mapping objects linear in kernel space for high use objects.

To ensure coherency users must call [`dma_buf_begin_cpu_access()`](#c-dma_buf_begin_cpu_access) and
[`dma_buf_end_cpu_access()`](#c-dma_buf_end_cpu_access) around any cpu access performed through this
mapping.

Returns 0 on success, or a negative errno code otherwise.

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

```c
int dma_buf_vmap_unlocked(struct dma_buf *dmabuf, struct iosys_map *map)
```

Create virtual mapping for the buffer object into kernel address space. Same restrictions as for vmap and friends apply.

**Parameters**

- `struct dma_buf *dmabuf`: \[in\]    buffer to vmap
- `struct iosys_map *map`: \[out\]   returns the vmap pointer

**Description**

Unlocked version of [`dma_buf_vmap()`](#c-dma_buf_vmap)

Returns 0 on success, or a negative errno code otherwise.

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

```c
void dma_buf_vunmap(struct dma_buf *dmabuf, struct iosys_map *map)
```

Unmap a vmap obtained by dma_buf_vmap.

**Parameters**

- `struct dma_buf *dmabuf`: \[in\]    buffer to vunmap
- `struct iosys_map *map`: \[in\]    vmap pointer to vunmap

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

```c
void dma_buf_vunmap_unlocked(struct dma_buf *dmabuf, struct iosys_map *map)
```

Unmap a vmap obtained by dma_buf_vmap.

**Parameters**

- `struct dma_buf *dmabuf`: \[in\]    buffer to vunmap
- `struct iosys_map *map`: \[in\]    vmap pointer to vunmap



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

operations possible on struct dma_buf

**Definition**

```c
struct dma_buf_ops {
    int (*attach)(struct dma_buf *, struct dma_buf_attachment *);
    void (*detach)(struct dma_buf *, struct dma_buf_attachment *);
    int (*pin)(struct dma_buf_attachment *attach);
    void (*unpin)(struct dma_buf_attachment *attach);
    struct sg_table * (*map_dma_buf)(struct dma_buf_attachment *, enum dma_data_direction);
    void (*unmap_dma_buf)(struct dma_buf_attachment *, struct sg_table *, enum dma_data_direction);
    void (*release)(struct dma_buf *);
    int (*begin_cpu_access)(struct dma_buf *, enum dma_data_direction);
    int (*end_cpu_access)(struct dma_buf *, enum dma_data_direction);
    int (*mmap)(struct dma_buf *, struct vm_area_struct *vma);
    int (*vmap)(struct dma_buf *dmabuf, struct iosys_map *map);
    void (*vunmap)(struct dma_buf *dmabuf, struct iosys_map *map);
};
```

**Members**

- `attach`: This is called from [`dma_buf_attach()`](#c-dma_buf_attach) to make sure that a given
  [`dma_buf_attachment.dev`](#c-struct-dma_buf_attachment) can access the provided [`dma_buf`](#c-struct-dma_buf). Exporters
  which support buffer objects in special locations like VRAM or
  device-specific carveout areas should check whether the buffer could
  be move to system memory (or directly accessed by the provided
  device), and otherwise need to fail the attach operation.

  The exporter should also in general check whether the current
  allocation fulfills the DMA constraints of the new device. If this
  is not the case, and the allocation cannot be moved, it should also
  fail the attach operation.

  Any exporter-private housekeeping data can be stored in the
  [`dma_buf_attachment.priv`](#c-struct-dma_buf_attachment) pointer.

  This callback is optional.

  Returns:

  0 on success, negative error code on failure. It might return -EBUSY
  to signal that backing storage is already allocated and incompatible
  with the requirements of requesting device.
- `detach`: This is called by [`dma_buf_detach()`](#c-dma_buf_detach) to release a [`dma_buf_attachment`](#c-struct-dma_buf_attachment).
  Provided so that exporters can clean up any housekeeping for an
  [`dma_buf_attachment`](#c-struct-dma_buf_attachment).

  This callback is optional.
- `pin`: This is called by [`dma_buf_pin()`](#c-dma_buf_pin) and lets the exporter know that the
  DMA-buf can't be moved any more. Ideally, the exporter should
  pin the buffer so that it is generally accessible by all
  devices.

  This is called with the `dmabuf.resv` object locked and is mutual
  exclusive with **cache_sgt_mapping**.

  This is called automatically for non-dynamic importers from
  [`dma_buf_attach()`](#c-dma_buf_attach).

  Note that similar to non-dynamic exporters in their **map_dma_buf**
  callback the driver must guarantee that the memory is available for
  use and cleared of any old data by the time this function returns.
  Drivers which pipeline their buffer moves internally must wait for
  all moves and clears to complete.

  Returns:

  0 on success, negative error code on failure.
- `unpin`: This is called by [`dma_buf_unpin()`](#c-dma_buf_unpin) and lets the exporter know that the
  DMA-buf can be moved again.

  This is called with the dmabuf->resv object locked and is mutual
  exclusive with **cache_sgt_mapping**.

  This callback is optional.
- `map_dma_buf`: This is called by [`dma_buf_map_attachment()`](#c-dma_buf_map_attachment) and is used to map a
  shared [`dma_buf`](#c-struct-dma_buf) into device address space, and it is mandatory. It
  can only be called if **attach** has been called successfully.

  This call may sleep, e.g. when the backing storage first needs to be
  allocated, or moved to a location suitable for all currently attached
  devices.

  Note that any specific buffer attributes required for this function
  should get added to device_dma_parameters accessible via
  [`device.dma_params`](/kernel/hardware/driver-api/fundamentals/infrastructure.md#c-struct-device) from the [`dma_buf_attachment`](#c-struct-dma_buf_attachment). The **attach** callback
  should also check these constraints.

  If this is being called for the first time, the exporter can now
  choose to scan through the list of attachments for this buffer,
  collate the requirements of the attached devices, and choose an
  appropriate backing storage for the buffer.

  Based on enum dma_data_direction, it might be possible to have
  multiple users accessing at the same time (for reading, maybe), or
  any other kind of sharing that the exporter might wish to make
  available to buffer-users.

  This is always called with the dmabuf->resv object locked when
  the dynamic_mapping flag is true.

  Note that for non-dynamic exporters the driver must guarantee that
  that the memory is available for use and cleared of any old data by
  the time this function returns.  Drivers which pipeline their buffer
  moves internally must wait for all moves and clears to complete.
  Dynamic exporters do not need to follow this rule: For non-dynamic
  importers the buffer is already pinned through **pin**, which has the
  same requirements. Dynamic importers otoh are required to obey the
  dma_resv fences.

  Returns:

  A `sg_table` scatter list of the backing storage of the DMA buffer,
  already mapped into the device address space of the [`device`](/kernel/hardware/driver-api/fundamentals/infrastructure.md#c-struct-device) attached
  with the provided [`dma_buf_attachment`](#c-struct-dma_buf_attachment). The addresses and lengths in
  the scatter list are PAGE_SIZE aligned.

  On failure, returns a negative error value wrapped into a pointer.
  May also return -EINTR when a signal was received while being
  blocked.

  Note that exporters should not try to cache the scatter list, or
  return the same one for multiple calls. Caching is done either by the
  DMA-BUF code (for non-dynamic importers) or the importer. Ownership
  of the scatter list is transferred to the caller, and returned by
  **unmap_dma_buf**.
- `unmap_dma_buf`: This is called by [`dma_buf_unmap_attachment()`](#c-dma_buf_unmap_attachment) and should unmap and
  release the `sg_table` allocated in **map_dma_buf**, and it is mandatory.
  For static dma_buf handling this might also unpin the backing
  storage if this is the last mapping of the DMA buffer.
- `release`: Called after the last dma_buf_put to release the [`dma_buf`](#c-struct-dma_buf), and
  mandatory.
- `begin_cpu_access`: This is called from [`dma_buf_begin_cpu_access()`](#c-dma_buf_begin_cpu_access) and allows the
  exporter to ensure that the memory is actually coherent for cpu
  access. The exporter also needs to ensure that cpu access is coherent
  for the access direction. The direction can be used by the exporter
  to optimize the cache flushing, i.e. access with a different
  direction (read instead of write) might return stale or even bogus
  data (e.g. when the exporter needs to copy the data to temporary
  storage).

  Note that this is both called through the DMA_BUF_IOCTL_SYNC IOCTL
  command for userspace mappings established through **mmap**, and also
  for kernel mappings established with **vmap**.

  This callback is optional.

  Returns:

  0 on success or a negative error code on failure. This can for
  example fail when the backing storage can't be allocated. Can also
  return -ERESTARTSYS or -EINTR when the call has been interrupted and
  needs to be restarted.
- `end_cpu_access`: This is called from [`dma_buf_end_cpu_access()`](#c-dma_buf_end_cpu_access) when the importer is
  done accessing the CPU. The exporter can use this to flush caches and
  undo anything else done in **begin_cpu_access**.

  This callback is optional.

  Returns:

  0 on success or a negative error code on failure. Can return
  -ERESTARTSYS or -EINTR when the call has been interrupted and needs
  to be restarted.
- `mmap`: This callback is used by the [`dma_buf_mmap()`](#c-dma_buf_mmap) function

  Note that the mapping needs to be incoherent, userspace is expected
  to bracket CPU access using the DMA_BUF_IOCTL_SYNC interface.

  Because dma-buf buffers have invariant size over their lifetime, the
  dma-buf core checks whether a vma is too large and rejects such
  mappings. The exporter hence does not need to duplicate this check.
  Drivers do not need to check this themselves.

  If an exporter needs to manually flush caches and hence needs to fake
  coherency for mmap support, it needs to be able to zap all the ptes
  pointing at the backing storage. Now linux mm needs a struct
  address_space associated with the struct file stored in vma->vm_file
  to do that with the function unmap_mapping_range. But the dma_buf
  framework only backs every dma_buf fd with the anon_file struct file,
  i.e. all dma_bufs share the same file.

  Hence exporters need to setup their own file (and address_space)
  association by setting vma->vm_file and adjusting vma->vm_pgoff in
  the dma_buf mmap callback. In the specific case of a gem driver the
  exporter could use the shmem file already provided by gem (and set
  vm_pgoff = 0). Exporters can then zap ptes by unmapping the
  corresponding range of the struct address_space associated with their
  own file.

  This callback is optional.

  Returns:

  0 on success or a negative error code on failure.
- `vmap`: \[optional\] creates a virtual mapping for the buffer into kernel
  address space. Same restrictions as for vmap and friends apply.
- `vunmap`: \[optional\] unmaps a vmap from the buffer

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

shared buffer object

**Definition**

```c
struct dma_buf {
    size_t size;
    struct file *file;
    struct list_head attachments;
    const struct dma_buf_ops *ops;
    unsigned vmapping_counter;
    struct iosys_map vmap_ptr;
    const char *exp_name;
    const char *name;
    spinlock_t name_lock;
    struct module *owner;
    struct list_head list_node;
    void *priv;
    struct dma_resv *resv;
    wait_queue_head_t poll;
    struct dma_buf_poll_cb_t {
        struct dma_fence_cb cb;
        wait_queue_head_t *poll;
        __poll_t active;
    } cb_in, cb_out;
};
```

**Members**

- `size`: Size of the buffer; invariant over the lifetime of the buffer.
- `file`: File pointer used for sharing buffers across, and for refcounting.
  See [`dma_buf_get()`](#c-dma_buf_get) and [`dma_buf_put()`](#c-dma_buf_put).
- `attachments`: List of dma_buf_attachment that denotes all devices attached,
  protected by [`dma_resv`](#c-struct-dma_resv) lock **resv**.
- `ops`: dma_buf_ops associated with this buffer object.
- `vmapping_counter`: Used internally to refcnt the vmaps returned by [`dma_buf_vmap()`](#c-dma_buf_vmap).
  Protected by **lock**.
- `vmap_ptr`: The current vmap ptr if **vmapping_counter** > 0. Protected by **lock**.
- `exp_name`: Name of the exporter; useful for debugging. Must not be NULL
- `name`: Userspace-provided name. Default value is NULL. If not NULL,
  length cannot be longer than DMA_BUF_NAME_LEN, including NIL
  char. Useful for accounting and debugging. Read/Write accesses
  are protected by **name_lock**

  See the IOCTLs DMA_BUF_SET_NAME or DMA_BUF_SET_NAME_A/B
- `name_lock`: Spinlock to protect name access for read access.
- `owner`: Pointer to exporter module; used for refcounting when exporter is a
  kernel module.
- `list_node`: node for dma_buf accounting and debugging.
- `priv`: exporter specific private data for this buffer object.
- `resv`: Reservation object linked to this dma-buf.

  IMPLICIT SYNCHRONIZATION RULES:

  Drivers which support implicit synchronization of buffer access as
  e.g. exposed in `Implicit Fence Poll Support` must follow the
  below rules.

  - Drivers must add a read fence through [`dma_resv_add_fence()`](#c-dma_resv_add_fence) with the
    DMA_RESV_USAGE_READ flag for anything the userspace API considers a
    read access. This highly depends upon the API and window system.

  - Similarly drivers must add a write fence through
    [`dma_resv_add_fence()`](#c-dma_resv_add_fence) with the DMA_RESV_USAGE_WRITE flag for
    anything the userspace API considers write access.

  - Drivers may just always add a write fence, since that only
    causes unnecessary synchronization, but no correctness issues.

  - Some drivers only expose a synchronous userspace API with no
    pipelining across drivers. These do not set any fences for their
    access. An example here is v4l.

  - Driver should use [`dma_resv_usage_rw()`](#c-dma_resv_usage_rw) when retrieving fences as
    dependency for implicit synchronization.

  DYNAMIC IMPORTER RULES:

  Dynamic importers, see `dma_buf_attachment_is_dynamic()`, have
  additional constraints on how they set up fences:

  - Dynamic importers must obey the write fences and wait for them to
    signal before allowing access to the buffer's underlying storage
    through the device.

  - Dynamic importers should set fences for any access that they can't
    disable immediately from their [`dma_buf_attach_ops.move_notify`](#c-struct-dma_buf_attach_ops)
    callback.

  IMPORTANT:

  All drivers and memory management related functions must obey the
  struct dma_resv rules, specifically the rules for updating and
  obeying fences. See enum dma_resv_usage for further descriptions.
- `poll`: for userspace poll support
- `cb_in`: for userspace poll support
- `cb_out`: for userspace poll support

**Description**

This represents a shared buffer, created by calling [`dma_buf_export()`](#c-dma_buf_export). The
userspace representation is a normal file descriptor, which can be created by
calling [`dma_buf_fd()`](#c-dma_buf_fd).

Shared dma buffers are reference counted using [`dma_buf_put()`](#c-dma_buf_put) and
[`get_dma_buf()`](#c-get_dma_buf).

Device DMA access is handled by the separate [`struct dma_buf_attachment`](#c-struct-dma_buf_attachment).

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

importer operations for an attachment

**Definition**

```c
struct dma_buf_attach_ops {
    bool allow_peer2peer;
    void (*move_notify)(struct dma_buf_attachment *attach);
};
```

**Members**

- `allow_peer2peer`: If this is set to true the importer must be able to handle peer
  resources without struct pages.
- `move_notify`: \[optional\] notification that the DMA-buf is moving

  If this callback is provided the framework can avoid pinning the
  backing store while mappings exists.

  This callback is called with the lock of the reservation object
  associated with the dma_buf held and the mapping function must be
  called with this lock held as well. This makes sure that no mapping
  is created concurrently with an ongoing move operation.

  Mappings stay valid and are not directly affected by this callback.
  But the DMA-buf can now be in a different physical location, so all
  mappings should be destroyed and re-created as soon as possible.

  New mappings can be created after this callback returns, and will
  point to the new location of the DMA-buf.

**Description**

Attachment operations implemented by the importer.

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

holds device-buffer attachment data

**Definition**

```c
struct dma_buf_attachment {
    struct dma_buf *dmabuf;
    struct device *dev;
    struct list_head node;
    bool peer2peer;
    const struct dma_buf_attach_ops *importer_ops;
    void *importer_priv;
    void *priv;
};
```

**Members**

- `dmabuf`: buffer for this attachment.
- `dev`: device attached to the buffer.
- `node`: list of dma_buf_attachment, protected by dma_resv lock of the dmabuf.
- `peer2peer`: true if the importer can handle peer resources without pages.
- `importer_ops`: importer operations for this attachment, if provided
  dma_buf_map/`unmap_attachment()` must be called with the dma_resv lock held.
- `importer_priv`: importer specific attachment data.
- `priv`: exporter specific attachment data.

**Description**

This structure holds the attachment information between the dma_buf buffer
and its user device(s). The list contains one attachment struct per device
attached to the buffer.

An attachment is created by calling [`dma_buf_attach()`](#c-dma_buf_attach), and released again by
calling [`dma_buf_detach()`](#c-dma_buf_detach). The DMA mapping itself needed to initiate a
transfer is created by [`dma_buf_map_attachment()`](#c-dma_buf_map_attachment) and freed again by calling
[`dma_buf_unmap_attachment()`](#c-dma_buf_unmap_attachment).

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

holds information needed to export a dma_buf

**Definition**

```c
struct dma_buf_export_info {
    const char *exp_name;
    struct module *owner;
    const struct dma_buf_ops *ops;
    size_t size;
    int flags;
    struct dma_resv *resv;
    void *priv;
};
```

**Members**

- `exp_name`: name of the exporter - useful for debugging.
- `owner`: pointer to exporter module - used for refcounting kernel module
- `ops`: Attach allocator-defined dma buf ops to the new buffer
- `size`: Size of the buffer - invariant over the lifetime of the buffer
- `flags`: mode flags for the file
- `resv`: reservation-object, NULL to allocate default one
- `priv`: Attach private data of allocator to this buffer

**Description**

This structure holds the information required to export the buffer. Used
with [`dma_buf_export()`](#c-dma_buf_export) only.

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

```c
DEFINE_DMA_BUF_EXPORT_INFO(name)
```

helper macro for exporters

**Parameters**

- `name`: export-info name

**Description**

DEFINE_DMA_BUF_EXPORT_INFO macro defines the [`struct dma_buf_export_info`](#c-struct-dma_buf_export_info),
zeroes it out and pre-populates exp_name in it.

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

```c
void get_dma_buf(struct dma_buf *dmabuf)
```

convenience wrapper for get_file.

**Parameters**

- `struct dma_buf *dmabuf`: \[in\]    pointer to dma_buf

**Description**

Increments the reference count on the dma-buf, needed in case of drivers
that either need to create additional references to the dmabuf on the
kernel side.  For example, an exporter that needs to keep a dmabuf ptr
so that subsequent exports don't create a new dmabuf.

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

```c
bool dma_buf_is_dynamic(struct dma_buf *dmabuf)
```

check if a DMA-buf uses dynamic mappings.

**Parameters**

- `struct dma_buf *dmabuf`: the DMA-buf to check

**Description**

Returns true if a DMA-buf exporter wants to be called with the dma_resv
locked for the map/unmap callbacks, false if it doesn't wants to be called
with the lock held.


<a id="rst-reservation-objects"></a>

## Reservation Objects


The reservation object provides a mechanism to manage a container of
dma_fence object associated with a resource. A reservation object
can have any number of fences attaches to it. Each fence carries an usage
parameter determining how the operation represented by the fence is using the
resource. The RCU mechanism is used to protect read access to fences from
locked write-side updates.

See struct dma_resv for more details.



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

```c
void dma_resv_init(struct dma_resv *obj)
```

initialize a reservation object

**Parameters**

- `struct dma_resv *obj`: the reservation object

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

```c
void dma_resv_fini(struct dma_resv *obj)
```

destroys a reservation object

**Parameters**

- `struct dma_resv *obj`: the reservation object

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

```c
int dma_resv_reserve_fences(struct dma_resv *obj, unsigned int num_fences)
```

Reserve space to add fences to a dma_resv object.

**Parameters**

- `struct dma_resv *obj`: reservation object
- `unsigned int num_fences`: number of fences we want to add

**Description**

Should be called before [`dma_resv_add_fence()`](#c-dma_resv_add_fence).  Must be called with **obj**
locked through [`dma_resv_lock()`](#c-dma_resv_lock).

Note that the preallocated slots need to be re-reserved if **obj** is unlocked
at any time before calling [`dma_resv_add_fence()`](#c-dma_resv_add_fence). This is validated when
CONFIG_DEBUG_MUTEXES is enabled.

RETURNS
Zero for success, or -errno

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

```c
void dma_resv_reset_max_fences(struct dma_resv *obj)
```

reset fences for debugging

**Parameters**

- `struct dma_resv *obj`: the dma_resv object to reset

**Description**

Reset the number of pre-reserved fence slots to test that drivers do
correct slot allocation using [`dma_resv_reserve_fences()`](#c-dma_resv_reserve_fences). See also
`dma_resv_list.max_fences`.

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

```c
void dma_resv_add_fence(struct dma_resv *obj, struct dma_fence *fence, enum dma_resv_usage usage)
```

Add a fence to the dma_resv obj

**Parameters**

- `struct dma_resv *obj`: the reservation object
- `struct dma_fence *fence`: the fence to add
- `enum dma_resv_usage usage`: how the fence is used, see enum dma_resv_usage

**Description**

Add a fence to a slot, **obj** must be locked with [`dma_resv_lock()`](#c-dma_resv_lock), and
[`dma_resv_reserve_fences()`](#c-dma_resv_reserve_fences) has been called.

See also [`dma_resv.fence`](#c-struct-dma_resv) for a discussion of the semantics.

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

```c
void dma_resv_replace_fences(struct dma_resv *obj, uint64_t context, struct dma_fence *replacement, enum dma_resv_usage usage)
```

replace fences in the dma_resv obj

**Parameters**

- `struct dma_resv *obj`: the reservation object
- `uint64_t context`: the context of the fences to replace
- `struct dma_fence *replacement`: the new fence to use instead
- `enum dma_resv_usage usage`: how the new fence is used, see enum dma_resv_usage

**Description**

Replace fences with a specified context with a new fence. Only valid if the
operation represented by the original fence has no longer access to the
resources represented by the dma_resv object when the new fence completes.

And example for using this is replacing a preemption fence with a page table
update fence which makes the resource inaccessible.

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

```c
struct dma_fence * dma_resv_iter_first_unlocked(struct dma_resv_iter *cursor)
```

first fence in an unlocked dma_resv obj.

**Parameters**

- `struct dma_resv_iter *cursor`: the cursor with the current position

**Description**

Subsequent fences are iterated with [`dma_resv_iter_next_unlocked()`](#c-dma_resv_iter_next_unlocked).

Beware that the iterator can be restarted.  Code which accumulates statistics
or similar needs to check for this with [`dma_resv_iter_is_restarted()`](#c-dma_resv_iter_is_restarted). For
this reason prefer the locked [`dma_resv_iter_first()`](#c-dma_resv_iter_first) whenever possible.

Returns the first fence from an unlocked dma_resv obj.

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

```c
struct dma_fence * dma_resv_iter_next_unlocked(struct dma_resv_iter *cursor)
```

next fence in an unlocked dma_resv obj.

**Parameters**

- `struct dma_resv_iter *cursor`: the cursor with the current position

**Description**

Beware that the iterator can be restarted.  Code which accumulates statistics
or similar needs to check for this with [`dma_resv_iter_is_restarted()`](#c-dma_resv_iter_is_restarted). For
this reason prefer the locked [`dma_resv_iter_next()`](#c-dma_resv_iter_next) whenever possible.

Returns the next fence from an unlocked dma_resv obj.

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

```c
struct dma_fence * dma_resv_iter_first(struct dma_resv_iter *cursor)
```

first fence from a locked dma_resv object

**Parameters**

- `struct dma_resv_iter *cursor`: cursor to record the current position

**Description**

Subsequent fences are iterated with [`dma_resv_iter_next_unlocked()`](#c-dma_resv_iter_next_unlocked).

Return the first fence in the dma_resv object while holding the
[`dma_resv.lock`](#c-struct-dma_resv).

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

```c
struct dma_fence * dma_resv_iter_next(struct dma_resv_iter *cursor)
```

next fence from a locked dma_resv object

**Parameters**

- `struct dma_resv_iter *cursor`: cursor to record the current position

**Description**

Return the next fences from the dma_resv object while holding the
[`dma_resv.lock`](#c-struct-dma_resv).

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

```c
int dma_resv_copy_fences(struct dma_resv *dst, struct dma_resv *src)
```

Copy all fences from src to dst.

**Parameters**

- `struct dma_resv *dst`: the destination reservation object
- `struct dma_resv *src`: the source reservation object

**Description**

Copy all fences from src to dst. dst-lock must be held.

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

```c
int dma_resv_get_fences(struct dma_resv *obj, enum dma_resv_usage usage, unsigned int *num_fences, struct dma_fence ***fences)
```

Get an object's fences fences without update side lock held

**Parameters**

- `struct dma_resv *obj`: the reservation object
- `enum dma_resv_usage usage`: controls which fences to include, see enum dma_resv_usage.
- `unsigned int *num_fences`: the number of fences returned
- `struct dma_fence ***fences`: the array of fence ptrs returned (array is krealloc'd to the
  required size, and must be freed by caller)

**Description**

Retrieve all fences from the reservation object.
Returns either zero or -ENOMEM.

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

```c
int dma_resv_get_singleton(struct dma_resv *obj, enum dma_resv_usage usage, struct dma_fence **fence)
```

Get a single fence for all the fences

**Parameters**

- `struct dma_resv *obj`: the reservation object
- `enum dma_resv_usage usage`: controls which fences to include, see enum dma_resv_usage.
- `struct dma_fence **fence`: the resulting fence

**Description**

Get a single fence representing all the fences inside the resv object.
Returns either 0 for success or -ENOMEM.

Warning: This can't be used like this when adding the fence back to the resv
object since that can lead to stack corruption when finalizing the
dma_fence_array.

Returns 0 on success and negative error values on failure.

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

```c
long dma_resv_wait_timeout(struct dma_resv *obj, enum dma_resv_usage usage, bool intr, unsigned long timeout)
```

Wait on reservation's objects fences

**Parameters**

- `struct dma_resv *obj`: the reservation object
- `enum dma_resv_usage usage`: controls which fences to include, see enum dma_resv_usage.
- `bool intr`: if true, do interruptible wait
- `unsigned long timeout`: timeout value in jiffies or zero to return immediately

**Description**

Callers are not required to hold specific locks, but maybe hold
[`dma_resv_lock()`](#c-dma_resv_lock) already
RETURNS
Returns -ERESTARTSYS if interrupted, 0 if the wait timed out, or
greater than zero on success.

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

```c
void dma_resv_set_deadline(struct dma_resv *obj, enum dma_resv_usage usage, ktime_t deadline)
```

Set a deadline on reservation's objects fences

**Parameters**

- `struct dma_resv *obj`: the reservation object
- `enum dma_resv_usage usage`: controls which fences to include, see enum dma_resv_usage.
- `ktime_t deadline`: the requested deadline (MONOTONIC)

**Description**

May be called without holding the dma_resv lock.  Sets **deadline** on
all fences filtered by **usage**.

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

```c
bool dma_resv_test_signaled(struct dma_resv *obj, enum dma_resv_usage usage)
```

Test if a reservation object's fences have been signaled.

**Parameters**

- `struct dma_resv *obj`: the reservation object
- `enum dma_resv_usage usage`: controls which fences to include, see enum dma_resv_usage.

**Description**

Callers are not required to hold specific locks, but maybe hold
[`dma_resv_lock()`](#c-dma_resv_lock) already.

RETURNS

True if all fences signaled, else false.

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

```c
void dma_resv_describe(struct dma_resv *obj, struct seq_file *seq)
```

Dump description of the resv object into seq_file

**Parameters**

- `struct dma_resv *obj`: the reservation object
- `struct seq_file *seq`: the seq_file to dump the description into

**Description**

Dump a textual description of the fences inside an dma_resv object into the
seq_file.



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

how the fences from a dma_resv obj are used

**Constants**

- `DMA_RESV_USAGE_KERNEL`: For in kernel memory management only.

  This should only be used for things like copying or clearing memory
  with a DMA hardware engine for the purpose of kernel memory
  management.

  Drivers *always* must wait for those fences before accessing the
  resource protected by the dma_resv object. The only exception for
  that is when the resource is known to be locked down in place by
  pinning it previously.
- `DMA_RESV_USAGE_WRITE`: Implicit write synchronization.

  This should only be used for userspace command submissions which add
  an implicit write dependency.
- `DMA_RESV_USAGE_READ`: Implicit read synchronization.

  This should only be used for userspace command submissions which add
  an implicit read dependency.
- `DMA_RESV_USAGE_BOOKKEEP`: No implicit sync.

  This should be used by submissions which don't want to participate in
  any implicit synchronization.

  The most common cases are preemption fences, page table updates, TLB
  flushes as well as explicitly synced user submissions.

  Explicitly synced user submissions can be promoted to
  DMA_RESV_USAGE_READ or DMA_RESV_USAGE_WRITE as needed using
  `dma_buf_import_sync_file()` when implicit synchronization should
  become necessary after initial adding of the fence.

**Description**

This enum describes the different use cases for a dma_resv object and
controls which fences are returned when queried.

An important fact is that there is the order KERNEL\<WRITE\<READ\<BOOKKEEP and
when the dma_resv object is asked for fences for one use case the fences
for the lower use case are returned as well.

For example when asking for WRITE fences then the KERNEL fences are returned
as well. Similar when asked for READ fences then both WRITE and KERNEL
fences are returned as well.

Already used fences can be promoted in the sense that a fence with
DMA_RESV_USAGE_BOOKKEEP could become DMA_RESV_USAGE_READ by adding it again
with this usage. But fences can never be degraded in the sense that a fence
with DMA_RESV_USAGE_WRITE could become DMA_RESV_USAGE_READ.

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

```c
enum dma_resv_usage dma_resv_usage_rw(bool write)
```

helper for implicit sync

**Parameters**

- `bool write`: true if we create a new implicit sync write

**Description**

This returns the implicit synchronization usage for write or read accesses,
see enum dma_resv_usage and [`dma_buf.resv`](#c-struct-dma_buf).

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

a reservation object manages fences for a buffer

**Definition**

```c
struct dma_resv {
    struct ww_mutex lock;
    struct dma_resv_list  *fences;
};
```

**Members**

- `lock`: Update side lock. Don't use directly, instead use the wrapper
  functions like [`dma_resv_lock()`](#c-dma_resv_lock) and [`dma_resv_unlock()`](#c-dma_resv_unlock).

  Drivers which use the reservation object to manage memory dynamically
  also use this lock to protect buffer object state like placement,
  allocation policies or throughout command submission.
- `fences`: Array of fences which where added to the dma_resv object

  A new fence is added by calling [`dma_resv_add_fence()`](#c-dma_resv_add_fence). Since this
  often needs to be done past the point of no return in command
  submission it cannot fail, and therefore sufficient slots need to be
  reserved by calling [`dma_resv_reserve_fences()`](#c-dma_resv_reserve_fences).

**Description**

This is a container for dma_fence objects which needs to handle multiple use
cases.

One use is to synchronize cross-driver access to a struct dma_buf, either for
dynamic buffer management or just to handle implicit synchronization between
different users of the buffer in userspace. See [`dma_buf.resv`](#c-struct-dma_buf) for a more
in-depth discussion.

The other major use is to manage access and locking within a driver in a
buffer based memory manager. struct ttm_buffer_object is the canonical
example here, since this is where reservation objects originated from. But
use in drivers is spreading and some drivers also manage struct
drm_gem_object with the same scheme.

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

current position into the dma_resv fences

**Definition**

```c
struct dma_resv_iter {
    struct dma_resv *obj;
    enum dma_resv_usage usage;
    struct dma_fence *fence;
    enum dma_resv_usage fence_usage;
    unsigned int index;
    struct dma_resv_list *fences;
    unsigned int num_fences;
    bool is_restarted;
};
```

**Members**

- `obj`: The dma_resv object we iterate over
- `usage`: Return fences with this usage or lower.
- `fence`: the currently handled fence
- `fence_usage`: the usage of the current fence
- `index`: index into the shared fences
- `fences`: the shared fences; private, *MUST* not dereference
- `num_fences`: number of fences
- `is_restarted`: true if this is the first returned fence

**Description**

Don't touch this directly in the driver, use the accessor function instead.

IMPORTANT

When using the lockless iterators like [`dma_resv_iter_next_unlocked()`](#c-dma_resv_iter_next_unlocked) or
[`dma_resv_for_each_fence_unlocked()`](#c-dma_resv_for_each_fence_unlocked) beware that the iterator can be restarted.
Code which accumulates statistics or similar needs to check for this with
[`dma_resv_iter_is_restarted()`](#c-dma_resv_iter_is_restarted).

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

```c
void dma_resv_iter_begin(struct dma_resv_iter *cursor, struct dma_resv *obj, enum dma_resv_usage usage)
```

initialize a dma_resv_iter object

**Parameters**

- `struct dma_resv_iter *cursor`: The dma_resv_iter object to initialize
- `struct dma_resv *obj`: The dma_resv object which we want to iterate over
- `enum dma_resv_usage usage`: controls which fences to include, see enum dma_resv_usage.

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

```c
void dma_resv_iter_end(struct dma_resv_iter *cursor)
```

cleanup a dma_resv_iter object

**Parameters**

- `struct dma_resv_iter *cursor`: the dma_resv_iter object which should be cleaned up

**Description**

Make sure that the reference to the fence in the cursor is properly
dropped.

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

```c
enum dma_resv_usage dma_resv_iter_usage(struct dma_resv_iter *cursor)
```

Return the usage of the current fence

**Parameters**

- `struct dma_resv_iter *cursor`: the cursor of the current position

**Description**

Returns the usage of the currently processed fence.

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

```c
bool dma_resv_iter_is_restarted(struct dma_resv_iter *cursor)
```

test if this is the first fence after a restart

**Parameters**

- `struct dma_resv_iter *cursor`: the cursor with the current position

**Description**

Return true if this is the first fence in an iteration after a restart.

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

```c
dma_resv_for_each_fence_unlocked(cursor, fence)
```

unlocked fence iterator

**Parameters**

- `cursor`: a struct dma_resv_iter pointer
- `fence`: the current fence

**Description**

Iterate over the fences in a struct dma_resv object without holding the
[`dma_resv.lock`](#c-struct-dma_resv) and using RCU instead. The cursor needs to be initialized
with [`dma_resv_iter_begin()`](#c-dma_resv_iter_begin) and cleaned up with [`dma_resv_iter_end()`](#c-dma_resv_iter_end). Inside
the iterator a reference to the dma_fence is held and the RCU lock dropped.

Beware that the iterator can be restarted when the struct dma_resv for
**cursor** is modified. Code which accumulates statistics or similar needs to
check for this with [`dma_resv_iter_is_restarted()`](#c-dma_resv_iter_is_restarted). For this reason prefer the
lock iterator [`dma_resv_for_each_fence()`](#c-dma_resv_for_each_fence) whenever possible.

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

```c
dma_resv_for_each_fence(cursor, obj, usage, fence)
```

fence iterator

**Parameters**

- `cursor`: a struct dma_resv_iter pointer
- `obj`: a dma_resv object pointer
- `usage`: controls which fences to return
- `fence`: the current fence

**Description**

Iterate over the fences in a struct dma_resv object while holding the
[`dma_resv.lock`](#c-struct-dma_resv). **all_fences** controls if the shared fences are returned as
well. The cursor initialisation is part of the iterator and the fence stays
valid as long as the lock is held and so no extra reference to the fence is
taken.

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

```c
int dma_resv_lock(struct dma_resv *obj, struct ww_acquire_ctx *ctx)
```

lock the reservation object

**Parameters**

- `struct dma_resv *obj`: the reservation object
- `struct ww_acquire_ctx *ctx`: the locking context

**Description**

Locks the reservation object for exclusive access and modification. Note,
that the lock is only against other writers, readers will run concurrently
with a writer under RCU. The seqlock is used to notify readers if they
overlap with a writer.

As the reservation object may be locked by multiple parties in an
undefined order, a #ww_acquire_ctx is passed to unwind if a cycle
is detected. See `ww_mutex_lock()` and `ww_acquire_init()`. A reservation
object may be locked by itself by passing NULL as **ctx**.

When a die situation is indicated by returning -EDEADLK all locks held by
**ctx** must be unlocked and then [`dma_resv_lock_slow()`](#c-dma_resv_lock_slow) called on **obj**.

Unlocked by calling [`dma_resv_unlock()`](#c-dma_resv_unlock).

See also [`dma_resv_lock_interruptible()`](#c-dma_resv_lock_interruptible) for the interruptible variant.

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

```c
int dma_resv_lock_interruptible(struct dma_resv *obj, struct ww_acquire_ctx *ctx)
```

lock the reservation object

**Parameters**

- `struct dma_resv *obj`: the reservation object
- `struct ww_acquire_ctx *ctx`: the locking context

**Description**

Locks the reservation object interruptible for exclusive access and
modification. Note, that the lock is only against other writers, readers
will run concurrently with a writer under RCU. The seqlock is used to
notify readers if they overlap with a writer.

As the reservation object may be locked by multiple parties in an
undefined order, a #ww_acquire_ctx is passed to unwind if a cycle
is detected. See `ww_mutex_lock()` and `ww_acquire_init()`. A reservation
object may be locked by itself by passing NULL as **ctx**.

When a die situation is indicated by returning -EDEADLK all locks held by
**ctx** must be unlocked and then [`dma_resv_lock_slow_interruptible()`](#c-dma_resv_lock_slow_interruptible) called on
**obj**.

Unlocked by calling [`dma_resv_unlock()`](#c-dma_resv_unlock).

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

```c
void dma_resv_lock_slow(struct dma_resv *obj, struct ww_acquire_ctx *ctx)
```

slowpath lock the reservation object

**Parameters**

- `struct dma_resv *obj`: the reservation object
- `struct ww_acquire_ctx *ctx`: the locking context

**Description**

Acquires the reservation object after a die case. This function
will sleep until the lock becomes available. See [`dma_resv_lock()`](#c-dma_resv_lock) as
well.

See also [`dma_resv_lock_slow_interruptible()`](#c-dma_resv_lock_slow_interruptible) for the interruptible variant.

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

```c
int dma_resv_lock_slow_interruptible(struct dma_resv *obj, struct ww_acquire_ctx *ctx)
```

slowpath lock the reservation object, interruptible

**Parameters**

- `struct dma_resv *obj`: the reservation object
- `struct ww_acquire_ctx *ctx`: the locking context

**Description**

Acquires the reservation object interruptible after a die case. This function
will sleep until the lock becomes available. See
[`dma_resv_lock_interruptible()`](#c-dma_resv_lock_interruptible) as well.

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

```c
bool dma_resv_trylock(struct dma_resv *obj)
```

trylock the reservation object

**Parameters**

- `struct dma_resv *obj`: the reservation object

**Description**

Tries to lock the reservation object for exclusive access and modification.
Note, that the lock is only against other writers, readers will run
concurrently with a writer under RCU. The seqlock is used to notify readers
if they overlap with a writer.

Also note that since no context is provided, no deadlock protection is
possible, which is also not needed for a trylock.

Returns true if the lock was acquired, false otherwise.

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

```c
bool dma_resv_is_locked(struct dma_resv *obj)
```

is the reservation object locked

**Parameters**

- `struct dma_resv *obj`: the reservation object

**Description**

Returns true if the mutex is locked, false if unlocked.

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

```c
struct ww_acquire_ctx * dma_resv_locking_ctx(struct dma_resv *obj)
```

returns the context used to lock the object

**Parameters**

- `struct dma_resv *obj`: the reservation object

**Description**

Returns the context used to lock a reservation object or NULL if no context
was used or the object is not locked at all.

WARNING: This interface is pretty horrible, but TTM needs it because it
doesn't pass the struct ww_acquire_ctx around in some very long callchains.
Everyone else just uses it to check whether they're holding a reservation or
not.

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

```c
void dma_resv_unlock(struct dma_resv *obj)
```

unlock the reservation object

**Parameters**

- `struct dma_resv *obj`: the reservation object

**Description**

Unlocks the reservation object following exclusive access.


<a id="rst-dma-fences"></a>

## DMA Fences


DMA fences, represented by [`struct dma_fence`](#c-struct-dma_fence), are the kernel internal
synchronization primitive for DMA operations like GPU rendering, video
encoding/decoding, or displaying buffers on a screen.

A fence is initialized using [`dma_fence_init()`](#c-dma_fence_init) and completed using
[`dma_fence_signal()`](#c-dma_fence_signal). Fences are associated with a context, allocated through
[`dma_fence_context_alloc()`](#c-dma_fence_context_alloc), and all fences on the same context are
fully ordered.

Since the purposes of fences is to facilitate cross-device and
cross-application synchronization, there's multiple ways to use one:

- Individual fences can be exposed as a [`sync_file`](#c-struct-sync_file), accessed as a file
  descriptor from userspace, created by calling [`sync_file_create()`](#c-sync_file_create). This is
  called explicit fencing, since userspace passes around explicit
  synchronization points.

- Some subsystems also have their own explicit fencing primitives, like
  [`drm_syncobj`](/kernel/hardware/gpu/drm-mm.md#c-struct-drm_syncobj). Compared to [`sync_file`](#c-struct-sync_file), a [`drm_syncobj`](/kernel/hardware/gpu/drm-mm.md#c-struct-drm_syncobj) allows the underlying
  fence to be updated.

- Then there's also implicit fencing, where the synchronization points are
  implicitly passed around as part of shared [`dma_buf`](#c-struct-dma_buf) instances. Such
  implicit fences are stored in [`struct dma_resv`](#c-struct-dma_resv) through the
  [`dma_buf.resv`](#c-struct-dma_buf) pointer.


<a id="rst-dma-fence-cross-driver-contract"></a>

### DMA Fence Cross-Driver Contract


Since [`dma_fence`](#c-struct-dma_fence) provide a cross driver contract, all drivers must follow the
same rules:

* Fences must complete in a reasonable time. Fences which represent kernels
  and shaders submitted by userspace, which could run forever, must be backed
  up by timeout and gpu hang recovery code. Minimally that code must prevent
  further command submission and force complete all in-flight fences, e.g.
  when the driver or hardware do not support gpu reset, or if the gpu reset
  failed for some reason. Ideally the driver supports gpu recovery which only
  affects the offending userspace context, and no other userspace
  submissions.

* Drivers may have different ideas of what completion within a reasonable
  time means. Some hang recovery code uses a fixed timeout, others a mix
  between observing forward progress and increasingly strict timeouts.
  Drivers should not try to second guess timeout handling of fences from
  other drivers.

* To ensure there's no deadlocks of [`dma_fence_wait()`](#c-dma_fence_wait) against other locks
  drivers should annotate all code required to reach [`dma_fence_signal()`](#c-dma_fence_signal),
  which completes the fences, with [`dma_fence_begin_signalling()`](#c-dma_fence_begin_signalling) and
  [`dma_fence_end_signalling()`](#c-dma_fence_end_signalling).

* Drivers are allowed to call [`dma_fence_wait()`](#c-dma_fence_wait) while holding [`dma_resv_lock()`](#c-dma_resv_lock).
  This means any code required for fence completion cannot acquire a
  [`dma_resv`](#c-struct-dma_resv) lock. Note that this also pulls in the entire established
  locking hierarchy around [`dma_resv_lock()`](#c-dma_resv_lock) and [`dma_resv_unlock()`](#c-dma_resv_unlock).

* Drivers are allowed to call [`dma_fence_wait()`](#c-dma_fence_wait) from their `shrinker`
  callbacks. This means any code required for fence completion cannot
  allocate memory with GFP_KERNEL.

* Drivers are allowed to call [`dma_fence_wait()`](#c-dma_fence_wait) from their `mmu_notifier`
  respectively `mmu_interval_notifier` callbacks. This means any code required
  for fence completion cannot allocate memory with GFP_NOFS or GFP_NOIO.
  Only GFP_ATOMIC is permissible, which might fail.

Note that only GPU drivers have a reasonable excuse for both requiring
`mmu_interval_notifier` and `shrinker` callbacks at the same time as having to
track asynchronous compute work using [`dma_fence`](#c-struct-dma_fence). No driver outside of
drivers/gpu should ever call [`dma_fence_wait()`](#c-dma_fence_wait) in such contexts.


<a id="rst-dma-fence-signalling-annotations"></a>

### DMA Fence Signalling Annotations


Proving correctness of all the kernel code around [`dma_fence`](#c-struct-dma_fence) through code
review and testing is tricky for a few reasons:

* It is a cross-driver contract, and therefore all drivers must follow the
  same rules for lock nesting order, calling contexts for various functions
  and anything else significant for in-kernel interfaces. But it is also
  impossible to test all drivers in a single machine, hence brute-force N vs.
  N testing of all combinations is impossible. Even just limiting to the
  possible combinations is infeasible.

* There is an enormous amount of driver code involved. For render drivers
  there's the tail of command submission, after fences are published,
  scheduler code, interrupt and workers to process job completion,
  and timeout, gpu reset and gpu hang recovery code. Plus for integration
  with core mm with have `mmu_notifier`, respectively `mmu_interval_notifier`,
  and `shrinker`. For modesetting drivers there's the commit tail functions
  between when fences for an atomic modeset are published, and when the
  corresponding vblank completes, including any interrupt processing and
  related workers. Auditing all that code, across all drivers, is not
  feasible.

* Due to how many other subsystems are involved and the locking hierarchies
  this pulls in there is extremely thin wiggle-room for driver-specific
  differences. [`dma_fence`](#c-struct-dma_fence) interacts with almost all of the core memory
  handling through page fault handlers via [`dma_resv`](#c-struct-dma_resv), [`dma_resv_lock()`](#c-dma_resv_lock) and
  [`dma_resv_unlock()`](#c-dma_resv_unlock). On the other side it also interacts through all
  allocation sites through `mmu_notifier` and `shrinker`.

Furthermore lockdep does not handle cross-release dependencies, which means
any deadlocks between [`dma_fence_wait()`](#c-dma_fence_wait) and [`dma_fence_signal()`](#c-dma_fence_signal) can't be caught
at runtime with some quick testing. The simplest example is one thread
waiting on a [`dma_fence`](#c-struct-dma_fence) while holding a lock:

```text
lock(A);
dma_fence_wait(B);
unlock(A);
```

while the other thread is stuck trying to acquire the same lock, which
prevents it from signalling the fence the previous thread is stuck waiting
on:

```text
lock(A);
unlock(A);
dma_fence_signal(B);
```

By manually annotating all code relevant to signalling a [`dma_fence`](#c-struct-dma_fence) we can
teach lockdep about these dependencies, which also helps with the validation
headache since now lockdep can check all the rules for us:

```text
cookie = dma_fence_begin_signalling();
lock(A);
unlock(A);
dma_fence_signal(B);
dma_fence_end_signalling(cookie);
```

For using [`dma_fence_begin_signalling()`](#c-dma_fence_begin_signalling) and [`dma_fence_end_signalling()`](#c-dma_fence_end_signalling) to
annotate critical sections the following rules need to be observed:

* All code necessary to complete a [`dma_fence`](#c-struct-dma_fence) must be annotated, from the
  point where a fence is accessible to other threads, to the point where
  [`dma_fence_signal()`](#c-dma_fence_signal) is called. Un-annotated code can contain deadlock issues,
  and due to the very strict rules and many corner cases it is infeasible to
  catch these just with review or normal stress testing.

* [`struct dma_resv`](#c-struct-dma_resv) deserves a special note, since the readers are only
  protected by rcu. This means the signalling critical section starts as soon
  as the new fences are installed, even before [`dma_resv_unlock()`](#c-dma_resv_unlock) is called.

* The only exception are fast paths and opportunistic signalling code, which
  calls [`dma_fence_signal()`](#c-dma_fence_signal) purely as an optimization, but is not required to
  guarantee completion of a [`dma_fence`](#c-struct-dma_fence). The usual example is a wait IOCTL
  which calls [`dma_fence_signal()`](#c-dma_fence_signal), while the mandatory completion path goes
  through a hardware interrupt and possible job completion worker.

* To aid composability of code, the annotations can be freely nested, as long
  as the overall locking hierarchy is consistent. The annotations also work
  both in interrupt and process context. Due to implementation details this
  requires that callers pass an opaque cookie from
  [`dma_fence_begin_signalling()`](#c-dma_fence_begin_signalling) to [`dma_fence_end_signalling()`](#c-dma_fence_end_signalling).

* Validation against the cross driver contract is implemented by priming
  lockdep with the relevant hierarchy at boot-up. This means even just
  testing with a single device is enough to validate a driver, at least as
  far as deadlocks with [`dma_fence_wait()`](#c-dma_fence_wait) against [`dma_fence_signal()`](#c-dma_fence_signal) are
  concerned.


<a id="rst-dma-fence-deadline-hints"></a>

### DMA Fence Deadline Hints


In an ideal world, it would be possible to pipeline a workload sufficiently
that a utilization based device frequency governor could arrive at a minimum
frequency that meets the requirements of the use-case, in order to minimize
power consumption.  But in the real world there are many workloads which
defy this ideal.  For example, but not limited to:

* Workloads that ping-pong between device and CPU, with alternating periods
  of CPU waiting for device, and device waiting on CPU.  This can result in
  devfreq and cpufreq seeing idle time in their respective domains and in
  result reduce frequency.

* Workloads that interact with a periodic time based deadline, such as double
  buffered GPU rendering vs vblank sync'd page flipping.  In this scenario,
  missing a vblank deadline results in an *increase* in idle time on the GPU
  (since it has to wait an additional vblank period), sending a signal to
  the GPU's devfreq to reduce frequency, when in fact the opposite is what is
  needed.

To this end, deadline hint(s) can be set on a [`dma_fence`](#c-struct-dma_fence) via [`dma_fence_set_deadline`](#c-dma_fence_set_deadline)
(or indirectly via userspace facing ioctls like [`sync_set_deadline`](#c-struct-sync_set_deadline)).
The deadline hint provides a way for the waiting driver, or userspace, to
convey an appropriate sense of urgency to the signaling driver.

A deadline hint is given in absolute ktime (CLOCK_MONOTONIC for userspace
facing APIs).  The time could either be some point in the future (such as
the vblank based deadline for page-flipping, or the start of a compositor's
composition cycle), or the current time to indicate an immediate deadline
hint (Ie. forward progress cannot be made until this fence is signaled).

Multiple deadlines may be set on a given fence, even in parallel.  See the
documentation for [`dma_fence_ops.set_deadline`](#c-struct-dma_fence_ops).

The deadline hint is just that, a hint.  The driver that created the fence
may react by increasing frequency, making different scheduling choices, etc.
Or doing nothing at all.


<a id="rst-dma-fences-functions-reference"></a>

### DMA Fences Functions Reference


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

```c
struct dma_fence * dma_fence_get_stub(void)
```

return a signaled fence

**Parameters**

- `void`: no arguments

**Description**

Return a stub fence which is already signaled. The fence's timestamp
corresponds to the initialisation time of the linux kernel.

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

```c
struct dma_fence * dma_fence_allocate_private_stub(ktime_t timestamp)
```

return a private, signaled fence

**Parameters**

- `ktime_t timestamp`: timestamp when the fence was signaled

**Description**

Return a newly allocated and signaled stub fence.

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

```c
u64 dma_fence_context_alloc(unsigned num)
```

allocate an array of fence contexts

**Parameters**

- `unsigned num`: amount of contexts to allocate

**Description**

This function will return the first index of the number of fence contexts
allocated.  The fence context is used for setting [`dma_fence.context`](#c-struct-dma_fence) to a
unique number by passing the context to [`dma_fence_init()`](#c-dma_fence_init).

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

```c
bool dma_fence_begin_signalling(void)
```

begin a critical DMA fence signalling section

**Parameters**

- `void`: no arguments

**Description**

Drivers should use this to annotate the beginning of any code section
required to eventually complete [`dma_fence`](#c-struct-dma_fence) by calling [`dma_fence_signal()`](#c-dma_fence_signal).

The end of these critical sections are annotated with
[`dma_fence_end_signalling()`](#c-dma_fence_end_signalling).

Opaque cookie needed by the implementation, which needs to be passed to
[`dma_fence_end_signalling()`](#c-dma_fence_end_signalling).

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

```c
void dma_fence_end_signalling(bool cookie)
```

end a critical DMA fence signalling section

**Parameters**

- `bool cookie`: opaque cookie from [`dma_fence_begin_signalling()`](#c-dma_fence_begin_signalling)

**Description**

Closes a critical section annotation opened by [`dma_fence_begin_signalling()`](#c-dma_fence_begin_signalling).

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

```c
void dma_fence_signal_timestamp_locked(struct dma_fence *fence, ktime_t timestamp)
```

signal completion of a fence

**Parameters**

- `struct dma_fence *fence`: the fence to signal
- `ktime_t timestamp`: fence signal timestamp in kernel's CLOCK_MONOTONIC time domain

**Description**

Signal completion for software callbacks on a fence, this will unblock
[`dma_fence_wait()`](#c-dma_fence_wait) calls and run all the callbacks added with
[`dma_fence_add_callback()`](#c-dma_fence_add_callback). Can be called multiple times, but since a fence
can only go from the unsignaled to the signaled state and not back, it will
only be effective the first time. Set the timestamp provided as the fence
signal timestamp.

Unlike [`dma_fence_signal_timestamp()`](#c-dma_fence_signal_timestamp), this function must be called with
[`dma_fence.lock`](#c-struct-dma_fence) held.

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

```c
void dma_fence_signal_timestamp(struct dma_fence *fence, ktime_t timestamp)
```

signal completion of a fence

**Parameters**

- `struct dma_fence *fence`: the fence to signal
- `ktime_t timestamp`: fence signal timestamp in kernel's CLOCK_MONOTONIC time domain

**Description**

Signal completion for software callbacks on a fence, this will unblock
[`dma_fence_wait()`](#c-dma_fence_wait) calls and run all the callbacks added with
[`dma_fence_add_callback()`](#c-dma_fence_add_callback). Can be called multiple times, but since a fence
can only go from the unsignaled to the signaled state and not back, it will
only be effective the first time. Set the timestamp provided as the fence
signal timestamp.

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

```c
void dma_fence_signal_locked(struct dma_fence *fence)
```

signal completion of a fence

**Parameters**

- `struct dma_fence *fence`: the fence to signal

**Description**

Signal completion for software callbacks on a fence, this will unblock
[`dma_fence_wait()`](#c-dma_fence_wait) calls and run all the callbacks added with
[`dma_fence_add_callback()`](#c-dma_fence_add_callback). Can be called multiple times, but since a fence
can only go from the unsignaled to the signaled state and not back, it will
only be effective the first time.

Unlike [`dma_fence_signal()`](#c-dma_fence_signal), this function must be called with [`dma_fence.lock`](#c-struct-dma_fence)
held.

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

```c
bool dma_fence_check_and_signal_locked(struct dma_fence *fence)
```

signal the fence if it's not yet signaled

**Parameters**

- `struct dma_fence *fence`: the fence to check and signal

**Description**

Checks whether a fence was signaled and signals it if it was not yet signaled.

Unlike [`dma_fence_check_and_signal()`](#c-dma_fence_check_and_signal), this function must be called with
[`struct dma_fence`](#c-struct-dma_fence).lock being held.

**Return**

true if fence has been signaled already, false otherwise.

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

```c
bool dma_fence_check_and_signal(struct dma_fence *fence)
```

signal the fence if it's not yet signaled

**Parameters**

- `struct dma_fence *fence`: the fence to check and signal

**Description**

Checks whether a fence was signaled and signals it if it was not yet signaled.
All this is done in a race-free manner.

**Return**

true if fence has been signaled already, false otherwise.

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

```c
void dma_fence_signal(struct dma_fence *fence)
```

signal completion of a fence

**Parameters**

- `struct dma_fence *fence`: the fence to signal

**Description**

Signal completion for software callbacks on a fence, this will unblock
[`dma_fence_wait()`](#c-dma_fence_wait) calls and run all the callbacks added with
[`dma_fence_add_callback()`](#c-dma_fence_add_callback). Can be called multiple times, but since a fence
can only go from the unsignaled to the signaled state and not back, it will
only be effective the first time.

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

```c
signed long dma_fence_wait_timeout(struct dma_fence *fence, bool intr, signed long timeout)
```

sleep until the fence gets signaled or until timeout elapses

**Parameters**

- `struct dma_fence *fence`: the fence to wait on
- `bool intr`: if true, do an interruptible wait
- `signed long timeout`: timeout value in jiffies, or MAX_SCHEDULE_TIMEOUT

**Description**

Returns -ERESTARTSYS if interrupted, 0 if the wait timed out, or the
remaining timeout in jiffies on success. Other error values may be
returned on custom implementations.

Performs a synchronous wait on this fence. It is assumed the caller
directly or indirectly (buf-mgr between reservation and committing)
holds a reference to the fence, otherwise the fence might be
freed before return, resulting in undefined behavior.

See also [`dma_fence_wait()`](#c-dma_fence_wait) and [`dma_fence_wait_any_timeout()`](#c-dma_fence_wait_any_timeout).

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

```c
void dma_fence_release(struct kref *kref)
```

default release function for fences

**Parameters**

- `struct kref *kref`: [`dma_fence.recfount`](#c-struct-dma_fence)

**Description**

This is the default release functions for [`dma_fence`](#c-struct-dma_fence). Drivers shouldn't call
this directly, but instead call [`dma_fence_put()`](#c-dma_fence_put).

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

```c
void dma_fence_free(struct dma_fence *fence)
```

default release function for [`dma_fence`](#c-struct-dma_fence).

**Parameters**

- `struct dma_fence *fence`: fence to release

**Description**

This is the default implementation for [`dma_fence_ops.release`](#c-struct-dma_fence_ops). It calls
[`kfree_rcu()`](/kernel/internals/core-api/kernel-api.md#c-kfree_rcu) on **fence**.

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

```c
void dma_fence_enable_sw_signaling(struct dma_fence *fence)
```

enable signaling on fence

**Parameters**

- `struct dma_fence *fence`: the fence to enable

**Description**

This will request for sw signaling to be enabled, to make the fence
complete as soon as possible. This calls [`dma_fence_ops.enable_signaling`](#c-struct-dma_fence_ops)
internally.

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

```c
int dma_fence_add_callback(struct dma_fence *fence, struct dma_fence_cb *cb, dma_fence_func_t func)
```

add a callback to be called when the fence is signaled

**Parameters**

- `struct dma_fence *fence`: the fence to wait on
- `struct dma_fence_cb *cb`: the callback to register
- `dma_fence_func_t func`: the function to call

**Description**

Add a software callback to the fence. The caller should keep a reference to
the fence.

**cb** will be initialized by [`dma_fence_add_callback()`](#c-dma_fence_add_callback), no initialization
by the caller is required. Any number of callbacks can be registered
to a fence, but a callback can only be registered to one fence at a time.

If fence is already signaled, this function will return -ENOENT (and
*not* call the callback).

Note that the callback can be called from an atomic context or irq context.

Returns 0 in case of success, -ENOENT if the fence is already signaled
and -EINVAL in case of error.

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

```c
int dma_fence_get_status(struct dma_fence *fence)
```

returns the status upon completion

**Parameters**

- `struct dma_fence *fence`: the dma_fence to query

**Description**

This wraps [`dma_fence_get_status_locked()`](#c-dma_fence_get_status_locked) to return the error status
condition on a signaled fence. See [`dma_fence_get_status_locked()`](#c-dma_fence_get_status_locked) for more
details.

Returns 0 if the fence has not yet been signaled, 1 if the fence has
been signaled without an error condition, or a negative error code
if the fence has been completed in err.

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

```c
bool dma_fence_remove_callback(struct dma_fence *fence, struct dma_fence_cb *cb)
```

remove a callback from the signaling list

**Parameters**

- `struct dma_fence *fence`: the fence to wait on
- `struct dma_fence_cb *cb`: the callback to remove

**Description**

Remove a previously queued callback from the fence. This function returns
true if the callback is successfully removed, or false if the fence has
already been signaled.

*WARNING*:
Cancelling a callback should only be done if you really know what you're
doing, since deadlocks and race conditions could occur all too easily. For
this reason, it should only ever be done on hardware lockup recovery,
with a reference held to the fence.

Behaviour is undefined if **cb** has not been added to **fence** using
[`dma_fence_add_callback()`](#c-dma_fence_add_callback) beforehand.

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

```c
signed long dma_fence_default_wait(struct dma_fence *fence, bool intr, signed long timeout)
```

default sleep until the fence gets signaled or until timeout elapses

**Parameters**

- `struct dma_fence *fence`: the fence to wait on
- `bool intr`: if true, do an interruptible wait
- `signed long timeout`: timeout value in jiffies, or MAX_SCHEDULE_TIMEOUT

**Description**

Returns -ERESTARTSYS if interrupted, 0 if the wait timed out, or the
remaining timeout in jiffies on success. If timeout is zero the value one is
returned if the fence is already signaled for consistency with other
functions taking a jiffies timeout.

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

```c
signed long dma_fence_wait_any_timeout(struct dma_fence **fences, uint32_t count, bool intr, signed long timeout, uint32_t *idx)
```

sleep until any fence gets signaled or until timeout elapses

**Parameters**

- `struct dma_fence **fences`: array of fences to wait on
- `uint32_t count`: number of fences to wait on
- `bool intr`: if true, do an interruptible wait
- `signed long timeout`: timeout value in jiffies, or MAX_SCHEDULE_TIMEOUT
- `uint32_t *idx`: used to store the first signaled fence index, meaningful only on
  positive return

**Description**

Returns -EINVAL on custom fence wait implementation, -ERESTARTSYS if
interrupted, 0 if the wait timed out, or the remaining timeout in jiffies
on success.

Synchronous waits for the first fence in the array to be signaled. The
caller needs to hold a reference to all fences in the array, otherwise a
fence might be freed before return, resulting in undefined behavior.

See also [`dma_fence_wait()`](#c-dma_fence_wait) and [`dma_fence_wait_timeout()`](#c-dma_fence_wait_timeout).

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

```c
void dma_fence_set_deadline(struct dma_fence *fence, ktime_t deadline)
```

set desired fence-wait deadline hint

**Parameters**

- `struct dma_fence *fence`: the fence that is to be waited on
- `ktime_t deadline`: the time by which the waiter hopes for the fence to be
  signaled

**Description**

Give the fence signaler a hint about an upcoming deadline, such as
vblank, by which point the waiter would prefer the fence to be
signaled by.  This is intended to give feedback to the fence signaler
to aid in power management decisions, such as boosting GPU frequency
if a periodic vblank deadline is approaching but the fence is not
yet signaled..

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

```c
void dma_fence_describe(struct dma_fence *fence, struct seq_file *seq)
```

Dump fence description into seq_file

**Parameters**

- `struct dma_fence *fence`: the fence to describe
- `struct seq_file *seq`: the seq_file to put the textual description into

**Description**

Dump a textual description of the fence and it's state into the seq_file.

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

```c
void dma_fence_init(struct dma_fence *fence, const struct dma_fence_ops *ops, spinlock_t *lock, u64 context, u64 seqno)
```

Initialize a custom fence.

**Parameters**

- `struct dma_fence *fence`: the fence to initialize
- `const struct dma_fence_ops *ops`: the dma_fence_ops for operations on this fence
- `spinlock_t *lock`: the irqsafe spinlock to use for locking this fence
- `u64 context`: the execution context this fence is run on
- `u64 seqno`: a linear increasing sequence number for this context

**Description**

Initializes an allocated fence, the caller doesn't have to keep its
refcount after committing with this fence, but it will need to hold a
refcount again if [`dma_fence_ops.enable_signaling`](#c-struct-dma_fence_ops) gets called.

context and seqno are used for easy comparison between fences, allowing
to check which fence is later by simply using [`dma_fence_later()`](#c-dma_fence_later).

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

```c
void dma_fence_init64(struct dma_fence *fence, const struct dma_fence_ops *ops, spinlock_t *lock, u64 context, u64 seqno)
```

Initialize a custom fence with 64-bit seqno support.

**Parameters**

- `struct dma_fence *fence`: the fence to initialize
- `const struct dma_fence_ops *ops`: the dma_fence_ops for operations on this fence
- `spinlock_t *lock`: the irqsafe spinlock to use for locking this fence
- `u64 context`: the execution context this fence is run on
- `u64 seqno`: a linear increasing sequence number for this context

**Description**

Initializes an allocated fence, the caller doesn't have to keep its
refcount after committing with this fence, but it will need to hold a
refcount again if [`dma_fence_ops.enable_signaling`](#c-struct-dma_fence_ops) gets called.

Context and seqno are used for easy comparison between fences, allowing
to check which fence is later by simply using [`dma_fence_later()`](#c-dma_fence_later).

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

```c
const char __rcu * dma_fence_driver_name(struct dma_fence *fence)
```

Access the driver name

**Parameters**

- `struct dma_fence *fence`: the fence to query

**Description**

Returns a driver name backing the dma-fence implementation.

IMPORTANT CONSIDERATION:
Dma-fence contract stipulates that access to driver provided data (data not
directly embedded into the object itself), such as the [`dma_fence.lock`](#c-struct-dma_fence) and
memory potentially accessed by the [`dma_fence.ops`](#c-struct-dma_fence) functions, is forbidden
after the fence has been signalled. Drivers are allowed to free that data,
and some do.

To allow safe access drivers are mandated to guarantee a RCU grace period
between signalling the fence and freeing said data.

As such access to the driver name is only valid inside a RCU locked section.
The pointer MUST be both queried and USED ONLY WITHIN a SINGLE block guarded
by the [`rcu_read_lock`](/kernel/internals/core-api/kernel-api.md#c-rcu_read_lock) and [`rcu_read_unlock`](/kernel/internals/core-api/kernel-api.md#c-rcu_read_unlock) pair.

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

```c
const char __rcu * dma_fence_timeline_name(struct dma_fence *fence)
```

Access the timeline name

**Parameters**

- `struct dma_fence *fence`: the fence to query

**Description**

Returns a timeline name provided by the dma-fence implementation.

IMPORTANT CONSIDERATION:
Dma-fence contract stipulates that access to driver provided data (data not
directly embedded into the object itself), such as the [`dma_fence.lock`](#c-struct-dma_fence) and
memory potentially accessed by the [`dma_fence.ops`](#c-struct-dma_fence) functions, is forbidden
after the fence has been signalled. Drivers are allowed to free that data,
and some do.

To allow safe access drivers are mandated to guarantee a RCU grace period
between signalling the fence and freeing said data.

As such access to the driver name is only valid inside a RCU locked section.
The pointer MUST be both queried and USED ONLY WITHIN a SINGLE block guarded
by the [`rcu_read_lock`](/kernel/internals/core-api/kernel-api.md#c-rcu_read_lock) and [`rcu_read_unlock`](/kernel/internals/core-api/kernel-api.md#c-rcu_read_unlock) pair.



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

software synchronization primitive

**Definition**

```c
struct dma_fence {
    spinlock_t *lock;
    const struct dma_fence_ops *ops;
    union {
        struct list_head cb_list;
        ktime_t timestamp;
        struct rcu_head rcu;
    };
    u64 context;
    u64 seqno;
    unsigned long flags;
    struct kref refcount;
    int error;
};
```

**Members**

- `lock`: spin_lock_irqsave used for locking
- `ops`: dma_fence_ops associated with this fence
- `{unnamed_union}`: anonymous
- `cb_list`: list of all callbacks to call
- `timestamp`: Timestamp when the fence was signaled.
- `rcu`: used for releasing fence with kfree_rcu
- `context`: execution context this fence belongs to, returned by
  [`dma_fence_context_alloc()`](#c-dma_fence_context_alloc)
- `seqno`: the sequence number of this fence inside the execution context,
  can be compared to decide which fence would be signaled later.
- `flags`: A mask of DMA_FENCE_FLAG_* defined below
- `refcount`: refcount for this fence
- `error`: Optional, only valid if \< 0, must be set before calling
  dma_fence_signal, indicates that the fence has completed with an error.

**Description**

the flags member must be manipulated and read using the appropriate
atomic ops (bit_*), so taking the spinlock will not be needed most
of the time.

DMA_FENCE_FLAG_SIGNALED_BIT - fence is already signaled
DMA_FENCE_FLAG_TIMESTAMP_BIT - timestamp recorded for fence signaling
DMA_FENCE_FLAG_ENABLE_SIGNAL_BIT - enable_signaling might have been called
DMA_FENCE_FLAG_USER_BITS - start of the unused bits, can be used by the
implementer of the fence for its own purposes. Can be used in different
ways by different fence implementers, so do not rely on this.

Since atomic bitops are used, this is not guaranteed to be the case.
Particularly, if the bit was set, but dma_fence_signal was called right
before this bit was set, it would have been able to set the
DMA_FENCE_FLAG_SIGNALED_BIT, before enable_signaling was called.
Adding a check for DMA_FENCE_FLAG_SIGNALED_BIT after setting
DMA_FENCE_FLAG_ENABLE_SIGNAL_BIT closes this race, and makes sure that
after dma_fence_signal was called, any enable_signaling call will have either
been completed, or never called at all.

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

callback for [`dma_fence_add_callback()`](#c-dma_fence_add_callback)

**Definition**

```c
struct dma_fence_cb {
    struct list_head node;
    dma_fence_func_t func;
};
```

**Members**

- `node`: used by [`dma_fence_add_callback()`](#c-dma_fence_add_callback) to append this struct to fence::cb_list
- `func`: dma_fence_func_t to call

**Description**

This struct will be initialized by [`dma_fence_add_callback()`](#c-dma_fence_add_callback), additional
data can be passed along by embedding dma_fence_cb in another struct.

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

operations implemented for fence

**Definition**

```c
struct dma_fence_ops {
    const char * (*get_driver_name)(struct dma_fence *fence);
    const char * (*get_timeline_name)(struct dma_fence *fence);
    bool (*enable_signaling)(struct dma_fence *fence);
    bool (*signaled)(struct dma_fence *fence);
    signed long (*wait)(struct dma_fence *fence, bool intr, signed long timeout);
    void (*release)(struct dma_fence *fence);
    void (*set_deadline)(struct dma_fence *fence, ktime_t deadline);
};
```

**Members**

- `get_driver_name`: Returns the driver name. This is a callback to allow drivers to
  compute the name at runtime, without having it to store permanently
  for each fence, or build a cache of some sort.

  This callback is mandatory.
- `get_timeline_name`: Return the name of the context this fence belongs to. This is a
  callback to allow drivers to compute the name at runtime, without
  having it to store permanently for each fence, or build a cache of
  some sort.

  This callback is mandatory.
- `enable_signaling`: Enable software signaling of fence.

  For fence implementations that have the capability for hw->hw
  signaling, they can implement this op to enable the necessary
  interrupts, or insert commands into cmdstream, etc, to avoid these
  costly operations for the common case where only hw->hw
  synchronization is required.  This is called in the first
  [`dma_fence_wait()`](#c-dma_fence_wait) or [`dma_fence_add_callback()`](#c-dma_fence_add_callback) path to let the fence
  implementation know that there is another driver waiting on the
  signal (ie. hw->sw case).

  This is called with irq's disabled, so only spinlocks which disable
  IRQ's can be used in the code outside of this callback.

  A return value of false indicates the fence already passed,
  or some failure occurred that made it impossible to enable
  signaling. True indicates successful enabling.

  [`dma_fence.error`](#c-struct-dma_fence) may be set in enable_signaling, but only when false
  is returned.

  Since many implementations can call [`dma_fence_signal()`](#c-dma_fence_signal) even when before
  **enable_signaling** has been called there's a race window, where the
  [`dma_fence_signal()`](#c-dma_fence_signal) might result in the final fence reference being
  released and its memory freed. To avoid this, implementations of this
  callback should grab their own reference using [`dma_fence_get()`](#c-dma_fence_get), to be
  released when the fence is signalled (through e.g. the interrupt
  handler).

  This callback is optional. If this callback is not present, then the
  driver must always have signaling enabled.
- `signaled`: Peek whether the fence is signaled, as a fastpath optimization for
  e.g. [`dma_fence_wait()`](#c-dma_fence_wait) or [`dma_fence_add_callback()`](#c-dma_fence_add_callback). Note that this
  callback does not need to make any guarantees beyond that a fence
  once indicates as signalled must always return true from this
  callback. This callback may return false even if the fence has
  completed already, in this case information hasn't propogated throug
  the system yet. See also [`dma_fence_is_signaled()`](#c-dma_fence_is_signaled).

  May set [`dma_fence.error`](#c-struct-dma_fence) if returning true.

  This callback is optional.
- `wait`: Custom wait implementation, defaults to [`dma_fence_default_wait()`](#c-dma_fence_default_wait) if
  not set.

  Deprecated and should not be used by new implementations. Only used
  by existing implementations which need special handling for their
  hardware reset procedure.

  Must return -ERESTARTSYS if the wait is intr = true and the wait was
  interrupted, and remaining jiffies if fence has signaled, or 0 if wait
  timed out. Can also return other error values on custom implementations,
  which should be treated as if the fence is signaled. For example a hardware
  lockup could be reported like that.
- `release`: Called on destruction of fence to release additional resources.
  Can be called from irq context.  This callback is optional. If it is
  NULL, then [`dma_fence_free()`](#c-dma_fence_free) is instead called as the default
  implementation.
- `set_deadline`: Callback to allow a fence waiter to inform the fence signaler of
  an upcoming deadline, such as vblank, by which point the waiter
  would prefer the fence to be signaled by.  This is intended to
  give feedback to the fence signaler to aid in power management
  decisions, such as boosting GPU frequency.

  This is called without [`dma_fence.lock`](#c-struct-dma_fence) held, it can be called
  multiple times and from any context.  Locking is up to the callee
  if it has some state to manage.  If multiple deadlines are set,
  the expectation is to track the soonest one.  If the deadline is
  before the current time, it should be interpreted as an immediate
  deadline.

  This callback is optional.

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

```c
void dma_fence_put(struct dma_fence *fence)
```

decreases refcount of the fence

**Parameters**

- `struct dma_fence *fence`: fence to reduce refcount of

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

```c
struct dma_fence * dma_fence_get(struct dma_fence *fence)
```

increases refcount of the fence

**Parameters**

- `struct dma_fence *fence`: fence to increase refcount of

**Description**

Returns the same fence, with refcount increased by 1.

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

```c
struct dma_fence * dma_fence_get_rcu(struct dma_fence *fence)
```

get a fence from a dma_resv_list with rcu read lock

**Parameters**

- `struct dma_fence *fence`: fence to increase refcount of

**Description**

Function returns NULL if no refcount could be obtained, or the fence.

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

```c
struct dma_fence * dma_fence_get_rcu_safe(struct dma_fence __rcu **fencep)
```

acquire a reference to an RCU tracked fence

**Parameters**

- `struct dma_fence __rcu **fencep`: pointer to fence to increase refcount of

**Description**

Function returns NULL if no refcount could be obtained, or the fence.
This function handles acquiring a reference to a fence that may be
reallocated within the RCU grace period (such as with SLAB_TYPESAFE_BY_RCU),
so long as the caller is using RCU on the pointer to the fence.

An alternative mechanism is to employ a seqlock to protect a bunch of
fences, such as used by struct dma_resv. When using a seqlock,
the seqlock must be taken before and checked after a reference to the
fence is acquired (as shown here).

The caller is required to hold the RCU read lock.

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

```c
bool dma_fence_is_signaled_locked(struct dma_fence *fence)
```

Return an indication if the fence is signaled yet.

**Parameters**

- `struct dma_fence *fence`: the fence to check

**Description**

Returns true if the fence was already signaled, false if not. Since this
function doesn't enable signaling, it is not guaranteed to ever return
true if [`dma_fence_add_callback()`](#c-dma_fence_add_callback), [`dma_fence_wait()`](#c-dma_fence_wait) or
[`dma_fence_enable_sw_signaling()`](#c-dma_fence_enable_sw_signaling) haven't been called before.

This function requires [`dma_fence.lock`](#c-struct-dma_fence) to be held.

See also [`dma_fence_is_signaled()`](#c-dma_fence_is_signaled).

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

```c
bool dma_fence_is_signaled(struct dma_fence *fence)
```

Return an indication if the fence is signaled yet.

**Parameters**

- `struct dma_fence *fence`: the fence to check

**Description**

Returns true if the fence was already signaled, false if not. Since this
function doesn't enable signaling, it is not guaranteed to ever return
true if [`dma_fence_add_callback()`](#c-dma_fence_add_callback), [`dma_fence_wait()`](#c-dma_fence_wait) or
[`dma_fence_enable_sw_signaling()`](#c-dma_fence_enable_sw_signaling) haven't been called before.

It's recommended for seqno fences to call dma_fence_signal when the
operation is complete, it makes it possible to prevent issues from
wraparound between time of issue and time of use by checking the return
value of this function before calling hardware-specific wait instructions.

See also [`dma_fence_is_signaled_locked()`](#c-dma_fence_is_signaled_locked).

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

```c
bool __dma_fence_is_later(struct dma_fence *fence, u64 f1, u64 f2)
```

return if f1 is chronologically later than f2

**Parameters**

- `struct dma_fence *fence`: fence in whose context to do the comparison
- `u64 f1`: the first fence's seqno
- `u64 f2`: the second fence's seqno from the same context

**Description**

Returns true if f1 is chronologically later than f2. Both fences must be
from the same context, since a seqno is not common across contexts.

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

```c
bool dma_fence_is_later(struct dma_fence *f1, struct dma_fence *f2)
```

return if f1 is chronologically later than f2

**Parameters**

- `struct dma_fence *f1`: the first fence from the same context
- `struct dma_fence *f2`: the second fence from the same context

**Description**

Returns true if f1 is chronologically later than f2. Both fences must be
from the same context, since a seqno is not re-used across contexts.

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

```c
bool dma_fence_is_later_or_same(struct dma_fence *f1, struct dma_fence *f2)
```

return true if f1 is later or same as f2

**Parameters**

- `struct dma_fence *f1`: the first fence from the same context
- `struct dma_fence *f2`: the second fence from the same context

**Description**

Returns true if f1 is chronologically later than f2 or the same fence. Both
fences must be from the same context, since a seqno is not re-used across
contexts.

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

```c
struct dma_fence * dma_fence_later(struct dma_fence *f1, struct dma_fence *f2)
```

return the chronologically later fence

**Parameters**

- `struct dma_fence *f1`: the first fence from the same context
- `struct dma_fence *f2`: the second fence from the same context

**Description**

Returns NULL if both fences are signaled, otherwise the fence that would be
signaled last. Both fences must be from the same context, since a seqno is
not re-used across contexts.

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

```c
int dma_fence_get_status_locked(struct dma_fence *fence)
```

returns the status upon completion

**Parameters**

- `struct dma_fence *fence`: the dma_fence to query

**Description**

Drivers can supply an optional error status condition before they signal
the fence (to indicate whether the fence was completed due to an error
rather than success). The value of the status condition is only valid
if the fence has been signaled, [`dma_fence_get_status_locked()`](#c-dma_fence_get_status_locked) first checks
the signal state before reporting the error status.

Returns 0 if the fence has not yet been signaled, 1 if the fence has
been signaled without an error condition, or a negative error code
if the fence has been completed in err.

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

```c
void dma_fence_set_error(struct dma_fence *fence, int error)
```

flag an error condition on the fence

**Parameters**

- `struct dma_fence *fence`: the dma_fence
- `int error`: the error to store

**Description**

Drivers can supply an optional error status condition before they signal
the fence, to indicate that the fence was completed due to an error
rather than success. This must be set before signaling (so that the value
is visible before any waiters on the signal callback are woken). This
helper exists to help catching erroneous setting of #dma_fence.error.

Examples of error codes which drivers should use:

* `-ENODATA`   This operation produced no data, no other operation affected.
* `-ECANCELED` All operations from the same context have been canceled.
* `-ETIME`     Operation caused a timeout and potentially device reset.

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

```c
ktime_t dma_fence_timestamp(struct dma_fence *fence)
```

helper to get the completion timestamp of a fence

**Parameters**

- `struct dma_fence *fence`: fence to get the timestamp from.

**Description**

After a fence is signaled the timestamp is updated with the signaling time,
but setting the timestamp can race with tasks waiting for the signaling. This
helper busy waits for the correct timestamp to appear.

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

```c
signed long dma_fence_wait(struct dma_fence *fence, bool intr)
```

sleep until the fence gets signaled

**Parameters**

- `struct dma_fence *fence`: the fence to wait on
- `bool intr`: if true, do an interruptible wait

**Description**

This function will return -ERESTARTSYS if interrupted by a signal,
or 0 if the fence was signaled. Other error values may be
returned on custom implementations.

Performs a synchronous wait on this fence. It is assumed the caller
directly or indirectly holds a reference to the fence, otherwise the
fence might be freed before return, resulting in undefined behavior.

See also [`dma_fence_wait_timeout()`](#c-dma_fence_wait_timeout) and [`dma_fence_wait_any_timeout()`](#c-dma_fence_wait_any_timeout).

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

```c
bool dma_fence_is_array(struct dma_fence *fence)
```

check if a fence is from the array subclass

**Parameters**

- `struct dma_fence *fence`: the fence to test

**Description**

Return true if it is a dma_fence_array and false otherwise.

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

```c
bool dma_fence_is_chain(struct dma_fence *fence)
```

check if a fence is from the chain subclass

**Parameters**

- `struct dma_fence *fence`: the fence to test

**Description**

Return true if it is a dma_fence_chain and false otherwise.

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

```c
bool dma_fence_is_container(struct dma_fence *fence)
```

check if a fence is a container for other fences

**Parameters**

- `struct dma_fence *fence`: the fence to test

**Description**

Return true if this fence is a container for other fences, false otherwise.
This is important since we can't build up large fence structure or otherwise
we run into recursion during operation on those fences.


<a id="rst-dma-fence-array"></a>

### DMA Fence Array


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

```c
struct dma_fence_array * dma_fence_array_alloc(int num_fences)
```

Allocate a custom fence array

**Parameters**

- `int num_fences`: \[in\]    number of fences to add in the array

**Description**

Return dma fence array on success, NULL on failure

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

```c
void dma_fence_array_init(struct dma_fence_array *array, int num_fences, struct dma_fence **fences, u64 context, unsigned seqno, bool signal_on_any)
```

Init a custom fence array

**Parameters**

- `struct dma_fence_array *array`: \[in\]    dma fence array to arm
- `int num_fences`: \[in\]    number of fences to add in the array
- `struct dma_fence **fences`: \[in\]    array containing the fences
- `u64 context`: \[in\]    fence context to use
- `unsigned seqno`: \[in\]    sequence number to use
- `bool signal_on_any`: \[in\]    signal on any fence in the array

**Description**

Implementation of **dma_fence_array_create** without allocation. Useful to init
a preallocated dma fence array in the path of reclaim or dma fence signaling.

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

```c
struct dma_fence_array * dma_fence_array_create(int num_fences, struct dma_fence **fences, u64 context, unsigned seqno, bool signal_on_any)
```

Create a custom fence array

**Parameters**

- `int num_fences`: \[in\]    number of fences to add in the array
- `struct dma_fence **fences`: \[in\]    array containing the fences
- `u64 context`: \[in\]    fence context to use
- `unsigned seqno`: \[in\]    sequence number to use
- `bool signal_on_any`: \[in\]    signal on any fence in the array

**Description**

Allocate a dma_fence_array object and initialize the base fence with
[`dma_fence_init()`](#c-dma_fence_init).
In case of error it returns NULL.

The caller should allocate the fences array with num_fences size
and fill it with the fences it wants to add to the object. Ownership of this
array is taken and [`dma_fence_put()`](#c-dma_fence_put) is used on each fence on release.

If **signal_on_any** is true the fence array signals if any fence in the array
signals, otherwise it signals when all fences in the array signal.

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

```c
bool dma_fence_match_context(struct dma_fence *fence, u64 context)
```

Check if all fences are from the given context

**Parameters**

- `struct dma_fence *fence`: \[in\]    fence or fence array
- `u64 context`: \[in\]    fence context to check all fences against

**Description**

Checks the provided fence or, for a fence array, all fences in the array
against the given context. Returns false if any fence is from a different
context.



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

callback helper for fence array

**Definition**

```c
struct dma_fence_array_cb {
    struct dma_fence_cb cb;
    struct dma_fence_array *array;
};
```

**Members**

- `cb`: fence callback structure for signaling
- `array`: reference to the parent fence array object

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

fence to represent an array of fences

**Definition**

```c
struct dma_fence_array {
    struct dma_fence base;
    spinlock_t lock;
    unsigned num_fences;
    atomic_t num_pending;
    struct dma_fence **fences;
    struct irq_work work;
    struct dma_fence_array_cb callbacks[] ;
};
```

**Members**

- `base`: fence base class
- `lock`: spinlock for fence handling
- `num_fences`: number of fences in the array
- `num_pending`: fences in the array still pending
- `fences`: array of the fences
- `work`: internal irq_work function
- `callbacks`: array of callback helpers

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

```c
struct dma_fence_array * to_dma_fence_array(struct dma_fence *fence)
```

cast a fence to a dma_fence_array

**Parameters**

- `struct dma_fence *fence`: fence to cast to a dma_fence_array

**Description**

Returns NULL if the fence is not a dma_fence_array,
or the dma_fence_array otherwise.

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

```c
dma_fence_array_for_each(fence, index, head)
```

iterate over all fences in array

**Parameters**

- `fence`: current fence
- `index`: index into the array
- `head`: potential dma_fence_array object

**Description**

Test if **array** is a dma_fence_array object and if yes iterate over all fences
in the array. If not just iterate over the fence in **array** itself.

For a deep dive iterator see [`dma_fence_unwrap_for_each()`](#c-dma_fence_unwrap_for_each).


<a id="rst-dma-fence-chain"></a>

### DMA Fence Chain


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

```c
struct dma_fence * dma_fence_chain_walk(struct dma_fence *fence)
```

chain walking function

**Parameters**

- `struct dma_fence *fence`: current chain node

**Description**

Walk the chain to the next node. Returns the next fence or NULL if we are at
the end of the chain. Garbage collects chain nodes which are already
signaled.

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

```c
int dma_fence_chain_find_seqno(struct dma_fence **pfence, uint64_t seqno)
```

find fence chain node by seqno

**Parameters**

- `struct dma_fence **pfence`: pointer to the chain node where to start
- `uint64_t seqno`: the sequence number to search for

**Description**

Advance the fence pointer to the chain node which will signal this sequence
number. If no sequence number is provided then this is a no-op.

Returns EINVAL if the fence is not a chain node or the sequence number has
not yet advanced far enough.

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

```c
void dma_fence_chain_init(struct dma_fence_chain *chain, struct dma_fence *prev, struct dma_fence *fence, uint64_t seqno)
```

initialize a fence chain

**Parameters**

- `struct dma_fence_chain *chain`: the chain node to initialize
- `struct dma_fence *prev`: the previous fence
- `struct dma_fence *fence`: the current fence
- `uint64_t seqno`: the sequence number to use for the fence chain

**Description**

Initialize a new chain node and either start a new chain or add the node to
the existing chain of the previous fence.



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

fence to represent an node of a fence chain

**Definition**

```c
struct dma_fence_chain {
    struct dma_fence base;
    struct dma_fence  *prev;
    u64 prev_seqno;
    struct dma_fence *fence;
    union {
        struct dma_fence_cb cb;
        struct irq_work work;
    };
    spinlock_t lock;
};
```

**Members**

- `base`: fence base class
- `prev`: previous fence of the chain
- `prev_seqno`: original previous seqno before garbage collection
- `fence`: encapsulated fence
- `{unnamed_union}`: anonymous
- `cb`: callback for signaling

  This is used to add the callback for signaling the
  complection of the fence chain. Never used at the same time
  as the irq work.
- `work`: irq work item for signaling

  Irq work structure to allow us to add the callback without
  running into lock inversion. Never used at the same time as
  the callback.
- `lock`: spinlock for fence handling

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

```c
struct dma_fence_chain * to_dma_fence_chain(struct dma_fence *fence)
```

cast a fence to a dma_fence_chain

**Parameters**

- `struct dma_fence *fence`: fence to cast to a dma_fence_array

**Description**

Returns NULL if the fence is not a dma_fence_chain,
or the dma_fence_chain otherwise.

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

```c
struct dma_fence * dma_fence_chain_contained(struct dma_fence *fence)
```

return the contained fence

**Parameters**

- `struct dma_fence *fence`: the fence to test

**Description**

If the fence is a dma_fence_chain the function returns the fence contained
inside the chain object, otherwise it returns the fence itself.

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

```c
dma_fence_chain_alloc()
```

**Description**

Returns a new struct dma_fence_chain object or NULL on failure.

This specialized allocator has to be a macro for its allocations to be
accounted separately (to have a separate alloc_tag). The typecast is
intentional to enforce typesafety.

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

```c
void dma_fence_chain_free(struct dma_fence_chain *chain)
```

**Parameters**

- `struct dma_fence_chain *chain`: chain node to free

**Description**

Frees up an allocated but not used struct dma_fence_chain object. This
doesn't need an RCU grace period since the fence was never initialized nor
published. After [`dma_fence_chain_init()`](#c-dma_fence_chain_init) has been called the fence must be
released by calling [`dma_fence_put()`](#c-dma_fence_put), and not through this function.

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

```c
dma_fence_chain_for_each(iter, head)
```

iterate over all fences in chain

**Parameters**

- `iter`: current fence
- `head`: starting point

**Description**

Iterate over all fences in the chain. We keep a reference to the current
fence while inside the loop which must be dropped when breaking out.

For a deep dive iterator see [`dma_fence_unwrap_for_each()`](#c-dma_fence_unwrap_for_each).


<a id="rst-dma-fence-unwrap"></a>

### DMA Fence unwrap


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

cursor into the container structure

**Definition**

```c
struct dma_fence_unwrap {
    struct dma_fence *chain;
    struct dma_fence *array;
    unsigned int index;
};
```

**Members**

- `chain`: potential dma_fence_chain, but can be other fence as well
- `array`: potential dma_fence_array, but can be other fence as well
- `index`: last returned index if **array** is really a dma_fence_array

**Description**

Should be used with [`dma_fence_unwrap_for_each()`](#c-dma_fence_unwrap_for_each) iterator macro.

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

```c
dma_fence_unwrap_for_each(fence, cursor, head)
```

iterate over all fences in containers

**Parameters**

- `fence`: current fence
- `cursor`: current position inside the containers
- `head`: starting point for the iterator

**Description**

Unwrap dma_fence_chain and dma_fence_array containers and deep dive into all
potential fences in them. If **head** is just a normal fence only that one is
returned.

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

```c
dma_fence_unwrap_merge(...)
```

unwrap and merge fences

**Parameters**

- `...`: variable arguments

**Description**

All fences given as parameters are unwrapped and merged back together as flat
dma_fence_array. Useful if multiple containers need to be merged together.

Implemented as a macro to allocate the necessary arrays on the stack and
account the stack frame size to the caller.

Returns NULL on memory allocation failure, a dma_fence object representing
all the given fences otherwise.


<a id="rst-dma-fence-sync-file"></a>

### DMA Fence Sync File


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

```c
struct sync_file * sync_file_create(struct dma_fence *fence)
```

creates a sync file

**Parameters**

- `struct dma_fence *fence`: fence to add to the sync_fence

**Description**

Creates a sync_file containg **fence**. This function acquires and additional
reference of **fence** for the newly-created [`sync_file`](#c-struct-sync_file), if it succeeds. The
sync_file can be released with fput(sync_file->file). Returns the
sync_file or NULL in case of error.

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

```c
struct dma_fence * sync_file_get_fence(int fd)
```

get the fence related to the sync_file fd

**Parameters**

- `int fd`: sync_file fd to get the fence from

**Description**

Ensures **fd** references a valid sync_file and returns a fence that
represents all fence in the sync_file. On error NULL is returned.



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

sync file to export to the userspace

**Definition**

```c
struct sync_file {
        struct file             *file;
        char user_name[32];
    #ifdef CONFIG_DEBUG_FS;
        struct list_head        sync_file_list;
    #endif;
        wait_queue_head_t wq;
        unsigned long           flags;
        struct dma_fence        *fence;
        struct dma_fence_cb cb;
};
```

**Members**

- `file`: file representing this fence
- `user_name`: Name of the sync file provided by userspace, for merged fences.
  Otherwise generated through driver callbacks (in which case the
  entire array is 0).
- `sync_file_list`: membership in global file list
- `wq`: wait queue for fence signaling
- `flags`: flags for the sync_file
- `fence`: fence with the fences in the sync_file
- `cb`: fence callback information

**Description**

flags:
POLL_ENABLED: whether userspace is currently `poll()`'ing or not


<a id="rst-dma-fence-sync-file-uabi"></a>

### DMA Fence Sync File uABI


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

SYNC_IOC_MERGE: merge two fences

**Definition**

```c
struct sync_merge_data {
    char name[32];
    __s32 fd2;
    __s32 fence;
    __u32 flags;
    __u32 pad;
};
```

**Members**

- `name`: name of new fence
- `fd2`: file descriptor of second fence
- `fence`: returns the fd of the new fence to userspace
- `flags`: merge_data flags
- `pad`: padding for 64-bit alignment, should always be zero

**Description**

Creates a new fence containing copies of the sync_pts in both
the calling fd and sync_merge_data.fd2.  Returns the new fence's
fd in sync_merge_data.fence

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

detailed fence information

**Definition**

```c
struct sync_fence_info {
    char obj_name[32];
    char driver_name[32];
    __s32 status;
    __u32 flags;
    __u64 timestamp_ns;
};
```

**Members**

- `obj_name`: name of parent sync_timeline
- `driver_name`: name of driver implementing the parent
- `status`: status of the fence 0:active 1:signaled \<0:error
- `flags`: fence_info flags
- `timestamp_ns`: timestamp of status change in nanoseconds

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

SYNC_IOC_FILE_INFO: get detailed information on a sync_file

**Definition**

```c
struct sync_file_info {
    char name[32];
    __s32 status;
    __u32 flags;
    __u32 num_fences;
    __u32 pad;
    __u64 sync_fence_info;
};
```

**Members**

- `name`: name of fence
- `status`: status of fence. 1: signaled 0:active \<0:error
- `flags`: sync_file_info flags
- `num_fences`: number of fences in the sync_file
- `pad`: padding for 64-bit alignment, should always be zero
- `sync_fence_info`: pointer to array of struct [`sync_fence_info`](#c-struct-sync_fence_info) with all
  fences in the sync_file

**Description**

Takes a struct sync_file_info. If num_fences is 0, the field is updated
with the actual number of fences. If num_fences is > 0, the system will
use the pointer provided on sync_fence_info to return up to num_fences of
struct sync_fence_info, with detailed fence information.

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

SYNC_IOC_SET_DEADLINE - set a deadline hint on a fence

**Definition**

```c
struct sync_set_deadline {
    __u64 deadline_ns;
    __u64 pad;
};
```

**Members**

- `deadline_ns`: absolute time of the deadline
- `pad`: must be zero

**Description**

Allows userspace to set a deadline on a fence, see [`dma_fence_set_deadline`](#c-dma_fence_set_deadline)

The timebase for the deadline is CLOCK_MONOTONIC (same as vblank).  For
example

clock_gettime(CLOCK_MONOTONIC, `t`);
deadline_ns = (t.tv_sec * 1000000000L) + t.tv_nsec + ns_until_deadline


<a id="rst-indefinite-dma-fences"></a>

### Indefinite DMA Fences

At various times struct dma_fence with an indefinite time until dma_fence_wait() finishes have been proposed. Examples include:

- Future fences, used in HWC1 to signal when a buffer isn't used by the display any longer, and created with the screen update that makes the buffer visible. The time this fence completes is entirely under userspace's control.

- Proxy fences, proposed to handle &amp;drm_syncobj for which the fence has not yet been set. Used to asynchronously delay command submission.

- Userspace fences or gpu futexes, fine-grained locking within a command buffer that userspace uses for synchronization across engines or with the CPU, which are then imported as a DMA fence for integration into existing winsys protocols.

- Long-running compute command buffers, while still using traditional end of batch DMA fences for memory management instead of context preemption DMA fences which get reattached when the compute job is rescheduled.

Common to all these schemes is that userspace controls the dependencies of these fences and controls when they fire. Mixing indefinite fences with normal in-kernel DMA fences does not work, even when a fallback timeout is included to protect against malicious userspace:

- Only the kernel knows about all DMA fence dependencies, userspace is not aware of dependencies injected due to memory management or scheduler decisions.

- Only userspace knows about all dependencies in indefinite fences and when exactly they will complete, the kernel has no visibility.

Furthermore the kernel has to be able to hold up userspace command submission for memory management needs, which means we must support indefinite fences being dependent upon DMA fences. If the kernel also support indefinite fences in the kernel like a DMA fence, like any of the above proposal would, there is the potential for deadlocks.

```mermaid
flowchart TB
  n0["Kernel DMA Fences"]
  n1["userspace controlled fences"]
  n0 -->|"memory management"| n1
  n1 -->|"Future fence, fence proxy, ..."| n0
```

Indefinite Fencing Dependency Cycle

This means that the kernel might accidentally create deadlocks through memory management dependencies which userspace is unaware of, which randomly hangs workloads until the timeout kicks in. Workloads, which from userspace's perspective, do not contain a deadlock.  In such a mixed fencing architecture there is no single entity with knowledge of all dependencies. Therefore preventing such deadlocks from within the kernel is not possible.

The only solution to avoid dependencies loops is by not allowing indefinite fences in the kernel. This means:

- No future fences, proxy fences or userspace fences imported as DMA fences, with or without a timeout.

- No DMA fences that signal end of batchbuffer for command submission where userspace is allowed to use userspace fencing or long running compute workloads. This also means no implicit fencing for shared buffers in these cases.

<a id="rst-recoverable-hardware-page-faults-implications"></a>

### Recoverable Hardware Page Faults Implications

Modern hardware supports recoverable page faults, which has a lot of implications for DMA fences.

First, a pending page fault obviously holds up the work that's running on the accelerator and a memory allocation is usually required to resolve the fault. But memory allocations are not allowed to gate completion of DMA fences, which means any workload using recoverable page faults cannot use DMA fences for synchronization. Synchronization fences controlled by userspace must be used instead.

On GPUs this poses a problem, because current desktop compositor protocols on Linux rely on DMA fences, which means without an entirely new userspace stack built on top of userspace fences, they cannot benefit from recoverable page faults. Specifically this means implicit synchronization will not be possible. The exception is when page faults are only used as migration hints and never to on-demand fill a memory request. For now this means recoverable page faults on GPUs are limited to pure compute workloads.

Furthermore GPUs usually have shared resources between the 3D rendering and compute side, like compute units or command submission engines. If both a 3D job with a DMA fence and a compute workload using recoverable page faults are pending they could deadlock:

- The 3D workload might need to wait for the compute job to finish and release hardware resources first.

- The compute workload might be stuck in a page fault, because the memory allocation is waiting for the DMA fence of the 3D workload to complete.

There are a few options to prevent this problem, one of which drivers need to ensure:

- Compute workloads can always be preempted, even when a page fault is pending and not yet repaired. Not all hardware supports this.

- DMA fence workloads and workloads which need page fault handling have independent hardware resources to guarantee forward progress. This could be achieved through e.g. through dedicated engines and minimal compute unit reservations for DMA fence workloads.

- The reservation approach could be further refined by only reserving the hardware resources for DMA fence workloads when they are in-flight. This must cover the time from when the DMA fence is visible to other threads up to moment when fence is completed through dma_fence_signal().

- As a last resort, if the hardware provides no useful reservation mechanics, all workloads must be flushed from the GPU when switching between jobs requiring DMA fences or jobs requiring page fault handling: This means all DMA fences must complete before a compute job with page fault handling can be inserted into the scheduler queue. And vice versa, before a DMA fence can be made visible anywhere in the system, all compute workloads must be preempted to guarantee all pending GPU page faults are flushed.

- Only a fairly theoretical option would be to untangle these dependencies when allocating memory to repair hardware page faults, either through separate memory blocks or runtime tracking of the full dependency graph of all DMA fences. This results very wide impact on the kernel, since resolving the page on the CPU side can itself involve a page fault. It is much more feasible and robust to limit the impact of handling hardware page faults to the specific driver.

Note that workloads that run on independent hardware like copy engines or other GPUs do not have any impact. This allows us to keep using DMA fences internally in the kernel even for resolving hardware page faults, e.g. by using copy engines to clear or copy memory needed to resolve the page fault.

In some ways this page fault problem is a special case of the `Infinite DMA Fences` discussions: Infinite fences from compute workloads are allowed to depend on DMA fences, but not the other way around. And not even the page fault problem is new, because some other CPU thread in userspace might hit a page fault which holds up a userspace fence - supporting page faults on GPUs doesn't anything fundamentally new.

---

# Generic Radix Page Table

_Peios Kernel / Hardware and drivers / Driver development / Device I/O and shared memory_

> Generic PT is structured as a multi-compilation system. Since each format provides an API using a common set of names there can be only one format active within a compilation unit. This design avoids function pointers around the low level…

<a id="rst-generic-radix-page-table"></a>

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


Generic Radix Page Table is a set of functions and helpers to efficiently
parse radix style page tables typically seen in HW implementations. The
interface is built to deliver similar code generation as the mm's pte/pmd/etc
system by fully inlining the exact code required to handle each table level.

Like the mm subsystem each format contributes its parsing implementation
under common names and the common code implements the required algorithms.

The system is divided into three logical levels:

- The page table format and its manipulation functions
- Generic helpers to give a consistent API regardless of underlying format
- An algorithm implementation (e.g. IOMMU/DRM/KVM/MM)

Multiple implementations are supported. The intention is to have the generic
format code be re-usable for whatever specialized implementation is required.
The generic code is solely about the format of the radix tree; it does not
include memory allocation or higher level decisions that are left for the
implementation.

The generic framework supports a superset of functions across many HW
implementations:

- Entries comprised of contiguous blocks of IO PTEs for larger page sizes
- Multi-level tables, up to 6 levels. Runtime selected top level
- Runtime variable table level size (ARM's concatenated tables)
- Expandable top level allowing dynamic sizing of table levels
- Optional leaf entries at any level
- 32-bit/64-bit virtual and output addresses, using every address bit
- Dirty tracking
- Sign extended addressing



- Language used in Generic Page Table

  VA
  The input address to the page table, often the virtual address.
  OA
  The output address from the page table, often the physical address.
  leaf
  An entry that results in an output address.
  start/end
  An half-open range, e.g. \[0,0) refers to no VA.
  start/last
  An inclusive closed range, e.g. \[0,0\] refers to the VA 0
  common
  The generic page table container struct pt_common
  level
  Level 0 is always a table of only leaves with no futher table pointers.
  Increasing levels increase the size of the table items. The least
  significant VA bits used to index page tables are used to index the Level
  0 table. The various labels for table levels used by HW descriptions are
  not used.
  top_level
  The inclusive highest level of the table. A two-level table
  has a top level of 1.
  table
  A linear array of translation items for that level.
  index
  The position in a table of an element: item = table\[index\]
  item
  A single index in a table
  entry
  A single logical element in a table. If contiguous pages are not
  supported then item and entry are the same thing, otherwise entry refers
  to all the items that comprise a single contiguous translation.
  item/entry_size
  The number of bytes of VA the table index translates for.
  If the item is a table entry then the next table covers
  this size. If the entry translates to an output address then the
  full OA is: OA | (VA % entry_size)
  contig_count
  The number of consecutive items fused into a single entry.
  item_size * contig_count is the size of that entry's translation.
  lg2
  Indicates the value is encoded as log2, i.e. 1\<\<x is the actual value.
  Normally the compiler is fine to optimize divide and mod with log2 values
  automatically when inlining, however if the values are not constant
  expressions it can't. So we do it by hand; we want to avoid 64-bit
  divmod.


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

## Usage

Generic PT is structured as a multi-compilation system. Since each format provides an API using a common set of names there can be only one format active within a compilation unit. This design avoids function pointers around the low level API.

Instead the function pointers can end up at the higher level API (i.e. map/unmap, etc.) and the per-format code can be directly inlined into the per-format compilation unit. For something like IOMMU each format will be compiled into a per-format IOMMU operations kernel module.

For this to work the .c file for each compilation unit will include both the format headers and the generic code for the implementation. For instance in an implementation compilation unit the headers would normally be included as follows:

generic_pt/fmt/iommu_amdv1.c:



```text
#include <linux/generic_pt/common.h>
#include "defs_amdv1.h"
#include "../pt_defs.h"
#include "amdv1.h"
#include "../pt_common.h"
#include "../pt_iter.h"
#include "../iommu_pt.h"  /* The IOMMU implementation */
```

iommu_pt.h includes definitions that will generate the operations functions for map/unmap/etc. using the definitions provided by AMDv1. The resulting module will have exported symbols named like pt_iommu_amdv1_init().

Refer to drivers/iommu/generic_pt/fmt/iommu_template.h for an example of how the IOMMU implementation uses multi-compilation to generate per-format ops structs pointers.

The format code is written so that the common names arise from \#defines to distinct format specific names. This is intended to aid debuggability by avoiding symbol clashes across all the different formats.

Exported symbols and other global names are mangled using a per-format string via the NS() helper macro.

The format uses struct pt_common as the top-level struct for the table, and each format will have its own struct pt_xxx which embeds it to store format-specific information.

The implementation will further wrap struct pt_common in its own top-level struct, such as struct pt_iommu_amdv1.

<a id="rst-format-functions-at-the-struct-pt-common-level"></a>

### Format functions at the struct pt_common level


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

struct for all page table implementations

**Definition**

```c
struct pt_common {
    uintptr_t top_of_table;
    u8 max_oasz_lg2;
    u8 max_vasz_lg2;
    unsigned int features;
};
```

**Members**

- `top_of_table`: Encodes the table top pointer and the top level in a
  single value. Must use READ_ONCE/WRITE_ONCE to access it. The lower
  bits of the aligned table pointer are used for the level.
- `max_oasz_lg2`: Maximum number of bits the OA can contain. Upper bits
  must be zero. This may be less than what the page table format
  supports, but must not be more.
- `max_vasz_lg2`: Maximum number of bits the VA can contain. Upper bits
  are 0 or 1 depending on [`pt_full_va_prefix()`](#c-pt_full_va_prefix). This may be less than
  what the page table format supports, but must not be more. When
  PT_FEAT_DYNAMIC_TOP is set this reflects the maximum VA capability.
- `features`: Bitmap of `enum pt_features`

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

Features turned on in the table. Each symbol is a bit position.

**Constants**

- `PT_FEAT_DMA_INCOHERENT`: Cache flush page table memory before
  assuming the HW can read it. Otherwise a SMP release is sufficient
  for HW to read it.
- `PT_FEAT_FULL_VA`: The table can span the full VA range from 0 to
  PT_VADDR_MAX.
- `PT_FEAT_DYNAMIC_TOP`: The table's top level can be increased
  dynamically during map. This requires HW support for atomically
  setting both the table top pointer and the starting table level.
- `PT_FEAT_SIGN_EXTEND`: The top most bit of the valid VA range sign
  extends up to the full pt_vaddr_t. This divides the page table into
  three VA ranges:

  ```text
  0         -> 2^N - 1             Lower
  2^N       -> (MAX - 2^N - 1)     Non-Canonical
  MAX - 2^N -> MAX                 Upper
  ```

  In this mode pt_common::max_vasz_lg2 includes the sign bit and the
  upper bits that don't fall within the translation are just validated.

  If not set there is no sign extension and valid VA goes from 0 to 2^N
  - 1.
- `PT_FEAT_FLUSH_RANGE`: IOTLB maintenance is done by flushing IOVA
  ranges which will clean out any walk cache or any IOPTE fully
  contained by the range. The optimization objective is to minimize the
  number of flushes even if ranges include IOVA gaps that do not need
  to be flushed.
- `PT_FEAT_FLUSH_RANGE_NO_GAPS`: Like PT_FEAT_FLUSH_RANGE except that
  the optimization objective is to only flush IOVA that has been
  changed. This mode is suitable for cases like hypervisor shadowing
  where flushing unchanged ranges may cause the hypervisor to reparse
  significant amount of page table.



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

```c
void pt_attr_from_entry(const struct pt_state *pts, struct pt_write_attrs *attrs)
```

Convert the permission bits back to attrs

**Parameters**

- `const struct pt_state *pts`: Entry to convert from
- `struct pt_write_attrs *attrs`: Resulting attrs

**Description**

Fill in the attrs with the permission bits encoded in the current leaf entry.
The attrs should be usable with [`pt_install_leaf_entry()`](#c-pt_install_leaf_entry) to reconstruct the
same entry.

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

```c
bool pt_can_have_leaf(const struct pt_state *pts)
```

True if the current level can have an OA entry

**Parameters**

- `const struct pt_state *pts`: The current level

**Description**

True if the current level can support [`pt_install_leaf_entry()`](#c-pt_install_leaf_entry). A leaf
entry produce an OA.

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

```c
bool pt_can_have_table(const struct pt_state *pts)
```

True if the current level can have a lower table

**Parameters**

- `const struct pt_state *pts`: The current level

**Description**

Every level except 0 is allowed to have a lower table.

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

```c
void pt_clear_entries(struct pt_state *pts, unsigned int num_contig_lg2)
```

Make entries empty (non-present)

**Parameters**

- `struct pt_state *pts`: Starting table index
- `unsigned int num_contig_lg2`: Number of contiguous items to clear

**Description**

Clear a run of entries. A cleared entry will load back as PT_ENTRY_EMPTY
and does not have any effect on table walking. The starting index must be
aligned to num_contig_lg2.

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

```c
bool pt_entry_make_write_dirty(struct pt_state *pts)
```

Make an entry dirty

**Parameters**

- `struct pt_state *pts`: Table entry to change

**Description**

Make [`pt_entry_is_write_dirty()`](#c-pt_entry_is_write_dirty) return true for this entry. This can be called
asynchronously with any other table manipulation under a RCU lock and must
not corrupt the table.

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

```c
void pt_entry_make_write_clean(struct pt_state *pts)
```

Make the entry write clean

**Parameters**

- `struct pt_state *pts`: Table entry to change

**Description**

Modify the entry so that [`pt_entry_is_write_dirty()`](#c-pt_entry_is_write_dirty) == false. The HW will
eventually be notified of this change via a TLB flush, which is the point
that the HW must become synchronized. Any "write dirty" prior to the TLB
flush can be lost, but once the TLB flush completes all writes must make
their entries write dirty.

The format should alter the entry in a way that is compatible with any
concurrent update from HW. The entire contiguous entry is changed.

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

```c
bool pt_entry_is_write_dirty(const struct pt_state *pts)
```

True if the entry has been written to

**Parameters**

- `const struct pt_state *pts`: Entry to query

**Description**

"write dirty" means that the HW has written to the OA translated
by this entry. If the entry is contiguous then the consolidated
"write dirty" for all the items must be returned.

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

```c
bool pt_dirty_supported(struct pt_common *common)
```

True if the page table supports dirty tracking

**Parameters**

- `struct pt_common *common`: Page table to query

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

```c
unsigned int pt_entry_num_contig_lg2(const struct pt_state *pts)
```

Number of contiguous items for this leaf entry

**Parameters**

- `const struct pt_state *pts`: Entry to query

**Description**

Return the number of contiguous items this leaf entry spans. If the entry
is single item it returns ilog2(1).

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

```c
pt_oaddr_t pt_entry_oa(const struct pt_state *pts)
```

Output Address for this leaf entry

**Parameters**

- `const struct pt_state *pts`: Entry to query

**Description**

Return the output address for the start of the entry. If the entry
is contiguous this returns the same value for each sub-item. I.e.:

```text
log2_mod(pt_entry_oa(), pt_entry_oa_lg2sz()) == 0
```

See [`pt_item_oa()`](#c-pt_item_oa). The format should implement one of these two functions
depending on how it stores the OAs in the table.

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

```c
unsigned int pt_entry_oa_lg2sz(const struct pt_state *pts)
```

Return the size of an OA entry

**Parameters**

- `const struct pt_state *pts`: Entry to query

**Description**

If the entry is not contiguous this returns [`pt_table_item_lg2sz()`](#c-pt_table_item_lg2sz), otherwise
it returns the total VA/OA size of the entire contiguous entry.

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

```c
pt_oaddr_t pt_entry_oa_exact(const struct pt_state *pts)
```

Return the complete OA for an entry

**Parameters**

- `const struct pt_state *pts`: Entry to query

**Description**

During iteration the first entry could have a VA with an offset from the
natural start of the entry. Return the exact OA including the pts's VA
offset.

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

```c
pt_vaddr_t pt_full_va_prefix(const struct pt_common *common)
```

The top bits of the VA

**Parameters**

- `const struct pt_common *common`: Page table to query

**Description**

This is usually 0, but some formats have their VA space going downward from
PT_VADDR_MAX, and will return that instead. This value must always be
adjusted by struct pt_common max_vasz_lg2.

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

```c
bool pt_has_system_page_size(const struct pt_common *common)
```

True if level 0 can install a PAGE_SHIFT entry

**Parameters**

- `const struct pt_common *common`: Page table to query

**Description**

If true the caller can use, at level 0, pt_install_leaf_entry(PAGE_SHIFT).
This is useful to create optimized paths for common cases of PAGE_SIZE
mappings.

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

```c
void pt_install_leaf_entry(struct pt_state *pts, pt_oaddr_t oa, unsigned int oasz_lg2, const struct pt_write_attrs *attrs)
```

Write a leaf entry to the table

**Parameters**

- `struct pt_state *pts`: Table index to change
- `pt_oaddr_t oa`: Output Address for this leaf
- `unsigned int oasz_lg2`: Size in VA/OA for this leaf
- `const struct pt_write_attrs *attrs`: Attributes to modify the entry

**Description**

A leaf OA entry will return PT_ENTRY_OA from [`pt_load_entry()`](#c-pt_load_entry). It translates
the VA indicated by pts to the given OA.

For a single item non-contiguous entry oasz_lg2 is [`pt_table_item_lg2sz()`](#c-pt_table_item_lg2sz).
For contiguous it is [`pt_table_item_lg2sz()`](#c-pt_table_item_lg2sz) + num_contig_lg2.

This must not be called if [`pt_can_have_leaf()`](#c-pt_can_have_leaf) == false. Contiguous sizes
not indicated by [`pt_possible_sizes()`](#c-pt_possible_sizes) must not be specified.

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

```c
bool pt_install_table(struct pt_state *pts, pt_oaddr_t table_pa, const struct pt_write_attrs *attrs)
```

Write a table entry to the table

**Parameters**

- `struct pt_state *pts`: Table index to change
- `pt_oaddr_t table_pa`: CPU physical address of the lower table's memory
- `const struct pt_write_attrs *attrs`: Attributes to modify the table index

**Description**

A table entry will return PT_ENTRY_TABLE from [`pt_load_entry()`](#c-pt_load_entry). The table_pa
is the table at pts->level - 1. This is done by cmpxchg so pts must have the
current entry loaded. The pts is updated with the installed entry.

This must not be called if [`pt_can_have_table()`](#c-pt_can_have_table) == false.

**Return**

true if the table was installed successfully.

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

```c
pt_oaddr_t pt_item_oa(const struct pt_state *pts)
```

Output Address for this leaf item

**Parameters**

- `const struct pt_state *pts`: Item to query

**Description**

Return the output address for this item. If the item is part of a contiguous
entry it returns the value of the OA for this individual sub item.

See [`pt_entry_oa()`](#c-pt_entry_oa). The format should implement one of these two functions
depending on how it stores the OA's in the table.

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

```c
enum pt_entry_type pt_load_entry_raw(struct pt_state *pts)
```

Read from the location pts points at into the pts

**Parameters**

- `struct pt_state *pts`: Table index to load

**Description**

Return the type of entry that was loaded. pts->entry will be filled in with
the entry's content. See [`pt_load_entry()`](#c-pt_load_entry)

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

```c
unsigned int pt_max_oa_lg2(const struct pt_common *common)
```

Return the maximum OA the table format can hold

**Parameters**

- `const struct pt_common *common`: Page table to query

**Description**

The value oalog2_to_max_int([`pt_max_oa_lg2()`](#c-pt_max_oa_lg2)) is the MAX for the
OA. This is the absolute maximum address the table can hold. struct pt_common
max_oasz_lg2 sets a lower dynamic maximum based on HW capability.

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

```c
unsigned int pt_num_items_lg2(const struct pt_state *pts)
```

Return the number of items in this table level

**Parameters**

- `const struct pt_state *pts`: The current level

**Description**

The number of items in a table level defines the number of bits this level
decodes from the VA. This function is not called for the top level,
so it does not need to compute a special value for the top case. The
result for the top is based on pt_common max_vasz_lg2.

The value is used as part of determining the table indexes via the
equation:

```text
log2_mod(log2_div(VA, pt_table_item_lg2sz()), pt_num_items_lg2())
```

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

```c
unsigned int pt_pgsz_lg2_to_level(struct pt_common *common, unsigned int pgsize_lg2)
```

Return the level that maps the page size

**Parameters**

- `struct pt_common *common`: Page table to query
- `unsigned int pgsize_lg2`: Log2 page size

**Description**

Returns the table level that will map the given page size. The page
size must be part of the [`pt_possible_sizes()`](#c-pt_possible_sizes) for some level.

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

```c
pt_vaddr_t pt_possible_sizes(const struct pt_state *pts)
```

Return a bitmap of possible output sizes at this level

**Parameters**

- `const struct pt_state *pts`: The current level

**Description**

Each level has a list of possible output sizes that can be installed as
leaf entries. If [`pt_can_have_leaf()`](#c-pt_can_have_leaf) is false returns zero.

Otherwise the bit in position [`pt_table_item_lg2sz()`](#c-pt_table_item_lg2sz) should be set indicating
that a non-contiguous single item leaf entry is supported. The following
[`pt_num_items_lg2()`](#c-pt_num_items_lg2) number of bits can be set indicating contiguous entries
are supported. Bit [`pt_table_item_lg2sz()`](#c-pt_table_item_lg2sz) + [`pt_num_items_lg2()`](#c-pt_num_items_lg2) must not be
set, contiguous entries cannot span the entire table.

The OR of [`pt_possible_sizes()`](#c-pt_possible_sizes) of all levels is the typical bitmask of all
supported sizes in the entire table.

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

```c
unsigned int pt_table_item_lg2sz(const struct pt_state *pts)
```

Size of a single item entry in this table level

**Parameters**

- `const struct pt_state *pts`: The current level

**Description**

The size of the item specifies how much VA and OA a single item occupies.

See [`pt_entry_oa_lg2sz()`](#c-pt_entry_oa_lg2sz) for the same value including the effect of contiguous
entries.

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

```c
unsigned int pt_table_oa_lg2sz(const struct pt_state *pts)
```

Return the VA/OA size of the entire table

**Parameters**

- `const struct pt_state *pts`: The current level

**Description**

Return the size of VA decoded by the entire table level.

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

```c
pt_oaddr_t pt_table_pa(const struct pt_state *pts)
```

Return the CPU physical address of the table entry

**Parameters**

- `const struct pt_state *pts`: Entry to query

**Description**

This is only ever called on PT_ENTRY_TABLE entries. Must return the same
value passed to [`pt_install_table()`](#c-pt_install_table).

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

```c
struct pt_table_p * pt_table_ptr(const struct pt_state *pts)
```

Return a CPU pointer for a table item

**Parameters**

- `const struct pt_state *pts`: Entry to query

**Description**

Same as [`pt_table_pa()`](#c-pt_table_pa) but returns a CPU pointer.

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

```c
unsigned int pt_max_sw_bit(struct pt_common *common)
```

Return the maximum software bit usable for any level and entry

**Parameters**

- `struct pt_common *common`: Page table

**Description**

The swbit can be passed as bitnr to the other sw_bit functions.

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

```c
bool pt_test_sw_bit_acquire(struct pt_state *pts, unsigned int bitnr)
```

Read a software bit in an item

**Parameters**

- `struct pt_state *pts`: Entry to read
- `unsigned int bitnr`: Bit to read

**Description**

Software bits are ignored by HW and can be used for any purpose by the
software. This does a test bit and acquire operation.

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

```c
void pt_set_sw_bit_release(struct pt_state *pts, unsigned int bitnr)
```

Set a software bit in an item

**Parameters**

- `struct pt_state *pts`: Entry to set
- `unsigned int bitnr`: Bit to set

**Description**

Software bits are ignored by HW and can be used for any purpose by the
software. This does a set bit and release operation.

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

```c
void pt_load_entry(struct pt_state *pts)
```

Read from the location pts points at into the pts

**Parameters**

- `struct pt_state *pts`: Table index to load

**Description**

Set the type of entry that was loaded. pts->entry and pts->table_lower
will be filled in with the entry's content.


<a id="rst-iteration-helpers"></a>

### Iteration Helpers


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

```c
int pt_check_range(struct pt_range *range)
```

Validate the range can be iterated

**Parameters**

- `struct pt_range *range`: Range to validate

**Description**

Check that VA and last_va fall within the permitted range of VAs. If the
format is using PT_FEAT_SIGN_EXTEND then this also checks the sign extension
is correct.

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

```c
void pt_index_to_va(struct pt_state *pts)
```

Update range->va to the current pts->index

**Parameters**

- `struct pt_state *pts`: Iteration State

**Description**

Adjust range->va to match the current index. This is done in a lazy manner
since computing the VA takes several instructions and is rarely required.

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

```c
bool pt_entry_fully_covered(const struct pt_state *pts, unsigned int oasz_lg2)
```

Check if the item or entry is entirely contained within pts->range

**Parameters**

- `const struct pt_state *pts`: Iteration State
- `unsigned int oasz_lg2`: The size of the item to check, [`pt_table_item_lg2sz()`](#c-pt_table_item_lg2sz) or
  [`pt_entry_oa_lg2sz()`](#c-pt_entry_oa_lg2sz)

**Return**

true if the item is fully enclosed by the pts->range.

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

```c
unsigned int pt_range_to_index(const struct pt_state *pts)
```

Starting index for an iteration

**Parameters**

- `const struct pt_state *pts`: Iteration State

**Return**

the starting index for the iteration in pts.

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

```c
unsigned int pt_range_to_end_index(const struct pt_state *pts)
```

Ending index iteration

**Parameters**

- `const struct pt_state *pts`: Iteration State

**Return**

the last index for the iteration in pts.

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

```c
void pt_next_entry(struct pt_state *pts)
```

Advance pts to the next entry

**Parameters**

- `struct pt_state *pts`: Iteration State

**Description**

Update pts to go to the next index at this level. If pts is pointing at a
contiguous entry then the index may advance my more than one.

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

```c
for_each_pt_level_entry(pts)
```

For loop wrapper over entries in the range

**Parameters**

- `pts`: Iteration State

**Description**

This is the basic iteration primitive. It iterates over all the entries in
pts->range that fall within the pts's current table level. Each step does
pt_load_entry(pts).

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

```c
enum pt_entry_type pt_load_single_entry(struct pt_state *pts)
```

Version of [`pt_load_entry()`](#c-pt_load_entry) usable within a walker

**Parameters**

- `struct pt_state *pts`: Iteration State

**Description**

Alternative to [`for_each_pt_level_entry()`](#c-for_each_pt_level_entry) if the walker function uses only a
single entry.

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

```c
struct pt_range pt_top_range(struct pt_common *common)
```

Return a range that spans part of the top level

**Parameters**

- `struct pt_common *common`: Table

**Description**

For PT_FEAT_SIGN_EXTEND this will return the lower range, and cover half the
total page table. Otherwise it returns the entire page table.

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

```c
struct pt_range pt_all_range(struct pt_common *common)
```

Return a range that spans the entire page table

**Parameters**

- `struct pt_common *common`: Table

**Description**

The returned range spans the whole page table. Due to how PT_FEAT_SIGN_EXTEND
is supported range->va and range->last_va will be incorrect during the
iteration and must not be accessed.

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

```c
struct pt_range pt_upper_range(struct pt_common *common)
```

Return a range that spans part of the top level

**Parameters**

- `struct pt_common *common`: Table

**Description**

For PT_FEAT_SIGN_EXTEND this will return the upper range, and cover half the
total page table. Otherwise it returns the entire page table.

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

```c
struct pt_range pt_make_range(struct pt_common *common, pt_vaddr_t va, pt_vaddr_t last_va)
```

Return a range that spans part of the table

**Parameters**

- `struct pt_common *common`: Table
- `pt_vaddr_t va`: Start address
- `pt_vaddr_t last_va`: Last address

**Description**

The caller must validate the range with [`pt_check_range()`](#c-pt_check_range) before using it.

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

```c
struct pt_state pt_init(struct pt_range *range, unsigned int level, struct pt_table_p *table)
```

Initialize a pt_state on the stack

**Parameters**

- `struct pt_range *range`: Range pointer to embed in the state
- `unsigned int level`: Table level for the state
- `struct pt_table_p *table`: Pointer to the table memory at level

**Description**

Helper to initialize the on-stack pt_state from walker arguments.

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

```c
struct pt_state pt_init_top(struct pt_range *range)
```

Initialize a pt_state on the stack

**Parameters**

- `struct pt_range *range`: Range pointer to embed in the state

**Description**

The pt_state points to the top most level.

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

```c
int pt_descend(struct pt_state *pts, void *arg, pt_level_fn_t fn)
```

Recursively invoke the walker for the lower level

**Parameters**

- `struct pt_state *pts`: Iteration State
- `void *arg`: Value to pass to the function
- `pt_level_fn_t fn`: Walker function to call

**Description**

pts must point to a table item. Invoke fn as a walker on the table
pts points to.

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

```c
int pt_walk_range(struct pt_range *range, pt_level_fn_t fn, void *arg)
```

Walk over a VA range

**Parameters**

- `struct pt_range *range`: Range pointer
- `pt_level_fn_t fn`: Walker function to call
- `void *arg`: Value to pass to the function

**Description**

Walk over a VA range. The caller should have done a validity check, at
least calling [`pt_check_range()`](#c-pt_check_range), when building range. The walk will
start at the top most table.

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

```c
struct pt_range pt_range_slice(const struct pt_state *pts, unsigned int start_index, unsigned int end_index)
```

Return a range that spans indexes

**Parameters**

- `const struct pt_state *pts`: Iteration State
- `unsigned int start_index`: Starting index within pts
- `unsigned int end_index`: Ending index within pts

**Description**

Create a range than spans an index range of the current table level
pt_state points at.

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

```c
unsigned int pt_top_memsize_lg2(struct pt_common *common, uintptr_t top_of_table)
```

**Parameters**

- `struct pt_common *common`: Table
- `uintptr_t top_of_table`: Top of table value from `_pt_top_set()`

**Description**

Compute the allocation size of the top table. For PT_FEAT_DYNAMIC_TOP this
will compute the top size assuming the table will grow.

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

```c
unsigned int pt_compute_best_pgsize(pt_vaddr_t pgsz_bitmap, pt_vaddr_t va, pt_vaddr_t last_va, pt_oaddr_t oa)
```

Determine the best page size for leaf entries

**Parameters**

- `pt_vaddr_t pgsz_bitmap`: Permitted page sizes
- `pt_vaddr_t va`: Starting virtual address for the leaf entry
- `pt_vaddr_t last_va`: Last virtual address for the leaf entry, sets the max page size
- `pt_oaddr_t oa`: Starting output address for the leaf entry

**Description**

Compute the largest page size for va, last_va, and oa together and return it
in lg2. The largest page size depends on the format's supported page sizes at
this level, and the relative alignment of the VA and OA addresses. 0 means
the OA cannot be stored with the provided pgsz_bitmap.

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

```c
PT_MAKE_LEVELS(fn, do_fn)
```

Build an unwound walker

**Parameters**

- `fn`: Name of the walker function
- `do_fn`: Function to call at each level

**Description**

This builds a function call tree that can be fully inlined.
The caller must provide a function body in an __always_inline function:

```text
static __always_inline int do_fn(struct pt_range *range, void *arg,
       unsigned int level, struct pt_table_p *table,
       pt_level_fn_t descend_fn)
```

An inline function will be created for each table level that calls do_fn with
a compile time constant for level and a pointer to the next lower function.
This generates an optimally inlined walk where each of the functions sees a
constant level and can codegen the exact constants/etc for that level.

Note this can produce a lot of code!


<a id="rst-writing-a-format"></a>

### Writing a Format

It is best to start from a simple format that is similar to the target. x86_64 is usually a good reference for something simple, and AMDv1 is something fairly complete.

The required inline functions need to be implemented in the format header. These should all follow the standard pattern of:



```text
static inline pt_oaddr_t amdv1pt_entry_oa(const struct pt_state *pts)
{
       [..]
}
#define pt_entry_oa amdv1pt_entry_oa
```

where a uniquely named per-format inline function provides the implementation and a define maps it to the generic name. This is intended to make debug symbols work better. inline functions should always be used as the prototypes in pt_common.h will cause the compiler to validate the function signature to prevent errors.

Review pt_fmt_defaults.h to understand some of the optional inlines.

Once the format compiles then it should be run through the generic page table kunit test in kunit_generic_pt.h using kunit. For example:



```text
$ tools/testing/kunit/kunit.py run --build_dir build_kunit_x86_64 --arch x86_64 --kunitconfig ./drivers/iommu/generic_pt/.kunitconfig amdv1_fmt_test.*
[...]
[11:15:08] Testing complete. Ran 9 tests: passed: 9
[11:15:09] Elapsed time: 3.137s total, 0.001s configuring, 2.368s building, 0.311s running
```

The generic tests are intended to prove out the format functions and give clearer failures to speed up finding the problems. Once those pass then the entire kunit suite should be run.

<a id="rst-iommu-invalidation-features"></a>

### IOMMU Invalidation Features

Invalidation is how the page table algorithms synchronize with a HW cache of the page table memory, typically called the TLB (or IOTLB for IOMMU cases).

The TLB can store present PTEs, non-present PTEs and table pointers, depending on its design. Every HW has its own approach on how to describe what has changed to have changed items removed from the TLB.

<a id="rst-pt-feat-flush-range"></a>

#### PT_FEAT_FLUSH_RANGE

PT_FEAT_FLUSH_RANGE is the easiest scheme to understand. It tries to generate a single range invalidation for each operation, over-invalidating if there are gaps of VA that don't need invalidation. This trades off impacted VA for number of invalidation operations. It does not keep track of what is being invalidated; however, if pages have to be freed then page table pointers have to be cleaned from the walk cache. The range can start/end at any page boundary.

<a id="rst-pt-feat-flush-range-no-gaps"></a>

#### PT_FEAT_FLUSH_RANGE_NO_GAPS

PT_FEAT_FLUSH_RANGE_NO_GAPS is similar to PT_FEAT_FLUSH_RANGE; however, it tries to minimize the amount of impacted VA by issuing extra flush operations. This is useful if the cost of processing VA is very high, for instance because a hypervisor is processing the page table with a shadowing algorithm.

---

# The io_mapping functions

_Peios Kernel / Hardware and drivers / Driver development / Device I/O and shared memory_

> The io_mapping functions in linux/io-mapping.h provide an abstraction for efficiently mapping small regions of an I/O device to the CPU. The initial usage is to support the large graphics aperture on 32-bit processors where ioremap_wc…

<a id="rst-the-io-mapping-functions"></a>

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

## API

The io_mapping functions in linux/io-mapping.h provide an abstraction for efficiently mapping small regions of an I/O device to the CPU. The initial usage is to support the large graphics aperture on 32-bit processors where ioremap_wc cannot be used to statically map the entire aperture to the CPU as it would consume too much of the kernel address space.

A mapping object is created during driver initialization using:



```text
struct io_mapping *io_mapping_create_wc(unsigned long base,
                                        unsigned long size)
```

'base' is the bus address of the region to be made mappable, while 'size' indicates how large a mapping region to enable. Both are in bytes.

This \_wc variant provides a mapping which may only be used with io_mapping_map_atomic_wc(), io_mapping_map_local_wc() or io_mapping_map_wc().

With this mapping object, individual pages can be mapped either temporarily or long term, depending on the requirements. Of course, temporary maps are more efficient. They come in two flavours:



```text
void *io_mapping_map_local_wc(struct io_mapping *mapping,
                              unsigned long offset)

void *io_mapping_map_atomic_wc(struct io_mapping *mapping,
                               unsigned long offset)
```

'offset' is the offset within the defined mapping region.  Accessing addresses beyond the region specified in the creation function yields undefined results. Using an offset which is not page aligned yields an undefined result. The return value points to a single page in CPU address space.

This \_wc variant returns a write-combining map to the page and may only be used with mappings created by io_mapping_create_wc()

Temporary mappings are only valid in the context of the caller. The mapping is not guaranteed to be globally visible.

io_mapping_map_local_wc() has a side effect on X86 32bit as it disables migration to make the mapping code work. No caller can rely on this side effect.

io_mapping_map_atomic_wc() has the side effect of disabling preemption and pagefaults. Don't use in new code. Use io_mapping_map_local_wc() instead.

Nested mappings need to be undone in reverse order because the mapping code uses a stack for keeping track of them:



```text
addr1 = io_mapping_map_local_wc(map1, offset1);
addr2 = io_mapping_map_local_wc(map2, offset2);
...
io_mapping_unmap_local(addr2);
io_mapping_unmap_local(addr1);
```

The mappings are released with:



```text
void io_mapping_unmap_local(void *vaddr)
void io_mapping_unmap_atomic(void *vaddr)
```

'vaddr' must be the value returned by the last io_mapping_map_local_wc() or io_mapping_map_atomic_wc() call. This unmaps the specified mapping and undoes the side effects of the mapping functions.

If you need to sleep while holding a mapping, you can use the regular variant, although this may be significantly slower:



```text
void *io_mapping_map_wc(struct io_mapping *mapping,
                        unsigned long offset)
```

This works like io_mapping_map_atomic/local_wc() except it has no side effects and the pointer is globally visible.

The mappings are released with:



```text
void io_mapping_unmap(void *vaddr)
```

Use for pages mapped with io_mapping_map_wc().

At driver close time, the io_mapping object must be freed:



```text
void io_mapping_free(struct io_mapping *mapping)
```

---

# Ordering I/O writes to memory-mapped addresses

_Peios Kernel / Hardware and drivers / Driver development / Device I/O and shared memory_

> On some platforms, so-called memory-mapped I/O is weakly ordered. On such platforms, driver writers are responsible for ensuring that I/O writes to memory-mapped addresses on their device arrive in the order intended. This is typically…

<a id="rst-ordering-i-o-writes-to-memory-mapped-addresses"></a>

On some platforms, so-called memory-mapped I/O is weakly ordered.  On such platforms, driver writers are responsible for ensuring that I/O writes to memory-mapped addresses on their device arrive in the order intended.  This is typically done by reading a 'safe' device or bridge register, causing the I/O chipset to flush pending writes to the device before any reads are posted.  A driver would usually use this technique immediately prior to the exit of a critical section of code protected by spinlocks.  This would ensure that subsequent writes to I/O space arrived only after all prior writes (much like a memory barrier op, mb(), only with respect to I/O).

A more concrete example from a hypothetical device driver:



```text
        ...
CPU A:  spin_lock_irqsave(&dev_lock, flags)
CPU A:  val = readl(my_status);
CPU A:  ...
CPU A:  writel(newval, ring_ptr);
CPU A:  spin_unlock_irqrestore(&dev_lock, flags)
        ...
CPU B:  spin_lock_irqsave(&dev_lock, flags)
CPU B:  val = readl(my_status);
CPU B:  ...
CPU B:  writel(newval2, ring_ptr);
CPU B:  spin_unlock_irqrestore(&dev_lock, flags)
        ...
```

In the case above, the device may receive newval2 before it receives newval, which could cause problems.  Fixing it is easy enough though:



```text
        ...
CPU A:  spin_lock_irqsave(&dev_lock, flags)
CPU A:  val = readl(my_status);
CPU A:  ...
CPU A:  writel(newval, ring_ptr);
CPU A:  (void)readl(safe_register); /* maybe a config register? */
CPU A:  spin_unlock_irqrestore(&dev_lock, flags)
        ...
CPU B:  spin_lock_irqsave(&dev_lock, flags)
CPU B:  val = readl(my_status);
CPU B:  ...
CPU B:  writel(newval2, ring_ptr);
CPU B:  (void)readl(safe_register); /* maybe a config register? */
CPU B:  spin_unlock_irqrestore(&dev_lock, flags)
```

Here, the reads from safe_register will cause the I/O chipset to flush any pending writes before actually posting the read to the chipset, preventing possible data corruption.

---

# ioctl based interfaces

_Peios Kernel / Hardware and drivers / Driver development / Device I/O and shared memory_

> ioctl() is the most common way for applications to interface with device drivers. It is flexible and easily extended by adding new commands and can be passed through character devices, block devices as well as sockets and other special…

<a id="rst-ioctl-based-interfaces"></a>

ioctl() is the most common way for applications to interface with device drivers. It is flexible and easily extended by adding new commands and can be passed through character devices, block devices as well as sockets and other special file descriptors.

However, it is also very easy to get ioctl command definitions wrong, and hard to fix them later without breaking existing applications, so this documentation tries to help developers get it right.

<a id="rst-command-number-definitions"></a>

## Command number definitions

The command number, or request number, is the second argument passed to the ioctl system call. While this can be any 32-bit number that uniquely identifies an action for a particular driver, there are a number of conventions around defining them.

`include/uapi/asm-generic/ioctl.h` provides four macros for defining ioctl commands that follow modern conventions: `_IO`, `_IOR`, `_IOW`, and `_IOWR`. These should be used for all new commands, with the correct parameters:

- **\_IO/\_IOR/\_IOW/\_IOWR**

  The macro name specifies how the argument will be used.  It may be a pointer to data to be passed into the kernel (\_IOW), out of the kernel (\_IOR), or both (\_IOWR).  \_IO can indicate either commands with no argument or those passing an integer value instead of a pointer. It is recommended to only use \_IO for commands without arguments, and use pointers for passing data.

- **type**

  An 8-bit number, often a character literal, specific to a subsystem or driver, and listed in [Documentation/userspace-api/ioctl/ioctl-number.rst](/kernel/userspace/userspace-api/ioctl/ioctl-number.md)

- **nr**

  An 8-bit number identifying the specific command, unique for a give value of 'type'

- **data_type**

  The name of the data type pointed to by the argument, the command number encodes the `sizeof(data_type)` value in a 13-bit or 14-bit integer, leading to a limit of 8191 bytes for the maximum size of the argument. Note: do not pass sizeof(data_type) type into \_IOR/\_IOW/IOWR, as that will lead to encoding sizeof(sizeof(data_type)), i.e. sizeof(size_t). \_IO does not have a data_type parameter.

<a id="rst-interface-versions"></a>

## Interface versions

Some subsystems use version numbers in data structures to overload commands with different interpretations of the argument.

This is generally a bad idea, since changes to existing commands tend to break existing applications.

A better approach is to add a new ioctl command with a new number. The old command still needs to be implemented in the kernel for compatibility, but this can be a wrapper around the new implementation.

<a id="rst-return-code"></a>

## Return code

ioctl commands can return negative error codes as documented in errno(3); these get turned into errno values in user space. On success, the return code should be zero. It is also possible but not recommended to return a positive 'long' value.

When the ioctl callback is called with an unknown command number, the handler returns either -ENOTTY or -ENOIOCTLCMD, which also results in -ENOTTY being returned from the system call. Some subsystems return -ENOSYS or -EINVAL here for historic reasons, but this is wrong.

Prior to Linux 5.5, compat_ioctl handlers were required to return -ENOIOCTLCMD in order to use the fallback conversion into native commands. As all subsystems are now responsible for handling compat mode themselves, this is no longer needed, but it may be important to consider when backporting bug fixes to older kernels.

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

## Timestamps

Traditionally, timestamps and timeout values are passed as `struct timespec` or `struct timeval`, but these are problematic because of incompatible definitions of these structures in user space after the move to 64-bit time_t.

The `struct __kernel_timespec` type can be used instead to be embedded in other data structures when separate second/nanosecond values are desired, or passed to user space directly. This is still not ideal though, as the structure matches neither the kernel's timespec64 nor the user space timespec exactly. The get_timespec64() and put_timespec64() helper functions can be used to ensure that the layout remains compatible with user space and the padding is treated correctly.

As it is cheap to convert seconds to nanoseconds, but the opposite requires an expensive 64-bit division, a simple \__u64 nanosecond value can be simpler and more efficient.

Timeout values and timestamps should ideally use CLOCK_MONOTONIC time, as returned by ktime_get_ns() or ktime_get_ts64().  Unlike CLOCK_REALTIME, this makes the timestamps immune from jumping backwards or forwards due to leap second adjustments and clock_settime() calls.

ktime_get_real_ns() can be used for CLOCK_REALTIME timestamps that need to be persistent across a reboot or between multiple machines.

<a id="rst-bit-compat-mode"></a>

## 32-bit compat mode

In order to support 32-bit user space running on a 64-bit machine, each subsystem or driver that implements an ioctl callback handler must also implement the corresponding compat_ioctl handler.

As long as all the rules for data structures are followed, this is as easy as setting the .compat_ioctl pointer to a helper function such as compat_ptr_ioctl() or blkdev_compat_ptr_ioctl().

<a id="rst-compat-ptr"></a>

### compat_ptr()

On the s390 architecture, 31-bit user space has ambiguous representations for data pointers, with the upper bit being ignored. When running such a process in compat mode, the compat_ptr() helper must be used to clear the upper bit of a compat_uptr_t and turn it into a valid 64-bit pointer.  On other architectures, this macro only performs a cast to a `void __user *` pointer.

In an compat_ioctl() callback, the last argument is an unsigned long, which can be interpreted as either a pointer or a scalar depending on the command. If it is a scalar, then compat_ptr() must not be used, to ensure that the 64-bit kernel behaves the same way as a 32-bit kernel for arguments with the upper bit set.

The compat_ptr_ioctl() helper can be used in place of a custom compat_ioctl file operation for drivers that only take arguments that are pointers to compatible data structures.

<a id="rst-structure-layout"></a>

### Structure layout

Compatible data structures have the same layout on all architectures, avoiding all problematic members:

- `long` and `unsigned long` are the size of a register, so they can be either 32-bit or 64-bit wide and cannot be used in portable data structures. Fixed-length replacements are `__s32`, `__u32`, `__s64` and `__u64`.

- Pointers have the same problem, in addition to requiring the use of compat_ptr(). The best workaround is to use `__u64` in place of pointers, which requires a cast to `uintptr_t` in user space, and the use of u64_to_user_ptr() in the kernel to convert it back into a user pointer.

- On the x86-32 (i386) architecture, the alignment of 64-bit variables is only 32-bit, but they are naturally aligned on most other architectures including x86-64. This means a structure like:



  ```text
  struct foo {
      __u32 a;
      __u64 b;
      __u32 c;
  };
  ```

  has four bytes of padding between a and b on x86-64, plus another four bytes of padding at the end, but no padding on i386, and it needs a compat_ioctl conversion handler to translate between the two formats.

  To avoid this problem, all structures should have their members naturally aligned, or explicit reserved fields added in place of the implicit padding. The `pahole` tool can be used for checking the alignment.

- On ARM OABI user space, structures are padded to multiples of 32-bit, making some structs incompatible with modern EABI kernels if they do not end on a 32-bit boundary.

- On the m68k architecture, struct members are not guaranteed to have an alignment greater than 16-bit, which is a problem when relying on implicit padding.

- Bitfields and enums generally work as one would expect them to, but some properties of them are implementation-defined, so it is better to avoid them completely in ioctl interfaces.

- `char` members can be either signed or unsigned, depending on the architecture, so the \__u8 and \__s8 types should be used for 8-bit integer values, though char arrays are clearer for fixed-length strings.

<a id="rst-information-leaks"></a>

## Information leaks

Uninitialized data must not be copied back to user space, as this can cause an information leak, which can be used to defeat kernel address space layout randomization (KASLR), helping in an attack.

For this reason (and for compat support) it is best to avoid any implicit padding in data structures.  Where there is implicit padding in an existing structure, kernel drivers must be careful to fully initialize an instance of the structure before copying it to user space.  This is usually done by calling memset() before assigning to individual members.

<a id="rst-subsystem-abstractions"></a>

## Subsystem abstractions

While some device drivers implement their own ioctl function, most subsystems implement the same command for multiple drivers.  Ideally the subsystem has an .ioctl() handler that copies the arguments from and to user space, passing them into subsystem specific callback functions through normal kernel pointers.

This helps in various ways:

- Applications written for one driver are more likely to work for another one in the same subsystem if there are no subtle differences in the user space ABI.

- The complexity of user space access and data structure layout is done in one place, reducing the potential for implementation bugs.

- It is more likely to be reviewed by experienced developers that can spot problems in the interface when the ioctl is shared between multiple drivers than when it is only used in a single driver.

<a id="rst-alternatives-to-ioctl"></a>

## Alternatives to ioctl

There are many cases in which ioctl is not the best solution for a problem. Alternatives include:

- System calls are a better choice for a system-wide feature that is not tied to a physical device or constrained by the file system permissions of a character device node

- netlink is the preferred way of configuring any network related objects through sockets.

- debugfs is used for ad-hoc interfaces for debugging functionality that does not need to be exposed as a stable interface to applications.

- sysfs is a good way to expose the state of an in-kernel object that is not tied to a file descriptor.

- configfs can be used for more complex configuration than sysfs

- A custom file system can provide extra flexibility with a simple user interface but adds a lot of complexity to the implementation.

---

# Sync File API Guide

_Peios Kernel / Hardware and drivers / Driver development / Device I/O and shared memory_

> This document serves as a guide for device drivers writers on what the sync_file API is, and how drivers can support it. Sync file is the carrier of the fences(struct dma_fence) that are needed to synchronize between drivers or across…

<a id="rst-sync-file-api-guide"></a>

**Author:** Gustavo Padovan &lt;gustavo at padovan dot org&gt;

This document serves as a guide for device drivers writers on what the sync_file API is, and how drivers can support it. Sync file is the carrier of the fences(struct dma_fence) that are needed to synchronize between drivers or across process boundaries.

The sync_file API is meant to be used to send and receive fence information to/from userspace. It enables userspace to do explicit fencing, where instead of attaching a fence to the buffer a producer driver (such as a GPU or V4L driver) sends the fence related to the buffer to userspace via a sync_file.

The sync_file then can be sent to the consumer (DRM driver for example), that will not use the buffer for anything before the fence(s) signals, i.e., the driver that issued the fence is not using/processing the buffer anymore, so it signals that the buffer is ready to use. And vice-versa for the consumer -&gt; producer part of the cycle.

Sync files allows userspace awareness on buffer sharing synchronization between drivers.

Sync file was originally added in the Android kernel but current Linux Desktop can benefit a lot from it.

<a id="rst-in-fences-and-out-fences"></a>

## in-fences and out-fences

Sync files can go either to or from userspace. When a sync_file is sent from the driver to userspace we call the fences it contains 'out-fences'. They are related to a buffer that the driver is processing or is going to process, so the driver creates an out-fence to be able to notify, through dma_fence_signal(), when it has finished using (or processing) that buffer. Out-fences are fences that the driver creates.

On the other hand if the driver receives fence(s) through a sync_file from userspace we call these fence(s) 'in-fences'. Receiving in-fences means that we need to wait for the fence(s) to signal before using any buffer related to the in-fences.

<a id="rst-creating-sync-files"></a>

## Creating Sync Files

When a driver needs to send an out-fence userspace it creates a sync_file.

Interface:



```text
struct sync_file *sync_file_create(struct dma_fence *fence);
```

The caller pass the out-fence and gets back the sync_file. That is just the first step, next it needs to install an fd on sync_file-&gt;file. So it gets an fd:



```text
fd = get_unused_fd_flags(O_CLOEXEC);
```

and installs it on sync_file-&gt;file:



```text
fd_install(fd, sync_file->file);
```

The sync_file fd now can be sent to userspace.

If the creation process fail, or the sync_file needs to be released by any other reason fput(sync_file-&gt;file) should be used.

<a id="rst-receiving-sync-files-from-userspace"></a>

## Receiving Sync Files from Userspace

When userspace needs to send an in-fence to the driver it passes file descriptor of the Sync File to the kernel. The kernel can then retrieve the fences from it.

Interface:



```text
struct dma_fence *sync_file_get_fence(int fd);
```

The returned reference is owned by the caller and must be disposed of afterwards using dma_fence_put(). In case of error, a NULL is returned instead.

References:

1. struct sync_file in include/linux/sync_file.h

2. All interfaces mentioned above defined in include/linux/sync_file.h
